• Flask 学习7. make_response() 自定义响应内容 上海


    前言

    视图函数的返回值会自动转换为一个响应对象。如果返回值是一个字典,那么会调用 jsonify() 来产生一个响应。

    响应转换规则

    视图函数的返回值会自动转换为一个响应对象。如果返回值是一个字符串,那么会被 转换为一个包含作为响应体的字符串、一个 200 OK 出错代码 和一个 text/html 类型的响应对象。
    如果返回值是一个字典,那么会调用 jsonify() 来产生一个响应。

    具体规则:

    • 如果视图返回的是一个响应对象,那么就直接返回它。
    • 如果返回的是一个字符串,那么根据这个字符串和缺省参数生成一个用于返回的 响应对象。
    • 如果返回的是一个字典,那么调用 jsonify 创建一个响应对象。
    • 如果返回的是一个元组,那么元组中的项目可以提供额外的信息。元组中必须至少 包含一个项目,且项目应当由 (response, status) 、 (response, headers) 或者 (response, status, headers) 组成。 status 的值会重载状态代码, headers 是一个由额外头部值组成的列表 或字典。
    • 如果以上都不是,那么 Flask 会假定返回值是一个有效的 WSGI 应用并把它转换为 一个响应对象。

    如果想要在视图内部掌控响应对象的结果,那么可以使用 make_response() 函数。

    errorhandler定义404页面

    errorhandler的源码内容

        @setupmethod
        def errorhandler(
            self, code_or_exception: t.Union[t.Type[Exception], int]
        ) -> t.Callable[[T_error_handler], T_error_handler]:
            """Register a function to handle errors by code or exception class.
    
            A decorator that is used to register a function given an
            error code.  Example::
    
                @app.errorhandler(404)
                def page_not_found(error):
                    return 'This page does not exist', 404
    
            You can also register handlers for arbitrary exceptions::
    
                @app.errorhandler(DatabaseError)
                def special_exception_handler(error):
                    return 'Database connection failed', 500
    
            .. versionadded:: 0.7
                Use :meth:`register_error_handler` instead of modifying
                :attr:`error_handler_spec` directly, for application wide error
                handlers.
    
            .. versionadded:: 0.7
               One can now additionally also register custom exception types
               that do not necessarily have to be a subclass of the
               :class:`~werkzeug.exceptions.HTTPException` class.
    
            :param code_or_exception: the code as integer for the handler, or
                                      an arbitrary exception
            """
    
    

    设置404返回内容

    from flask import Flask
    from flask import render_template
    
    app = Flask(__name__)
    
    
    @app.errorhandler(404)
    def not_found(error):
        return render_template('error.html'), 404
    

    error.html内容

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>404</title>
    </head>
    <body>
      <h2>404 page not found</h2>
    </body>
    </html>
    

    访问一个不存在的页面,返回404

    HTTP/1.1 404 NOT FOUND
    Server: Werkzeug/2.2.2 Python/3.8.5
    Date: Mon, 22 Aug 2022 02:52:36 GMT
    Content-Type: text/html; charset=utf-8
    Content-Length: 150
    Connection: close
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>404</title>
    </head>
    <body>
      <h2>404 page not found</h2>
    </body>
    </html>
    

    make_response() 自定义返回内容

    可以使用 make_response() 包裹返回表达式,获得响应对象,并对该对象 进行修改,然后再返回:

    from flask import Flask
    from flask import render_template, make_response
    app = Flask(__name__)
    
    
    @app.errorhandler(404)
    def not_found(error):
        resp = make_response(render_template('error.html'), 404)
        resp.headers['X-Something'] = 'A value'
        return resp
    

    返回404页面返回报文

    HTTP/1.1 404 NOT FOUND
    Server: Werkzeug/2.2.2 Python/3.8.5
    Date: Mon, 22 Aug 2022 02:54:32 GMT
    Content-Type: text/html; charset=utf-8
    Content-Length: 150
    X-Something: A value
    Connection: close
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>404</title>
    </head>
    <body>
      <h2>404 page not found</h2>
    </body>
    </html>
    
  • 相关阅读:
    arm-linux-3.4.2移植for2440
    编译内核是出现:arch/arm/mm/tlb-v4wbi.S:64:error: too many positional arguments
    poj3050 Hopscotch
    poj3187 Backward Digit Sums
    poj2718 Smallest Difference
    hihocoder offer收割编程练习赛10 C 区间价值
    poj1862 Stripies
    poj3262 Protecting the Flowers
    poj2229 Sumsets
    poj2385 Apple Catching
  • 原文地址:https://www.cnblogs.com/yoyoketang/p/16612117.html
Copyright © 2020-2023  润新知