来自 flask 文档 使用时不带尾随斜杠的链接会使用斜杠重定向到该链接。
在我的情况下,网址以
/uploads/
结尾,当我从 localhost:5000/uploads/
上传文件时,以下代码会打印我的文件,但当我从 files
上传文件时,localhost:5000/uploads
为空。如何保留尾部斜杠以下路线,但重定向后仍然能够获取上传的文件?
@app.route('/upload/')
def upload_file():
files = request.files.getlist('files')
print(files)
重定向实际上并不完全由 Flask 完成。 Flask 仅返回 301 或 302 重定向(可能是 302),无论您使用什么 http 客户端,都需要决定如何处理它。
请参阅此内容以讨论将会发生的情况: HTTP:POST 请求收到 302,重定向请求应该是 GET 吗?
这是相关的部分,来自 Chrome 来源的评论:
// For 303 redirects, all request methods except HEAD are converted to GET,
// as per the latest httpbis draft. The draft also allows POST requests to
// be converted to GETs when following 301/302 redirects, for historical
// reasons. Most major browsers do this and so shall we. Both RFC 2616 and
// the httpbis draft say to prompt the user to confirm the generation of new
// requests, other than GET and HEAD requests, but IE omits these prompts and
// so shall we.
文件上传通常是 POST 请求。无论如何,它都不会是 GET。因此,您通常不能依赖客户端在新的 POST 请求中重新发送文件。
理想情况下,非斜线 URL 在语义上应该是正确的。我认为出于向后兼容性的原因,您想保留带有斜线的那个。
如果您确实需要两者都工作,那么@AdityaDN 在他的评论中建议的选项是您应该寻找的。具体来说,您需要防止重定向发生,并且让两个端点都具有立即响应请求的函数。就我个人而言,我偏向第二个答案(https://stackoverflow.com/a/54118051/1934174),假设它有效。我自己没试过。