我正在使用Flask创建一个网页,并且是我的新手。我希望用户将文本粘贴到textarea
中,然后用该文本进行预测,但是用户也可以上传文件并使用该文件中的文本进行预测。
这是我的HTML文件:
<!DOCTYPE html>
<html>
<body>
<p>Please type data or upload a file:</p>
<p>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul class=flashes>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
</p>
<form method="POST" action="{{ url_for('display_result') }}" enctype="multipart/form-data">
<textarea id="data" name="data" cols="100" rows="50"></textarea>
<br/>
<input type="submit" name="prediction" value="Predict text">
<input type="file" id="file_u" name="file_u" value="Upload a file to predict" requiered>
<input type="submit" name="prediction_file" value="Predict file">
</form>
</body>
</html>
这是Python的功能:
def display_result():
if request.method == "POST":
if request.form.get("prediction") == "Predict text":
if request.form["data"] == "":
flash("Please paste some data")
return redirect(url_for("home"))
else:
#Make a prediction with the data in the textarea
return render_template("result.html", result=result)
elif request.form.get("prediction_file") == "Predict file":
if request.files['file_u'].filename == '':
flash("No file selected for uploading")
return redirect(url_for("home"))
else:
upload_file = request.files["file_u"]
data = upload_file.read()
#Make a prediction with the file uploded
return render_template("result.html", result=result)
问题是,当用户未选择文件时,我希望该页面显示错误,但给出一个werkzeug.exceptions.HTTPException.wrap.<locals>.newcls: 400 Bad Request: KeyError: 'file_u'
。
答案 0 :(得分:0)
您可以在尝试获取文件值之前检查文件是否存在:
elif request.form.get("prediction_file") == "Predict file":
file_object = request.files.get("file_u")
if not file_object or not file_object.filename:
flash("No file selected for uploading")
return redirect(url_for("home"))
else:
data = file_object.read()
#Make a prediction with the file uploded
return render_template("result.html", result=result)