首页 > 解决方案 > 即使指定了 POST,Flask 也会返回 405 Method Not Allowed

问题描述

上传到我的upload_file路线时,我收到 405 Method Not Allowed 错误。我已经指定路由接受 GET 和 POST 方法,所以我不确定它为什么不起作用。

@app.route('/upload', methods=["GET, POST"])
def upload_file():
    if request.method == 'GET':
        return render_template("home.html")
    elif request.method == 'POST':
        if 'file' not in request.file:
            return render_template("home.html")

        file = request.files['file']

        if file.filename == '':
            return render_template("home.html")

        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            converted_file = convert(file)
            return render_template("home.html", converted_file=converted_file, img_src=UPLOAD_FOLDER+filename)
<form  method="post" enctype="multipart/form-data" action="/upload" >
    <input type="file" name="file">
    <input type="submit" value="Upload">
</form>    

标签: pythonflask

解决方案


@app.route('/upload', methods=["GET, POST"])

应该:

@app.route('/upload', methods=["GET", "POST"])

你给出了一个包含一个字符串“GET,POST”的列表,而不是一个包含两个字符串的列表:“GET”和“POST”。

PS:如此处所述:请勿在生产中使用 run() 。

不要在生产环境中使用 run()。它并非旨在满足生产服务器的安全性和性能要求。相反,请参阅 WSGI 服务器建议的部署选项。

请阅读部署选项


推荐阅读