-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb_util.py
executable file
·63 lines (53 loc) · 1.79 KB
/
db_util.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by Charles on 2018/6/16
# Function:
from pymongo import MongoClient
DB_INSTANCE = None
class DBUtil:
# __metaclass__ = Singleton
__instance = None
def __new__(cls, *args, **kwargs):
if not cls.__instance:
cls.__instance = super(DBUtil, cls).__new__(cls, *args, **kwargs)
return cls.__instance
def __init__(self, host="127.0.0.1", port=27017, db_name="Huobi", user=None, password=None):
self._host = host
self._port = port
self._db_name = db_name
self._client = None
self._db = None
self._user = user
self._password = password
def init(self):
print("init database!")
try:
self._client = MongoClient(self._host, self._port)
self._db = self._client[self._db_name]
if self._user and self._password:
self._db.authenticate(self._user, self._password)
print("init database successfully!")
return True
except Exception as e:
print("Catch an exception duration database connection. exception: %s" % e)
self.close_db()
return False
#raise (Exception("数据库连接失败!"))
def close(self):
print("close database!")
if self._client:
self._client.close()
self._client = None
self._db = None
return True
def is_valid(self):
return self._client and self._db
@property
def db(self):
return self._db
if __name__ == '__main__':
dbutil = DBUtil()
dbutil.init()
clc = dbutil.db.get_collection("test")
clc.insert_one({"user": "charles1", "age": 30})
dbutil.close()