-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfetch.py
62 lines (55 loc) · 2.04 KB
/
fetch.py
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
#!/usr/bin/python3
import requests
from cachecontrol import CacheControl # type: ignore
from cachecontrol.caches.file_cache import FileCache # type: ignore
import sys
import time
import config
config=config.Config().config
class _Singleton(type):
"""
Define an Instance operation that lets clients access its unique
instance.
"""
def __init__(cls, name, bases, attrs, **kwargs):
super().__init__(name, bases, attrs)
cls._instance = None
def __call__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__call__(*args, **kwargs)
return cls._instance
class Fetcher(metaclass=_Singleton):
def __init__(self):
cachefile = f"{config['cachedir']}/requests"
self._cached_sess = CacheControl(requests.Session(),
cache=FileCache(cachefile))
def get(self, *args, **kwargs):
try:
return self._cached_sess.get(*args, **kwargs)
except requests.exceptions.Timeout as errc:
print ("Timeout:",errc)
time.sleep(1)
return self.get(*args, **kwargs)
except requests.exceptions.ConnectionError as errc:
print ("Error Connecting:",errc)
time.sleep(1)
return self.get(*args, **kwargs)
except requests.exceptions.RequestException as e:
# catastrophic error. bail.
print(e, flush=True)
sys.exit(1)
def head(self, *args, **kwargs):
try:
return self._cached_sess.head(*args, **kwargs)
except requests.exceptions.Timeout as errc:
print ("Timeout:",errc)
time.sleep(1)
return self.head(*args, **kwargs)
except requests.exceptions.ConnectionError as errc:
print ("Error Connecting:",errc)
time.sleep(1)
return self.head(*args, **kwargs)
except requests.exceptions.RequestException as e:
# catastrophic error. bail.
print(e, flush=True)
sys.exit(1)