[Answer]-Should a database connection be opened only once in a django app or once for every user within views.py?

1👍

Opening a connection when it is required is likely to be the better solution. Otherwise, there is the potential that the connection is no longer open. Thus, you would need to test that the connection is still open, and restart it if it isn’t before continuing anyway.

This means you could run the queries within a context manager block, which would auto-close the connection for you, even if an unhanded exception occurs.

Alternatively, you could have a pool of connections, and just grab one that is not currently in use (I don’t know if this would be an issue in this case).

It all depends just how expensive creating connections is, and if it makes sense to be able to re-use them.

Leave a comment