Managing a database connection object in Django

54 views
Skip to first unread message

Ankit Arora

unread,
Nov 20, 2014, 1:59:04 PM11/20/14
to django...@googlegroups.com

I'm working with a Postgresql database with Django. Because of licensing reasons, I can't use psycopg2 , so I'm using the alternative pygresql.

I don't need to use the Django ORM at all, I simply need the cursor for cur.execute() and cur.fetchall().

Since pygresql doesn't have a Django backend connector, I can't use the pygresql pgdb module in the Database settings in settings.py; I've to manually open up a connection object.

What would be the best practice to do this? Currently I've simply created the connection object conn=pgdb.connect(params) in views.py outside of all functions, but this seems a bit hacky and I do get 'ProgrammingError: Server Closed the connection unexpectedly' errors here and there.

One approach might be to simply create an executeQuery() function which Opens a connection, executes a query, and closes it each time I want to execute a query. But I'm not sure if that's best practice and whether it would cause any issues.

Any tips?

Collin Anderson

unread,
Nov 21, 2014, 5:44:01 PM11/21/14
to django...@googlegroups.com
Hi,

For simplicity and reliability, although a hair slower, it probably makes sense to create a new database connection during each request.

You could define a function that gets a database connection with your parameters and then call that at the top of each view.

Collin
Reply all
Reply to author
Forward
0 new messages