-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbottle_redis.py
52 lines (43 loc) · 1.56 KB
/
bottle_redis.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
# -*- coding: utf-8 -*-
import redis
import inspect
from bottle import __version__, PluginError
class RedisPlugin(object):
name = 'redis'
api = 2
def __init__(self, keyword='rdb', *args, **kwargs):
self.keyword = keyword
self.redisdb = None
self.args = args
self.kwargs = kwargs
def setup(self, app):
for other in app.plugins:
if not isinstance(other, RedisPlugin):
continue
if other.keyword == self.keyword:
raise PluginError("Found another redis plugin with "\
"conflicting settings (non-unique keyword).")
if self.redisdb is None:
self.redisdb = redis.ConnectionPool(*self.args, **self.kwargs)
def apply(self, callback, route):
# hack to support bottle v0.9.x
if __version__.startswith('0.9'):
config = route['config']
_callback = route['callback']
else:
config = route.config
_callback = route.callback
conf = config.get('redis') or {}
try:
args = inspect.getargspec(_callback)[0]
except ValueError:
args = inspect.getfullargspec(_callback)[0] # FIXME deprecated since Python 3.5
keyword = conf.get('keyword', self.keyword)
if keyword not in args:
return callback
def wrapper(*args, **kwargs):
kwargs[self.keyword] = redis.Redis(connection_pool=self.redisdb)
rv = callback(*args, **kwargs)
return rv
return wrapper
Plugin = RedisPlugin