Last active
June 27, 2018 20:00
-
-
Save travishathaway/8522471671b7255981561db4d60b931f to your computer and use it in GitHub Desktop.
This is an example that accompanies a presentation I recently gave on decorators. In this example, I show how to create decorators for managing connections to SQLite3 databases.
This file contains hidden or 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
from functools import wraps | |
import sqlite3 | |
CONN_STR = '/tmp/foo.db' | |
def sqlite_conn(conn_str): | |
def dec_func(func): | |
@wraps(func) | |
def wrap(*args, **kwargs): | |
conn = sqlite3.connect(conn_str) | |
cursor = conn.cursor() | |
try: | |
res = func(cursor, *args, **kwargs) | |
conn.commit() | |
return res | |
finally: | |
conn.close() | |
return wrap | |
return dec_func | |
@sqlite_conn(CONN_STR) | |
def create_tables(cursor): | |
cursor.execute('create table test (id integer, desc text)') | |
@sqlite_conn(CONN_STR) | |
def insert_data(cursor, table, data): | |
cursor.execute(f'insert into {table} values (?, ?)', data) | |
@sqlite_conn(CONN_STR) | |
def read_data(cursor, table): | |
cursor.execute(f'select * from {table}') | |
return cursor.fetchall() | |
create_tables() | |
insert_data('test', (1, 'hai')) | |
insert_data('test', (2, 'there')) | |
print(read_data('test')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment