简体   繁体   English

烧瓶上的 PyMongo

[英]PyMongo on the Flask

I'm curious if this is right working.我很好奇这是否正确工作。

In case of using MySQL , both connecting and closing are done per one request.在使用MySQL 的情况下,每个请求都完成连接和关闭。

1st request: connect, close第一个请求:连接,关闭
2nd request: connect, close第二个请求:连接,关闭
3rd request: connect, close第三个请求:连接,关闭
4th request: connect, close第四个请求:连接,关闭
5th request: connect, close第 5 个请求:连接、关闭

every requests bring both connect and close每个请求都带来连接和关闭
This is how I manage MySQL connection and think many of other developer do like this.这就是我管理 MySQL 连接的方式,并认为许多其他开发人员也是这样做的。

BUT..但..

In case of using mongodb with PyMongo module , it works not like above.如果将mongodb 与 PyMongo 模块一起使用,它的工作方式与上面不同。

1st request: connect第一个请求:连接
2nd request: connect第二个请求:连接
3rd request: (use connection of 1st or 2nd) <= Do not connect but use previous connection第三个请求:(使用第一个或第二个连接)<= 不连接但使用以前的连接
4th request: (use connection of 1st or 2nd) <= same第四个请求:(使用第一个或第二个连接)<=相同
5th request: (use connection of 1st or 2nd) <= same第 5 个请求:(使用第 1 个或第 2 个连接)<= 相同

Does this keep the connection in app.config and use on after request?这是否在 app.config 中保持连接并在请求后使用?
I feel How it works is very difficult from managing connection of MySQL.我觉得从管理 MySQL 的连接来看它是如何工作的非常困难。
Is this normal working?这是正常工作吗?
Doesn't it need to close the connection after using?使用后不需要关闭连接吗?

from flask import Flask
from flask_pymongo import PyMongo
app = Flask(__name__)

app.config['MONGO_HOST'] = '127.0.0.1'
app.config['MONGO_PORT'] = 27017
app.config['MONGO_DBNAME'] = 'test'
mongo = PyMongo(app, config_prefix='MONGO')

@app.route('/')
def test():
    mongo.db.user.insert({'name':'test'})
    return 'test'

if __name__ == '__main__':
    app.run()

Thank you for read.感谢您阅读。

You don't need to close PyMongo connections.您不需要关闭 PyMongo 连接。 Leave them open so that PyMongo's connection pooling gives you the most efficient performance:让它们保持打开状态,以便 PyMongo 的连接池为您提供最高效的性能:

https://pymongo.readthedocs.io/en/stable/faq.html#how-does-connection-pooling-work-in-pymongo https://pymongo.readthedocs.io/en/stable/faq.html#how-does-connection-pooling-work-in-pymongo

Your code, above, is correct.你上面的代码是正确的。 Create one "PyMongo" instance and reuse it throughout your application.创建一个“PyMongo”实例并在整个应用程序中重复使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM