summaryrefslogtreecommitdiffstats
path: root/ogcp/og_server.py
blob: 07ee6825bf12b8bb2b5cc8d4d8a9a4d9dc852fe6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# Copyright (C) 2020-2024 Soleta Networks <info@soleta.eu>
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the
# Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.

from ogcp import app

import requests
import json

class OGServer:
    def __init__(self, name, ip, port, api_token):
        self.name = name
        self.ip = ip
        self.port = port
        self.api_token = api_token
        self._prepare_requests()

    def _prepare_requests(self):
        self.URL = f'http://{self.ip}:{self.port}'
        self.HEADERS = {'Authorization' : self.api_token}

    def get(self, path, payload=None):
        try:
            r = requests.get(f'{self.URL}{path}',
                             headers=self.HEADERS,
                             json=payload)
        except requests.exceptions.ConnectionError:
            return None
        return r

    def post(self, path, payload):
        r = requests.post(f'{self.URL}{path}',
                          headers=self.HEADERS,
                          json=payload)
        return r

    def delete(self, path, payload):
        r = requests.delete(f'{self.URL}{path}',
                            headers=self.HEADERS,
                            json=payload)
        return r

    @property
    def id(self):
        ip = self.ip.replace('.', '-')
        return f'server_{ip}_{self.port}'


servers = []
if {'IP', 'PORT', 'API_TOKEN'} <= app.config.keys():
    # Config file backward compatibility
    servers.append(OGServer(app.config['IP'],
                            app.config['IP'],
                            app.config['PORT'],
                            app.config['API_TOKEN']))
if app.config.get('SERVERS'):
    for server in app.config['SERVERS']:
        ogserver = OGServer(server['NAME'],
                            server['IP'],
                            server['PORT'],
                            server['API_TOKEN'])
        servers.append(ogserver)