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 都成功啦

总结 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小菠萝测试笔记

来支持下测试小锅锅

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值