forked from coderbuzz/bottle-peewee
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbottle_peewee.py
More file actions
74 lines (57 loc) · 2.16 KB
/
bottle_peewee.py
File metadata and controls
74 lines (57 loc) · 2.16 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
"""
This is based on the code from Indra Gunawan originally licensed under MIT.
The changes I made to the code include refactoring, pep8ifying,
updating for using peewee version 3.
"""
import inspect
import peewee as pw
import bottle
class PeeweePlugin:
''' This plugin passes an Peewee database handle to route callbacks
that accept a `db` keyword argument. If a callback does not expect
such a parameter, no connection is made. You can override the database
settings on a per-route basis. '''
name = 'peewee'
api = 2
def __init__(self, db, keyword='db'):
self.db = db
self.keyword = keyword
def setup(self, app):
''' Make sure that other installed plugins don't affect the same
keyword argument.'''
for other in app.plugins:
if not isinstance(other, PeeweePlugin):
continue
if other.keyword == self.keyword:
raise bottle.PluginError(
"Found another peewee plugin with "
"conflicting settings (non-unique keyword).")
def apply(self, callback, context):
# Override global configuration with route-specific values.
conf = context.config
db = conf.get('db', self.db)
keyword = conf.get('keyword', self.keyword)
# Test if the original callback accepts a 'db' keyword.
# Ignore it if it does not need a database handle.
parameteres = inspect.signature(callback).parameters
if keyword not in parameteres:
return callback
def wrapper(*args, **kwargs):
# Connect to the database
try:
db.connect()
except pw.OperationalError:
# the db is already open
pass
# Add the connection handle as a keyword argument.
kwargs[keyword] = db
try:
rv = callback(*args, **kwargs)
except pw.PeeweeException:
db.rollback()
raise
finally:
db.close()
return rv
# Replace the route callback with the wrapped one.
return wrapper