9

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

I know Connection in pymongo is thread-safe and has built-in pooling. I guess I need to create a global Connection instance, and use before_request to put it in flask g.

In the 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 actually works. So questions are:

  1. Is this the best way to use Connection in flask?

  2. Do I need to explicitly reclaim resources in teardown_request and how to do it?

3 Answers 3

8

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

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

In app.py

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

In the view.py

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

And by using current_app, you can use application factory to create more than one app as http://flask.pocoo.org/docs/patterns/appfactories/

And for the second question, I'm still figuring it out.

Sign up to request clarification or add additional context in comments.

Comments

2

Here's example of using flask-pymnongo extension:

Example:

your mongodb uri (till db name) in app.config like below

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

and then under your api method where u need db do the following:

db = mongo.db

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

users_count = db.users.count()

Comments

0

I think what you present is ok. Flask is almost too flexible in how you can organize things, not always presenting one obvious and right way. You might make use of the flask-pymongo extension which adds a couple of small conveniences. To my knowledge, you don't have to do anything with the connection on request teardown.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.