-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask_runner.py
More file actions
37 lines (33 loc) · 1.21 KB
/
task_runner.py
File metadata and controls
37 lines (33 loc) · 1.21 KB
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
import socket
import urllib.request
import urllib.error
import json
import time
class NetworkClient:
def __init__(self):
self.timeout = 10
self.retries = 3
self.agent = 'PyDist/6.2.8'
def fetch_json(self, url):
req = urllib.request.Request(url, headers={'User-Agent': self.agent})
for attempt in range(self.retries):
try:
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
return json.loads(resp.read().decode('utf-8'))
except:
if attempt == self.retries - 1:
raise
time.sleep(0.5 * (attempt + 1))
return None
def fetch_text(self, url):
req = urllib.request.Request(url, headers={'User-Agent': self.agent})
for attempt in range(self.retries):
try:
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
return resp.read().decode('utf-8').strip()
except:
if attempt == self.retries - 1:
raise
time.sleep(0.5 * (attempt + 1))
return None
client = NetworkClient()