【问题标题】:BottlePy pre-request processingBottlePy 预请求处理
【发布时间】:2012-10-26 19:21:25
【问题描述】:

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

这样我就可以在做实际工作之前阅读request.environ

我正在尝试这样做,以免重复代码,但在 BottlyPy 中找不到这样做的方法...

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

【问题讨论】:

    标签: python uwsgi bottle


    【解决方案1】:

    这就是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)
    

    【讨论】:

    • 你的意思是我应该编写自己的插件来初始化一些我需要读取 request.environ 的东西吗?
    • 没错。制作 Bottle 插件并不难。
    • 太棒了,非常感谢您提供的非常简单的代码示例。
    猜你喜欢
    • 2017-06-25
    • 2021-05-11
    • 1970-01-01
    • 2021-09-26
    • 2014-10-31
    • 2016-03-17
    • 1970-01-01
    • 1970-01-01
    • 2019-08-29
    相关资源
    最近更新 更多