在Flask文件上传期间出现400错误的请求错误?

时间:2019-02-24 10:37:28

标签: python python-3.x flask

这是用于生成文件上传表单并对其进行处理的视图功能(是的,它直接来自Flask docs):

transaction_blueprint = Blueprint(
    "transaction", __name__, template_folder="../templates", url_prefix="/transactions"
)

@transaction_blueprint.route("/upload", methods=["GET", "POST"])
def upload_select_file():
    print(request.method)
    if request.method == "POST":
        # check if the post request has the file part
        if "file" not in request.files:
            flash("No file part")
            return redirect(request.url)
        file = request.files.get("file")
        # if user does not select file, browser also
        # submit an empty part without filename
        if file.filename == "":
            flash("No selected file")
            return redirect(request.url)
        # allowed_file is defined elsewhere
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join("/tmp", filename))
            return jsonify({"success": True})
    return """
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form method=post enctype=multipart/form-data>
      <input type=file name=file>
      <input type=submit value=Upload>
    </form>
    <p>%s</p>
    """ % "<br>".join(os.listdir("/tmp",))

http://localhost:8000/transactions/upload提交表单后,我收到400错误的请求错误。我正在使用一个大约15kb的简单文本文件进行测试。据我所知,HTML格式正确:

<form method="post" enctype="multipart/form-data">
  <input type="file" name="file">
  <input type="submit" value="Upload">
</form>

我搜索了两天,得知当在Flask视图端点中找不到文件输入的name属性时,会发生此错误。我使用request.files.get("file")处理。此外,在我的情况下,提交表单后,方法仍未到达(服务器日志甚至未打印“ POST”)。这是有道理的,因为400是客户端错误,但仍然...

使用蓝图是否有东西打破了这个问题?我在这里做什么错了?

1 个答案:

答案 0 :(得分:0)

添加csrf令牌即可完成

<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
相关问题