Flask(3)- Flask 中的 HTTP 方法

简介: 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 就能看到源码

image.png

  • 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 请求结果

image.png

没啥特别的~

 

POST 请求的栗子


代码

@app.route('/post', methods=["POST"])

def post_():

    # 返回字符串

    return {"messgage": "这是post请求"}

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

 

postman 请求结果

image.png

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

 

PUT、DELETE 请求的栗子


代码

@app.route('/delandput', methods=["DELETE", "PUT"])

def delandput():

    # 返回字符串

    return ["delete", "put"]

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

 

postman 请求结果

image.png

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

 

正确的代码

@app.route('/delandput', methods=["DELETE", "PUT"])

def delandput():

    # 返回字符串

    return {"result": ["delete", "put"]}

 

postman 请求结果

image.png

image.png

put 和 delete 都成功啦

 

总结 


image.png


相关文章
|
2月前
|
中间件 测试技术 数据库
软件测试|测试平台开发-Flask 入门:Flask HTTP请求详解
软件测试|测试平台开发-Flask 入门:Flask HTTP请求详解
25 0
|
XML JSON 前端开发
前端构造 HTTP 请求的四种方法
前端构造 HTTP 请求的四种方法
326 0
前端构造 HTTP 请求的四种方法
1、Http协议(概述、请求方法、状态码)
1、Http协议(概述、请求方法、状态码)
78 0
http详解7-http协议之方法和状态码3状态码和数字
http详解7-http协议之方法和状态码3状态码和数字
49 0
http详解7-http协议之方法和状态码3状态码和数字
http详解6-http协议之方法和状态码2
http详解6-http协议之方法和状态码2
72 0
http详解6-http协议之方法和状态码2
http详解8-http协议之方法和状态码4状态码和数字
http详解8-http协议之方法和状态码4状态码和数字
50 0
http详解8-http协议之方法和状态码4状态码和数字
http详解5-http协议之方法和状态码1
http详解5-http协议之方法和状态码1
54 0
http详解5-http协议之方法和状态码1
|
Java Python
python http服务flask架构实用代码 | 实用代码架构
python http服务flask架构实用代码 | 实用代码架构
python http服务flask架构实用代码 | 实用代码架构
|
JavaScript Python
Python全栈快餐教程(1) - 用Flask处理HTTP请求
# Python全栈快餐教程(1) - 用Flask处理HTTP请求 ## 初识Flask Flask是最流行的Python web框架之一。 我们来写个最小的web应用,只有一个路由先跑进来玩玩吧。 ```python from flask import Flask # 定义flask app对象 app = Flask(__name__) # 处理路由
1369 0
相关产品
云迁移中心
推荐文章
更多