How to create a pymongo connection for a request in Flask

In my Flask application, I hope to use pymongo directly. But I'm not sure what is the best way to create a pymongo connection for each request and how to restore the connection resource.

I know that the connection in pymongo is thread safe and has a built-in pool. I think I need to create a global instance of Connection and use before_request to put it in the g bulb.

In app.py:

from pymongo import Connection from admin.views import admin connection = Connection() db = connection['test'] @app.before_request def before_request(): g.db = db @app.teardown_request def teardown_request(exception): if hasattr(g, 'db'): # FIX pass 

In admin / views.py:

 from flask import g @admin.route('/') def index(): # do something with g.db 

It really works. Therefore, the questions:

  • Is this the best way to use Connection in a flask?

  • Do I need to explicitly specify resources in the teardown_request file and how to do this?

+6
source share
3 answers

I still think this is an interesting question, but why there is no answer ... So, here is my update.

For the first question, I think using current_app is more clear in Flask.

In app.py

 app = Flask(__name__) connection = Connection() db = connection['test'] app.db = db 

In view.py

 from Flask import current_app db = current_app.db # do anything with db 

And using current_app, you can use the factory application to create multiple applications as http://flask.pocoo.org/docs/patterns/appfactories/

And for the second question, I still understand this.

+7
source

Here's an example of using the bulb pimnongo extension:

Example:

your mongodb uri (before db name) in app.config as below

 app.config['MONGO_URI'] = 'mongodb://192.168.1.1:27017/your_db_name' mongo = PyMongo(app, config_prefix='MONGO') 

and then according to your api method where db needs to do the following:

 db = mongo.db 

Now you can work with this db connection and get your data:

 users_count = db.users.count() 
+2
source

I think you are in order. A flask is almost too flexible in how you can organize things, not always imagining one obvious and right way. You can use the pimongo flag extension , which adds a couple of small amenities. As far as I know, you do not need to do anything with the connection on demand.

0
source

Source: https://habr.com/ru/post/919962/


All Articles