这是用于生成文件上传表单并对其进行处理的查看功能(是的,这直接来自
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>
我搜索了两天,发现当文件输入
name
在Flask视图终结点中找不到属性。我用它来处理
request.files.get("file")
.此外,在我的情况下,在提交表单时,无法访问该方法(服务器日志甚至不打印)
POST
这是有道理的,因为400是一个客户端错误,但仍然。。。
使用蓝图有什么东西破坏了这一切吗?我做错了什么?