我是烧瓶新手。我正在尝试创建两个上传请求: 1. 无论第一个文件都会保存 2. 如果我不上传第二个文件,它将帮助我生成 output.json。任何人都可以建议为什么我没有返回有效的回复?谢谢
TypeError:视图函数未返回有效响应。该函数要么返回 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>
答案 0 :(得分:0)
您的路由接受 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 请求,则该函数将不返回任何内容,从而引发错误。
您可以删除 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.