Projekt

Obecné

Profil

Stáhnout (1.81 KB) Statistiky
| Větev: | Tag: | Revize:
1 7a278c5c silhavyj
import json
2
import requests
3
import logging
4 76b68bb9 silhavyj
from time import sleep
5
from diskcache import Deque
6 7a278c5c silhavyj
from requests import HTTPError, ConnectionError
7 86c76cca silhavyj
from requests.exceptions import InvalidSchema
8 7a278c5c silhavyj
9 474551ae silhavyj
_uri = None
10
_cache = None
11
_config = None
12 d1528a79 silhavyj
13 474551ae silhavyj
14
def api_client_set_config(config):
15
    global _config, _cache, _uri
16
    _config = config
17 86c76cca silhavyj
    _cache = _init_cache()
18 474551ae silhavyj
    _uri = config.server_url + ":" + config.server_port + config.server_endpoint
19 7a278c5c silhavyj
20
21 86c76cca silhavyj
def _init_cache():
22
    return Deque(directory=_config.cache_dir)
23
24
25 7a278c5c silhavyj
def send_data(payload: dict):
26 86c76cca silhavyj
    if _uri is None:
27
        logging.warning(f"sending payload = {payload} failed because uri is set to None")
28
        _cache_failed_payload(payload)
29
        return
30 7a278c5c silhavyj
    try:
31
        logging.info(f"sending payload = {payload} to {_uri}")
32
        response = requests.post(url=_uri, data=json.dumps(payload))
33
        logging.info(f"response text: {response.text}")
34 86c76cca silhavyj
    except (ConnectionError, InvalidSchema):
35 7a278c5c silhavyj
        logging.warning(f"sending payload = {payload} to {_uri} failed")
36 957aac06 silhavyj
        _cache_failed_payload(payload)
37 7a278c5c silhavyj
    except HTTPError as error:
38
        logging.error(f"HTTP Error ({_uri}) payload = {payload}, {error}")
39 957aac06 silhavyj
        _cache_failed_payload(payload)
40
41
42
def _cache_failed_payload(payload: dict):
43 474551ae silhavyj
    if len(_cache) >= _config.cache_max_entries:
44 957aac06 silhavyj
        oldest_payload = _cache.pop()
45
        logging.warning(f"cache is full - discarding payload = {oldest_payload}")
46
47
    logging.info(f"adding payload = {payload} into cache")
48
    _cache.append(payload)
49 76b68bb9 silhavyj
50
51 474551ae silhavyj
def _resend_cached_payloads():
52 86c76cca silhavyj
    retries = min(_config.max_retries, len(_cache))
53 474551ae silhavyj
    logging.info(f"emptying the cache ({retries} records)")
54
    for _ in range(0, retries):
55
        payload = _cache.pop()
56
        send_data(payload)
57
58
59 76b68bb9 silhavyj
def api_client_run():
60
    while True:
61 474551ae silhavyj
        _resend_cached_payloads()
62
        sleep(_config.cache_retry_period_seconds)