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

 

總結 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM