一:被装饰的函数必须传递一个参数,这个参数用来接收,视图函数的返回值
不加参数报错:
@app.after_request def handler_after_request(): return jsonify({"a":1}) # 错误提示 TypeError: handler_after_request() takes 0 positional arguments but 1 was given
加参数
@app.after_request def handler_after_request(response): return jsonify({"a":1}) # 返回 {"a":1}
二:参数的说明
视图函数的返回值有多个属性,且为Response Objects对象。官方文档里面的解释是:
The response object that is used by default in Flask. Works like the response object from Werkzeug but is set to have an HTML mimetype by default.
Quite often you don’t have to create this object yourself because make_response() will take care of that for you.
默认情况下在Flask中使用的响应对象。工作方式类似于Werkzeug中的response对象,但默认设置为具有HTML mimetype。通常您不必自己创建此对象,因为make_response()将为您处理这些问题。
属性1:headers
@app.after_request def handler_after_request(xx): print(xx.headers) return jsonify({"a":1}) # 打印结果 GET / HTTP/1.1 200 Content-Type: text/html; charset=utf-8 Content-Length: 232 Content-Type: text/html; charset=utf-8 Content-Length: 232
属性2:status
200 OK
属性3:status_code
200
属性4:data,处理返回值,可以假如判断条件,处理不同的返回值
@app.after_request def handler_after_request(xx): print(xx.data) print(xx.data.decode("utf-8")) return_str = xx.data.decode("utf-8") return_dict = eval(return_str) if return_dict.get("code") == 0: return jsonify({"return":"ok"}) else: return jsonify({"return":"fail"}) # 打印结果 b'{"code":0,"content":"xixi"} ' {"code":0,"content":"xixi"} # 返回值 {"return":"ok"}
方法1:get_json
get_json(force=False, silent=False, cache=True) Parse data as JSON. If the mimetype does not indicate JSON (application/json, see is_json()), this returns None. If parsing fails, on_json_loading_failed() is called and its return value is used as the return value. Parameters force – Ignore the mimetype and always try to parse JSON. silent – Silence parsing errors and return None instead. cache – Store the parsed JSON to return for subsequent calls.
例子
@app.after_request def handler_after_request(xx): return_dict = xx.get_json() # 直接使用xx.data取出的结果是byte类型的东西,get_json直接取出的是字典类型 print(return_str,type(return_dict) return jsonify(return_dict) # 打印结果 {'code': 0, 'content': 'xixi'} <class 'dict'> # 返回结果 {"code":0,"content":"xixi"}
# 如果视图函数没有返回值就返回
None <class 'NoneType'>
三:作用
(1)对视图函数的返回值进行统一处理
# TODO