首页 > 解决方案 > 即使明确定义了路线,Flask 也会返回 404

问题描述

我有一些使用蓝图的功能:

@election_blueprint.route("/getlast/{string:type}")
def get_specific_last(election_type: str):
    some code here

然后我在启动应用程序之前注册此蓝图:

app.register_blueprint(election_blueprint, url_prefix="/election")

而且,在那之后,Flask 说这个方法是在路由中定义的:

# FLASK_APP='owo/app.py' flask routes
Endpoint                     Methods  Rule
---------------------------  -------  ----------------------------------------------------------
elections.get_elections      GET      /election/find/{string: type}
elections.get_last           GET      /election/getlast/
elections.get_specific_last  GET      /election/getlast/{string:type} <-- There it is!

但是当我尝试从客户端获取它时,我得到 404,即使其他方法,即使在此蓝图中声明,似乎也可以正常工作。我究竟做错了什么?

例如,如果我只是去

http://localhost/election/getlast/sometype

它返回 404,但如果我使用另一种方法,比如

http://localhost/election/getlast/

它工作正常。

标签: flask

解决方案


我相信使用“{”而不是“<”在您的代码上写入的方式存在错字。此外,路由上的变量名应与函数上的变量名匹配:

@election_blueprint.route("/getlast/<string:election_type>")
def get_specific_last(election_type: str):
    some code here

很好的参考:https ://hackersandslackers.com/flask-routes/ 希望它适合你:)


推荐阅读