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
打个断点,进入 debug 调试模式,运行后,一直 F7 就能看到源码
默认的 app.route() 是仅支持 GET 请求的,如果想通过 POST、PUT、DELTE 等方法正常请求的话,需要添加 methods 参数哦
# 不指定 methods,默认就是 GET
@app.route('/')
def hello_world():
# 返回字符串
return '<b>Hello World</b>'
@app.route('/get', methods=["GET"])
def get_():
# 返回字符串
return '这是get请求'
没啥特别的~
@app.route('/post', methods=["POST"])
def post_():
# 返回字符串
return {"messgage": "这是post请求"}
返回的是一个 python 字典,那么最后请求得到响应会是啥呢?
踩坑之一:哎呀,假设我用 GET 方法发起请求,那么就会直接报 405,说你的请求方法是不允许的!记住了哦!
要记住,如果 return 的是字典,那么请求得到的响应数据是 Json 格式哦
@app.route('/delandput', methods=["DELETE", "PUT"])
def delandput():
# 返回字符串
return ["delete", "put"]
一个视图函数,允许 DELETE、PUT 方法
踩坑之二:我去!怎么报错了...仔细一看,错误信息已经提示的很清楚了,视图函数的返回值类型只能是 string、dict、tuple
@app.route('/delandput', methods=["DELETE", "PUT"])
def delandput():
# 返回字符串
return {"result": ["delete", "put"]}
put 和 delete 都成功啦