使用after_request时如何获取状态码? [英] How to get status code when using after_request?

查看:49
本文介绍了使用after_request时如何获取状态码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 after_request 时如何获取状态代码(200、500,...)?

How to get the status code (200, 500, ... ) when using after_request ?

我想要的是拥有记录器提供的输出(例如werkzeug),但是可以在其中添加我想要的内容(用户名,...):

What I want is to have the kind of output we have with a logger (for example werkzeug) but where it's possible to add what I want (username, ...) :

远程IP,时间点,路径,状态代码

推荐答案

在每个请求之后注册运行的函数应采用一个响应类对象并返回一个响应类对象(请参见

The function(s) that are registered to run after each request should take a response class object and return a response class object (see http://flask.pocoo.org/docs/0.10/api/#flask.Flask.after_request)

因此,您可以从响应类对象中获取该信息,有关可用信息的更多信息,请参见 http://flask.pocoo.org/docs/0.10/api/#flask.Response

So you can take that info from the response class object, for more info on what is available see http://flask.pocoo.org/docs/0.10/api/#flask.Response

这是一个部分示例:

import logging

#
# your other flask code here
#

@app.after_request
def log_the_status_code(response):
    status_as_string = response.status
    status_as_integer = response.status_code
    logging.warning("status as string %s" % status_as_string)
    logging.warning("status as integer %s" % status_as_integer)
    return response

作为输出,您应该在成功点击后进入控制台:

and as output, you should get in the console after a successful hit:

WARNING:root:status as string 200 OK
WARNING:root:status as integer 200

这篇关于使用after_request时如何获取状态码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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