2

I have Flask application, which looks like this:

from flask import Flask
app = Flask(__name__)
from pymongo import MongoClient

def get_db():
    c = MongoClient()
    return c.mydb

@app.route("/")
def hello():
    db = get_db()
    db.foo.find_one(...)
    ...

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

Seems it works fine. But I'm not sure about one thing. I create a MongoClient instance (and connection to db) in every view call. But should I close connection?

Maybe I should close connection after each view call, like this:

@app.before_request
def before_request():
    g.db = get_db()

@app.teardown_request
def teardown_request(exception):
    g.db.close()

How do you handle this stuff?

1 Answer 1

5

MongoClient has connection-pooling support built in, with a default size of 10. So you should be creating one MongoClient instance that's left open and shared by all your view calls.

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

2 Comments

@un1t Your MongoClient instance basically becomes a global variable; so however you want to handle that. Nothing flask-specific about it.
Don't do it per request - as thats a big overhead - have it in the module / global namespace.

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.