zoukankan      html  css  js  c++  java
  • flask框架之after_request的用法

    一:被装饰的函数必须传递一个参数,这个参数用来接收,视图函数的返回值

    不加参数报错:

    @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

  • 相关阅读:
    MySQL用户管理
    MySQL慢查询日志总结
    linux rinetd 端口转发部署
    CentOS6.8下安装MySQL5.6
    ELK filter过滤器来收集Nginx日志
    ELK+Redis 解析Nginx日志
    为什么很多IT公司不喜欢进过培训机构的人呢?
    Django之virtualenv下安装xadmin
    Django开发问题及解决方法汇总
    解决Pycharm添加虚拟解释器的报错问题
  • 原文地址:https://www.cnblogs.com/meloncodezhang/p/13884436.html
Copyright © 2011-2022 走看看