【发布时间】:2012-10-26 19:21:25
【问题描述】:
我正在寻找一种方法,让所有请求在进入 路由 之前进入函数 foo()。
这样我就可以在做实际工作之前阅读request.environ。
我正在尝试这样做,以免重复代码,但在 BottlyPy 中找不到这样做的方法...
我的设置是:nginx -> uwsgi -> bottlepy。
【问题讨论】:
我正在寻找一种方法,让所有请求在进入 路由 之前进入函数 foo()。
这样我就可以在做实际工作之前阅读request.environ。
我正在尝试这样做,以免重复代码,但在 BottlyPy 中找不到这样做的方法...
我的设置是:nginx -> uwsgi -> bottlepy。
【问题讨论】:
这就是plugins 的用途。
这是一个例子:
import bottle
from bottle import request, response
def foo(callback):
def wrapper(*args, **kwargs):
# before view function execution
print(request.environ) # do whatever you want
body = callback(*args, **kwargs) # this line basically means "call the view normally"
# after view function execution
response.headers['X-Foo'] = 'Bar' # you don't need this, just an example
return body # another 'mandatory' line: return what the view returned (you can change it too)
return wrapper
bottle.install(foo)
【讨论】: