Created
July 14, 2017 19:01
-
-
Save skeeved/79dfe5652b20182586bb55c3cbc94250 to your computer and use it in GitHub Desktop.
python borg pattern singleton
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Singleton class encapsulating a psycopg2 connection. | |
""" | |
import psycopg2 | |
from psycopg2.extras import DictCursor | |
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE) | |
psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY) | |
class DB(object): | |
"""Borg pattern singleton""" | |
__state = {} | |
def __init__(self): | |
self.__dict__ = self.__state | |
if not hasattr(self, 'conn'): | |
self.conn = psycopg2.connect(database='foo', | |
user='bar', | |
host='baz') | |
self.cur = self.conn.cursor(cursor_factory=DictCursor) | |
if __name__ == '__main__': | |
db = DB() | |
db.cur.execute("some sql here") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment