Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

psycopg2 with flask, when to close connection

Tags:

psycopg2

flask

I'm trying to build a simple web application that will be querying a postgres db and inserting/deleting data. Since it is a very simple application, I'm not using an ORM layer like sqlalchemy. Instead I'd like to use psycopg directly. Now, I'm wondering, when would be the best time to close cursors and connections? I'm having trouble getting the bigger picture of when the connection is idling with respect to access to the web app.

Thanks!

like image 709
adnxn Avatar asked Apr 04 '13 18:04

adnxn


1 Answers

maybe the official documentation can be useful

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

@app.teardown_request
def teardown_request(exception):
    g.db.close()
like image 140
gipi Avatar answered Jan 12 '23 00:01

gipi