在一个烦杂的after_request钩子中访问响应对象 [英] Access the response object in a bottlepy after_request hook

查看:61
本文介绍了在一个烦杂的after_request钩子中访问响应对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下网络应用程序:

I have the following web app:

import bottle
app = bottle.Bottle()

@app.route('/ping')
def ping():
    print 'pong'
    return 'pong'

@app.hook('after_request')
def after():
    print 'foo'
    print bottle.response.body

if __name__ == "__main__":
    app.run(host='0.0.0.0', port='9999', server='cherrypy')

在发送回响应之前,是否可以访问响应正文?

Is there a way to access the response body before sending the response back?

如果我启动该应用程序并查询/ping,我会在控制台中看到ping()after()函数以正确的顺序运行

If I start the app and I query /ping, I can see in the console that the ping() and the after() function run in the right sequence

$ python bottle_after_request.py 
Bottle v0.11.6 server starting up (using CherryPyServer())...
Listening on http://0.0.0.0:9999/
Hit Ctrl-C to quit.

pong
foo

但是在after()中尝试访问response.body时,我什么都没有.

but when in after() I try to access response.body, I don't have anything.

在Flask中,after_request装饰函数将输入响应对象,因此很容易访问它.如何在Bottle中做同样的事情?

In Flask the after_request decorated functions take in input the response object so it's easy to access it. How can I do the same in Bottle?

有什么我想念的吗?

推荐答案

在发送回响应之前,是否可以访问响应正文?

Is there a way to access the response body before sending the response back?

您可以编写一个简单的插件,这可能只是您所需要的(取决于您实际对响应所做的操作).

You could write a simple plugin, which (depending on what you're actually trying to do with the response) might be all you need.

下面是 Bottle插件文档中的示例,该示例设置了请求标头.它可以同样容易地操作body.

Here's an example from the Bottle plugin docs, which sets a request header. It could just as easily manipulate body.

from bottle import response, install
import time

def stopwatch(callback):
    def wrapper(*args, **kwargs):
        start = time.time()
        body = callback(*args, **kwargs)
        end = time.time()
        response.headers['X-Exec-Time'] = str(end - start)
        return body
    return wrapper

install(stopwatch)

希望能达到您的目的.

这篇关于在一个烦杂的after_request钩子中访问响应对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆