-
Notifications
You must be signed in to change notification settings - Fork 1
/
connection.py
46 lines (36 loc) · 1.13 KB
/
connection.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
import json
import pymongo
CONFIG_PREFIX = "connection"
MONGODB = "local"
# MONGODB = "remote"
def singleton(cls, *args, **kw):
instances = {}
def _singleton():
if cls not in instances:
instances[cls] = cls(*args, **kw)
return instances[cls]
return _singleton
@singleton
class MongoConnection:
def __init__(self):
config_file = "_".join([CONFIG_PREFIX, MONGODB]) + ".json"
with open(config_file) as f:
config = json.load(f)
f.close()
user = config.get("user", "")
password = config.get("password", "")
if user and password:
self._host = "mongodb://%s:%s@%s" % (config["user"], config["password"], config["host"])
else:
self._host = "mongodb://%s" % config["host"]
self._port = config["port"]
self._client = pymongo.MongoClient(host=self._host, port=self._port)
@property
def client(self):
return self._client
@property
def db(self):
return self.client.get_database("model")
@property
def collection(self):
return self.db.get_collection("strategy")