在某些路线上得到404是不一致的

2024-04-26 22:50:26 发布

您现在位置:Python中文网/ 问答频道 /正文

问题很简单

#This works
@app.route("/projects")
def user_home():
    return 'projects'

#This works
@app.route("/projects/new", methods=["GET", "POST"])
def create_project():
    return 'new project'

#This works
@app.route("/projects/<project_id>")
async def project_detail(project_id):
    return 'project detail'

#This works
@app.route("/projects/<project_id>/tasks")
def user_tasks(project_id):
    return 'project tasks'

#This gives a 404
@app.route("/projects/<project_id>/tasks/new", methods=["GET", "POST"])
def create_task(project_id):
    return 'new project task'

#This works
@app.route("/projects/<project_id>/tasks/<task_id>")
async def task_detail(project_id, task_id):
    return 'task detail'

最后一条路线是给我一个404,尽管它遵循与上面相同的逻辑。你知道吗

这里发生了什么?你知道吗

如果我能更好地设计我的路线,我愿意接受建议,这是一个简单的master/detail/CRUD应用程序

(标记Quart,因为我实际上使用的是Quart,但目前我假设这无关紧要,因为它与flask具有相同的api)


Tags: projectidappnewtaskreturndefthis
2条回答

我对您的代码没有任何错误,请重新检查。但也许你可以试试

@app.route("/projects/<project_id>/tasks/new_task/", methods=["GET", "POST"])
def create_task(project_id):
    return 'new project task'

根据this answer,关键问题是Werkzeug缺少正斜杠的解释,而正斜杠又给出了404错误。你知道吗

Your /users route is missing a trailing slash, which Werkzeug interprets as an explicit rule to not match a trailing slash. Either add the trailing slash, and Werkzeug will redirect if the url doesn't have it, or set strict_slashes=False on the route and Werkzeug will match the rule with or without the slash

根据docs

URL rules that end with a slash are branch URLs, others are leaves. If you have strict_slashes enabled (which is the default), all branch URLs that are visited without a trailing slash will trigger a redirect to the same URL with that slash appended.

因此,对于您的情况,您可以尝试:

@app.route("/projects/<project_id>/tasks/new", methods=["GET", "POST"], strict_slashes=False)
def create_task(project_id):
    return 'new project task'

相关问题 更多 >