-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmongodb_utils.py
82 lines (70 loc) · 2.67 KB
/
mongodb_utils.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 27 10:03:22 2020
@author: DLituiev
"""
import yaml
import logging
from pymongo import MongoClient
from pymongo.errors import ConnectionFailure, OperationFailure
from pymongo import errors as mongoerrors
from .credentials import get_credentials
def get_mongo_handle(url=None, ip=None, server=None, port=27017,
username=None, password=None, db=None, **kwargs):
client = MongoClient(url or ip or server,
port=port,
username=username,
password=password,
**kwargs)
# try a basic server operation
client.server_info()['version']
if db is not None:
try:
dbconn = client[db]
except Exception as err:
print("Mongo database {} is not available in this connection".format(db))
print(mongoerrors.__dict__.keys())
raise err
return dbconn
else:
return client
def connect_mongodb(configfile, reset=False, **kwargs):
"""Connect to a mongodb given a YAML config file.
Credentials are requested or retrieved from keyring separately.
The YAML file must contain following:
url: mongodb://10.20.30.40:27017
db: 'databasename'
Alternatively / optionally to URL, server / ip and port can be provided:
server: xyz.company.org
port: 27017
ip: 10.20.30.40
Optional keyword arguments:
db -- database name
name -- name of credentials entry
"""
with open(configfile) as fh:
dbconfig = yaml.load(fh, Loader=yaml.SafeLoader)
kwargs = {kk.lower():vv for kk,vv in kwargs.items()}
dbconfig.update(**kwargs)
if 'server' not in dbconfig:
dbconfig['server'] = (dbconfig["url"]
.replace("mongodb://","")
.split("/")[0].split(":")[0]
)
name = dbconfig['name'] if ('name' in dbconfig) else dbconfig['server']
windows_info="Credential type: A Web site or program credential"
while True:
username, pwd = get_credentials(name, reset=reset, windows_info=windows_info)
try:
db = get_mongo_handle(username=username,
password=pwd,
**dbconfig)
break
except OperationFailure as ee:
logging.warning(str(ee))
logging.debug(f"credentials name: {name}")
logging.debug(f"username: {username}")
if not 'Authentication failed' in str(ee):
raise ee
reset=True
return db