[英]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.