Projekt

Obecné

Profil

Stáhnout (1.81 KB) Statistiky
| Větev: | Tag: | Revize:
1
import json
2
import requests
3
import logging
4
from time import sleep
5
from diskcache import Deque
6
from requests import HTTPError, ConnectionError
7
from requests.exceptions import InvalidSchema
8

    
9
_uri = None
10
_cache = None
11
_config = None
12

    
13

    
14
def api_client_set_config(config):
15
    global _config, _cache, _uri
16
    _config = config
17
    _cache = _init_cache()
18
    _uri = config.server_url + ":" + config.server_port + config.server_endpoint
19

    
20

    
21
def _init_cache():
22
    return Deque(directory=_config.cache_dir)
23

    
24

    
25
def send_data(payload: dict):
26
    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
    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
    except (ConnectionError, InvalidSchema):
35
        logging.warning(f"sending payload = {payload} to {_uri} failed")
36
        _cache_failed_payload(payload)
37
    except HTTPError as error:
38
        logging.error(f"HTTP Error ({_uri}) payload = {payload}, {error}")
39
        _cache_failed_payload(payload)
40

    
41

    
42
def _cache_failed_payload(payload: dict):
43
    if len(_cache) >= _config.cache_max_entries:
44
        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

    
50

    
51
def _resend_cached_payloads():
52
    retries = min(_config.max_retries, len(_cache))
53
    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
def api_client_run():
60
    while True:
61
        _resend_cached_payloads()
62
        sleep(_config.cache_retry_period_seconds)
(1-1/3)