Flask(3)- Flask 中的 HTTP 方法

查看 app.route() 源代码

    def route(self, rule: str, **options: t.Any) -> t.Callable:
        """Decorate a view function to register it with the given URL
        rule and options. Calls :meth:`add_url_rule`, which has more
        details about the implementation.

        .. code-block:: python

            @app.route("/")
            def index():
                return "Hello, World!"

        See :ref:`url-route-registrations`.

        The endpoint name for the route defaults to the name of the view
        function if the ``endpoint`` parameter isn't passed.

        The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` and
        ``OPTIONS`` are added automatically.

        :param rule: The URL rule string.
        :param options: Extra options passed to the
            :class:`~werkzeug.routing.Rule` object.
        """

        def decorator(f: t.Callable) -> t.Callable:
            endpoint = options.pop("endpoint", None)
            self.add_url_rule(rule, endpoint, f, **options)
            return f

        return decorator

 

重点

  • Calls:meth: add_url_rule,需要关注下这个方法
  • end_poiont 如果未传递 endpoint 参数,则路由的端点名称默认为视图函数的名称,如果已为注册函数,则会引发错误
  • methods 参数默认值是 ["GET"],所以当你不传 methods 参数时,只有发送 GET 请求才能匹配上对应的路由

 

来看看 add_url_rule 方法

打个断点,进入 debug 调试模式,运行后,一直 F7 就能看到源码

  • self:就是 Flask 类的实例
  • rule:其实就是路由规则
  • end_point:函数名
  • methods:如果没有传,那么会先通过 view_func 获取 methods 属性,如果还是没有,那默认就是 GET,记得这是个列表 [ ]

 

结论

默认的 app.route() 是仅支持 GET 请求的,如果想通过 POST、PUT、DELTE 等方法正常请求的话,需要添加 methods 参数哦

 

GET 请求的栗子

代码

# 不指定 methods,默认就是 GET
@app.route('/')
def hello_world():
    # 返回字符串
    return '<b>Hello World</b>'


@app.route('/get', methods=["GET"])
def get_():
    # 返回字符串
    return '这是get请求'

 

postman 请求结果

 

没啥特别的~

 

POST 请求的栗子

代码

@app.route('/post', methods=["POST"])
def post_():
    # 返回字符串
    return {"messgage": "这是post请求"}

返回的是一个 python 字典,那么最后请求得到响应会是啥呢?

 

postman 请求结果

踩坑之一:哎呀,假设我用 GET 方法发起请求,那么就会直接报 405,说你的请求方法是不允许的!记住了哦!

 

要记住,如果 return 的是字典,那么请求得到的响应数据是 Json 格式哦

 

PUT、DELETE 请求的栗子

代码

@app.route('/delandput', methods=["DELETE", "PUT"])
def delandput():
    # 返回字符串
    return ["delete", "put"]

一个视图函数,允许 DELETE、PUT 方法

 

postman 请求结果

踩坑之二:我去!怎么报错了...仔细一看,错误信息已经提示的很清楚了,视图函数的返回值类型只能是 string、dict、tuple

 

正确的代码

@app.route('/delandput', methods=["DELETE", "PUT"])
def delandput():
    # 返回字符串
    return {"result": ["delete", "put"]}

 

postman 请求结果

put 和 delete 都成功啦

 

总结 

 

posted @ 2021-07-10 16:41  小菠萝测试笔记  阅读(855)  评论(0编辑  收藏  举报