/
client.py
64 lines (52 loc) · 1.52 KB
/
client.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
63
64
"""
client.py
Establish a connection to the database
"""
import logging
from pymongo import MongoClient
from pymongo.errors import ConnectionFailure, ServerSelectionTimeoutError
try:
# Python 3.x
from urllib.parse import quote_plus
except ImportError:
# Python 2.x
from urllib import quote_plus
LOG = logging.getLogger(__name__)
def get_connection(
host="localhost",
port=27017,
username=None,
password=None,
uri=None,
mongodb=None,
authdb=None,
timeout=20,
*args,
**kwargs
):
"""Get a client to the mongo database
host(str): Host of database
port(int): Port of database
username(str)
password(str)
uri(str)
authdb (str): database to use for authentication
timeout(int): How long should the client try to connect
"""
authdb = authdb or mongodb
if uri is None:
if username and password:
uri = "mongodb://{}:{}@{}:{}/{}".format(
quote_plus(username), quote_plus(password), host, port, authdb
)
log_uri = "mongodb://{}:****@{}:{}/{}".format(quote_plus(username), host, port, authdb)
else:
log_uri = uri = "mongodb://%s:%s" % (host, port)
LOG.info("Try to connect to %s" % log_uri)
try:
client = MongoClient(uri, serverSelectionTimeoutMS=timeout)
except ServerSelectionTimeoutError as err:
LOG.warning("Connection Refused")
raise ConnectionFailure
LOG.info("Connection established")
return client