This repository has been archived by the owner on Dec 26, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
db.py
57 lines (44 loc) · 1.81 KB
/
db.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
import copy
from time import sleep
from pymongo import MongoClient
from log import log
class Database:
def __init__(self, host=None, port=27017, db='tester', username=None, password=None):
# collection name definitions
RESULTS_COLLECTION = 'results'
RATELIMIT_COLLECTION = 'rate-limits'
log.info('Connecting to %s:%d', host, port)
log.info('Using Database `%s`', db)
# client and DB
self.client = MongoClient(host, port, serverSelectionTimeoutMS=3, username=username, password=password)
self.db = self.client[db]
# collections
self.results = self.db[RESULTS_COLLECTION]
self.rate_limits = self.db[RATELIMIT_COLLECTION]
# Test connection immediately, instead of
# when trying to write in a request, later.
self.client.admin.command('ismaster')
def write_result(self, result):
# copy.deepcopy; otherwise mongo ObjectId (_id) would be added,
# screwing up later JSON serialisation of results
self.results.insert_one(copy.deepcopy(result))
def write_rate_limit(self, data):
self.rate_limits.insert_one(data)
def close(self):
self.client.close()
def connect(host=None, port=27017, db='tester', username=None, password=None):
if host is None:
raise ValueError('Database constructor needs a `host`name or ip!')
attempt = 0
max_attempts = 7
mongo_client = None
while (mongo_client is None):
try:
mongo_client = Database(host=host, port=port, db=db, username=username, password=password)
except Exception as e:
if attempt is max_attempts:
raise e
sleep(attempt)
attempt += 1
log.warn('Retrying connection, %s/%s', attempt, max_attempts)
return mongo_client