-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy patheasypg.py
55 lines (48 loc) · 1.45 KB
/
easypg.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
"""
EasyPG - a module to make it easier to connect to PostgreSQL with different configurations.
:version: 7
"""
from contextlib import closing, contextmanager
import psycopg2
from ConfigParser import SafeConfigParser
def connect(context=True, autocommit=True, **kwargs):
"""
Connects to the database. Configuration is read from the configuration
file ``pgapp.cfg``, if available.
:param context: whether to wrap the connection in an auto-closing context manager.
:param kwargs: Default configuration parameters.
:return: The database connection, wrapped in a context manager for a ``with`` block.
:rtype: psycopg2.Connection
"""
cp = SafeConfigParser()
cp.read('pgapp.cfg')
opts = dict(kwargs.items())
opts.update(cp.items('database'))
cxn = psycopg2.connect(**opts)
cxn.autocommit = autocommit
if context:
return closing(cxn)
else:
return cxn
@contextmanager
def cursor(**kwargs):
"""
Context-managed cursor and database connection. This will yield a cursor,
and close both the cursor and the database connection.
:param kwargs: The connection arguments.
:return:
"""
dbc = connect(context=False, **kwargs)
try:
cur = dbc.cursor()
try:
yield cur
finally:
dbc.close()
finally:
dbc.close()
def demo():
with cursor() as cur:
print "connected to database"
if __name__ == '__main__':
demo()