[英]view didn't return a response in flask
我是 flask 的新手。我正在嘗試創建兩個上傳請求:1. 第一個文件無論如何都會保存 2. 如果我不上傳第二個文件,它將幫助我生成 output.json。 誰能建議我為什么沒有返回有效回復? 謝謝
類型錯誤:視圖 function 未返回有效響應。 function 要么返回 None,要么在沒有返回語句的情況下結束。
路線:
@app.route('/upload', methods=['POST','GET'])
def upload():
if request.method == 'POST' and 'txt_data' in request.files:
#Files upload and initiation
num_sentences = int(request.form['num_sentences'])
session["num_sentences"] = num_sentences
uploaded_file = request.files['txt_data']
filename = secure_filename(uploaded_file.filename)
session["filename"] = filename
# save uploaded file
if filename != '':
uploaded_file.save(os.path.join(app.config['UPLOAD_PATH'], filename))
text_file = open(os.path.join('uploads',filename), "r").read()
nlp_file_doc = nlp(text_file)
all_sentences = list(nlp_file_doc.sents)
ongoing_sentences = all_sentences[num_sentences:]
first_sentence = ongoing_sentences[0].text
# Save output file
if 'output_data' in request.files:
output_file = request.files['output_data']
output_filename = secure_filename(output_file.filename)
uploaded_file.save(os.path.join(app.config['OUTPUT_PATH'], output_filename))
else:
data = {first_sentence:[]}
with open("output.json", "w") as write_file:
json.dump(data, write_file)
#Test out the first sentence
extraction = apply_extraction(first_sentence, nlp)
return render_template('annotation.html',
all_sentences = all_sentences,
extraction = extraction, num_sentences = num_sentences)
html:
<form method=POST enctype=multipart/form-data action="{{ url_for('upload') }}" class="form-group">
<div class="form-group">
<input type="file" name="txt_data">
<form method=POST enctype=multipart/form-data action="{{ url_for('upload') }}" class="form-group">
<div class="form-group">
<input type="file" name="output_data">
</form>
您的路線接受GET 和 POST方法,但僅在您有 POST 請求的情況下返回。
@app.route('/upload', methods=['POST','GET'])
def upload():
if request.method == 'POST':
...
return something
# What happens here if the request.method is 'GET'?
如果您在 /upload 上發出 GET 請求,則 function 將不返回任何內容,並拋出錯誤。
您可以刪除 GET 方法或為 GET 案例返回一些東西。
解決方案 1:
@app.route('/upload', methods=['POST'])
解決方案 2:
@app.route('/upload', methods=['POST','GET'])
def upload():
if request.method == 'POST':
return something
return something_else # if request.method == 'POST' returns false.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.