在写接口的时候,因为当初的弱智,没有选择 Flask-PyMongo 等库在初始化 app 的时候一并初始化 mongo 示例,而是在每个接口里创建一个 mongoClient。。
mongo = MongoClient(mongo_uri, connect=False)
最近新业务里,需要一个会被频繁访问,且会进行数据库查询的接口。
```
# 这是逻辑函数的开始
device_id = query_data['deviceId']
collection = mongo.app.user
user_data = collection.find_one({"deviceId": device_id})
# 后面还有很多但是没有必要所以省略了
```
然后发现该接口会偶尔出现下面的报错信息,但是其他会使用到 Mongo 的接口却没有出现过这个问题。报错信息如下:
```
Traceback (most recent call last):
File "/root/py27test/lib/python2.7/site-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/root/py27test/lib/python2.7/site-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/root/py27test/lib/python2.7/site-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/root/py27test/lib/python2.7/site-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/root/py27test/lib/python2.7/site-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
# 这里是接口的部分
File "./utils/v5.py", line 47, in decorated_function
return f(*args, **kwargs)
File "./utils/v5.py", line 1081, in user_function
data, error_message = query_module.query(query_data, mongo)
File "./fetcher/tools_v4.py", line 81, in user_query
user_data = collection.find_one({"deviceId": device_id})
# 接口的部分结束
File "/root/py27test/lib/python2.7/site-packages/pymongo/collection.py", line 1262, in find_one
for result in cursor.limit(-1):
File "/root/py27test/lib/python2.7/site-packages/pymongo/cursor.py", line 1189, in next
if len(self.__data) or self._refresh():
File "/root/py27test/lib/python2.7/site-packages/pymongo/cursor.py", line 1087, in _refresh
self.__session = self.__collection.database.client._ensure_session()
File "/root/py27test/lib/python2.7/site-packages/pymongo/mongo_client.py", line 1558, in _ensure_session
return self.__start_session(True, causal_consistency=False)
File "/root/py27test/lib/python2.7/site-packages/pymongo/mongo_client.py", line 1511, in __start_session
server_session = self._get_server_session()
File "/root/py27test/lib/python2.7/site-packages/pymongo/mongo_client.py", line 1544, in _get_server_session
return self._topology.get_server_session()
File "/root/py27test/lib/python2.7/site-packages/pymongo/topology.py", line 427, in get_server_session
None)
File "/root/py27test/lib/python2.7/site-packages/pymongo/topology.py", line 199, in _select_servers_loop
self._error_message(selector))
ServerSelectionTimeoutError: No servers found yet
```
[汗]搜索了 stackoverflow 的解决方法一个是connect=False
,另一个是在 fork 前等待两秒。似乎不太适用,猛男落泪,所以来求助一哈各位大佬。
Python:2.7.5 PyMongo:3.7.1
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.