cosmos
cosmos

Reputation: 2303

Should db connection be closed after every request?

I am creating a basic API using python flask and came across this documentation (similar suggestions are there in other documentations a well):

http://flask.pocoo.org/docs/0.12/tutorial/dbcon/

This document suggests db connections like this:

def get_db():
    """Opens a new database connection if there is none yet for the
    current application context.
    """
    if not hasattr(g, 'sqlite_db'):
        g.sqlite_db = connect_db()
    return g.sqlite_db

@app.teardown_appcontext
def close_db(error):
    """Closes the database again at the end of the request."""
    if hasattr(g, 'sqlite_db'):
        g.sqlite_db.close()

Initially, I though app.teardown_appcontext should be triggered for application closure. But when I tested, I found it is being triggered at the end of every request. I have two questions:

1) Why teardown_appcontext is being triggered at every request. Then how it is different from teardown_request?

2) Isn't it bad idea to acquire db connection for every request and close afterwards? I think connection should be acquired only once for complete application run. If it is a bad idea, how db connection should be acquired and closed?

Upvotes: 4

Views: 785

Answers (1)

Mr. Cat
Mr. Cat

Reputation: 55

it's good practice to pool connections when dealing with databases. the library you're using is in process and single process - this differs from most DB clients, which are network based and multi user. the overhead of creating a connection is much lower when everything is local.

Upvotes: 1

Related Questions