-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathcfbot_util.py
More file actions
75 lines (62 loc) · 2.06 KB
/
cfbot_util.py
File metadata and controls
75 lines (62 loc) · 2.06 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
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
66
67
68
69
70
71
72
73
74
75
import cfbot_config
import pg8000
import requests
import time
import json
global_http_session = None
def get_http_session():
"""A session allowing for HTTP connection reuse."""
global global_http_session
if global_http_session is None:
global_http_session = requests.Session()
return global_http_session
def slow_fetch(url, none_for_404=False):
"""Fetch the body of a web URL, but sleep every time too to be kind to the
commitfest server."""
response = get_http_session().get(
url,
headers={"User-Agent": cfbot_config.USER_AGENT},
timeout=cfbot_config.TIMEOUT,
)
if response.status_code == 404 and none_for_404:
return None
response.raise_for_status()
time.sleep(cfbot_config.SLOW_FETCH_SLEEP)
return response.text
def slow_fetch_binary(url, none_for_404=False):
"""Fetch the body of a web URL, but sleep every time too to be kind to the
commitfest server."""
response = get_http_session().get(
url,
headers={"User-Agent": cfbot_config.USER_AGENT},
timeout=cfbot_config.TIMEOUT,
)
if response.status_code == 404 and none_for_404:
return None
response.raise_for_status()
time.sleep(cfbot_config.SLOW_FETCH_SLEEP)
return response.content
def slow_fetch_json(url, none_for_404=False):
"""Fetch the body of a web URL, but sleep every time too to be kind to the
commitfest server."""
response = get_http_session().get(
url,
headers={"User-Agent": cfbot_config.USER_AGENT},
timeout=cfbot_config.TIMEOUT,
)
if response.status_code == 404 and none_for_404:
return None
response.raise_for_status()
time.sleep(cfbot_config.SLOW_FETCH_SLEEP)
return json.loads(response.content)
def post(url, d):
response = get_http_session().post(
url,
headers={"User-Agent": cfbot_config.USER_AGENT},
json=d,
timeout=cfbot_config.TIMEOUT,
)
response.raise_for_status()
def db():
"""Get a database connection."""
return pg8000.connect(cfbot_config.DSN)