BottlePy预请求处理

时间:2012-08-21 15:55:35

标签: python uwsgi bottle

我正在寻找一种方法让所有请求在进入路由之前进入函数foo()

这样我就可以在做真正的工作之前阅读request.environ

我正在尝试这样做,以便我不重复代码,但无法在 BottlyPy 中找到办法做这样的事情......

我的设置是:nginx - > uwsgi - > bottlepy。

1 个答案:

答案 0 :(得分:3)

这就是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)
相关问题