Skip to content

Commit fc0ca13

Browse files
committed
mongo 支持 url连接方式
1 parent 31d78ea commit fc0ca13

2 files changed

Lines changed: 56 additions & 44 deletions

File tree

feapder/db/mongodb.py

Lines changed: 36 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -23,49 +23,59 @@
2323

2424
class MongoDB:
2525
def __init__(
26-
self, ip=None, port=None, db=None, user_name=None, user_pass=None, **kwargs
26+
self,
27+
ip=None,
28+
port=None,
29+
db=None,
30+
user_name=None,
31+
user_pass=None,
32+
url=None,
33+
**kwargs,
2734
):
28-
if not ip:
29-
ip = setting.MONGO_IP
30-
if not port:
31-
port = setting.MONGO_PORT
32-
if not db:
33-
db = setting.MONGO_DB
34-
if not user_name:
35-
user_name = setting.MONGO_USER_NAME
36-
if not user_pass:
37-
user_pass = setting.MONGO_USER_PASS
38-
39-
self.client = MongoClient(
40-
host=ip, port=port, username=user_name, password=user_pass
41-
)
35+
if url:
36+
self.client = MongoClient(url, **kwargs)
37+
else:
38+
if not ip:
39+
ip = setting.MONGO_IP
40+
if not port:
41+
port = setting.MONGO_PORT
42+
if not db:
43+
db = setting.MONGO_DB
44+
if not user_name:
45+
user_name = setting.MONGO_USER_NAME
46+
if not user_pass:
47+
user_pass = setting.MONGO_USER_PASS
48+
self.client = MongoClient(
49+
host=ip, port=port, username=user_name, password=user_pass
50+
)
51+
4252
self.db = self.get_database(db)
4353

4454
# 缓存索引信息
4555
self.__index__cached = {}
4656

4757
@classmethod
4858
def from_url(cls, url, **kwargs):
49-
# mongodb://username:password@ip:port/db
59+
"""
60+
Args:
61+
url: mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
62+
参考:http://mongodb.github.io/mongo-java-driver/3.4/javadoc/com/mongodb/MongoClientURI.html
63+
**kwargs:
64+
65+
Returns:
66+
67+
"""
5068
url_parsed = parse.urlparse(url)
5169

5270
db_type = url_parsed.scheme.strip()
5371
if db_type != "mongodb":
5472
raise Exception(
55-
"url error, expect mongodb://username:password@ip:port/db, but get {}".format(
73+
"url error, expect mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]], but get {}".format(
5674
url
5775
)
5876
)
5977

60-
connect_params = {}
61-
connect_params["ip"] = url_parsed.hostname.strip()
62-
connect_params["port"] = url_parsed.port
63-
connect_params["user_name"] = url_parsed.username.strip()
64-
connect_params["user_pass"] = url_parsed.password.strip()
65-
connect_params["db"] = url_parsed.path.strip("/").strip()
66-
67-
connect_params.update(kwargs)
68-
return cls(**connect_params)
78+
return cls(url=url, **kwargs)
6979

7080
def get_database(self, database, **kwargs) -> Database:
7181
"""

tests/test_mongodb.py

Lines changed: 20 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2,26 +2,28 @@
22

33
from feapder.db.mongodb import MongoDB
44

5-
db = MongoDB(ip="localhost", port=27017, db="feapder")
6-
75

86
class TestMongoDB(unittest.TestCase):
97
coll_name = "test"
108

9+
def setUp(self) -> None:
10+
# self.db = MongoDB(ip="localhost", port=27017, db="feapder")
11+
self.db = MongoDB.from_url("mongodb://localhost:27017/feapder")
12+
1113
def test_create_index(self):
12-
db.drop_collection(coll_name=self.coll_name)
13-
db.create_index(self.coll_name, ["a", "b"])
14+
self.db.drop_collection(coll_name=self.coll_name)
15+
self.db.create_index(self.coll_name, ["a", "b"])
1416

1517
def test_get_indexx(self):
16-
index = db.get_index(self.coll_name)
18+
index = self.db.get_index(self.coll_name)
1719
print(index)
1820

1921
def test_find(self):
2022
"""
2123
查询数据
2224
@return:
2325
"""
24-
r = db.find(
26+
r = self.db.find(
2527
coll_name=self.coll_name, limit=2, condition={"a": 1}, projection={"_id": 0}
2628
)
2729
print(r)
@@ -30,15 +32,15 @@ def test_insert(self):
3032
"""
3133
插入单条数据
3234
"""
33-
r = db.add(coll_name=self.coll_name, data={"a": 1, "b": "你好", "c": "哈哈"})
35+
r = self.db.add(coll_name=self.coll_name, data={"a": 1, "b": "你好", "c": "哈哈"})
3436
print(r)
3537
self.assertEqual(r, 1)
3638

3739
def test_insert_replace(self):
3840
"""
3941
插入单条数据,冲突时自动更新,即将重复数据替换为最新数据
4042
"""
41-
r = db.add(
43+
r = self.db.add(
4244
coll_name=self.coll_name, data={"a": 1, "b": "你好", "c": "啦啦"}, replace=True
4345
)
4446
self.assertEqual(r, 1)
@@ -47,7 +49,7 @@ def test_insert_columns(self):
4749
"""
4850
插入单条数据,发生冲突时,更新指定字段
4951
"""
50-
r = db.add(
52+
r = self.db.add(
5153
coll_name=self.coll_name,
5254
data={"a": 1, "b": "你好", "c": "666"},
5355
update_columns=("c",),
@@ -58,7 +60,7 @@ def test_insert_update_columns_value(self):
5860
"""
5961
插入单条数据,发生冲突时,用指定的值更新指定字段
6062
"""
61-
r = db.add(
63+
r = self.db.add(
6264
coll_name=self.coll_name,
6365
data={"a": 1, "b": "你好", "c": "666"},
6466
update_columns=("c",),
@@ -72,7 +74,7 @@ def test_batch_insert(self):
7274
@return:
7375
"""
7476
items = [{"a": 1, "b": "你好", "c": "666"}, {"a": 2, "b": "他好", "c": "888"}]
75-
add_count = db.add_batch(self.coll_name, items)
77+
add_count = self.db.add_batch(self.coll_name, items)
7678
datas_size = len(items)
7779
print("共导出 %s 条数据 到 %s, 重复 %s 条" % (datas_size, "test", datas_size - add_count))
7880

@@ -82,7 +84,7 @@ def test_batch_insert_replace(self):
8284
@return:
8385
"""
8486
items = [{"a": 1, "b": "你好", "c": "xixixi"}, {"a": 2, "b": "他好", "c": "777"}]
85-
add_count = db.add_batch(self.coll_name, items, replace=True)
87+
add_count = self.db.add_batch(self.coll_name, items, replace=True)
8688
datas_size = len(items)
8789
print("共导出 %s 条数据 到 %s, 重复 %s 条" % (datas_size, "test", datas_size - add_count))
8890
self.assertEqual(add_count, 0)
@@ -92,7 +94,7 @@ def test_batch_insert_update_columns(self):
9294
当数据冲突时,更新指定字段
9395
"""
9496
items = [{"a": 1, "b": "你好", "c": "88"}, {"a": 2, "b": "他好", "c": "888"}]
95-
add_count = db.add_batch(self.coll_name, items, update_columns=("c",))
97+
add_count = self.db.add_batch(self.coll_name, items, update_columns=("c",))
9698
datas_size = len(items)
9799
print("共导出 %s 条数据 到 %s, 重复 %s 条" % (datas_size, "test", datas_size - add_count))
98100
self.assertEqual(add_count, 0)
@@ -103,7 +105,7 @@ def test_batch_insert_update_columns_value(self):
103105
当数据重复时, 用指定的值更新指定字段
104106
"""
105107
items = [{"a": 1, "b": "你好", "c": "88"}, {"a": 2, "b": "他好", "c": "888"}]
106-
add_count = db.add_batch(
108+
add_count = self.db.add_batch(
107109
self.coll_name, items, update_columns=("c",), update_columns_value=("haha",)
108110
)
109111
datas_size = len(items)
@@ -115,23 +117,23 @@ def test_update(self):
115117
测试单条数据更新
116118
"""
117119
data = {"a": 1, "b": "你好", "c": "666"}
118-
r = db.update(self.coll_name, data, {"a": 1})
120+
r = self.db.update(self.coll_name, data, {"a": 1})
119121
self.assertEqual(r, True)
120122

121123
def test_delete(self):
122-
r = db.delete(self.coll_name, {"a": 1})
124+
r = self.db.delete(self.coll_name, {"a": 1})
123125
self.assertEqual(r, True)
124126

125127
def test_run_command(self):
126128
"""
127129
测试运行指令
128130
@return:
129131
"""
130-
r = db.run_command({"find": self.coll_name, "filter": {}})
132+
r = self.db.run_command({"find": self.coll_name, "filter": {}})
131133
print(r)
132134

133135
def test_drop_collection(self):
134-
r = db.drop_collection(self.coll_name)
136+
r = self.db.drop_collection(self.coll_name)
135137
print(r)
136138

137139

0 commit comments

Comments
 (0)