Skip to content

Instantly share code, notes, and snippets.

@skyler
Created October 11, 2012 18:12
Show Gist options
  • Save skyler/3874406 to your computer and use it in GitHub Desktop.
Save skyler/3874406 to your computer and use it in GitHub Desktop.
"""Convenience methods for interacting with the database.
Calling get_db_connection() will return the open database handle.
"""
import psycopg2
from psycopg2.extras import DictConnection
from contextlib import closing
import configure
_conn = None
"""The database connection."""
def get_db_connection():
"""Get a reference to the open database connection, or create a new
connection if one does not already exist.
Returns an instance of psycopg2's connection object.
"""
global _conn
if conn is None or conn.closed:
# Create a new connection object and store it on g.
_conn = DictConnection(configure.PG_CONNECT_INFO)
return _conn
def disconnect_db():
"""Disconnect from PostgreSQL.
This method should be called on request shutdown.
"""
global _conn
if _conn is not None and not _conn.closed:
_conn.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment