从服务器请求文件时出现 Flask 错误

时间:2021-05-29 06:28:41

标签: python http flask post frameworks

嗨,我在上传功能中遇到错误,我有另一个文件索引 html 文件,用户可以在其中上传文件和

`#Error#: RuntimeError: Working outside of request context.

This typically means that you attempted to use functionality that needed
an active HTTP request.Consult the documentation on testing for
information about how to avoid this problem.[Finished in 0.6s]`
  

在我的上传器功能中在线发生此错误: 代码:

`
@app.route("/")
@app.route("/upload", methods=["POST"])
def upload():
   return render_template('upload.html')

@app.route('/uploader', methods = ['GET', 'POST'])
def uploader():
   if request.method == 'POST':
      file1_path = os.path.join(app.config['UPLOAD'], secure_filename(FileIO.filename))
      f1 = request.files['file1']
      f1.save(file1_path)
      file2_path = os.path.join(app.config['UPLOAD'], secure_filename(FileIO.filename))
      f2 = request.files['file2']
      f2.save(file2_path)
      return file1_path, file2_path 
`

`
file1_path=uploader()
file2_path=uploader()
with open(file1_path, 'r') as file1:
   data = file1.read().replace('\n', '')
   str1=data.replace(' ', '')
with open(file2_path, 'r') as file2:
   data = file2.read().replace('\n', '')
   str2=data.replace(' ', '')
if(len(str1)>len(str2)):
   length=len(str1)
else:
   length=len(str2)
print(100-round((levenshtein(str1,str2)/length)*100,2),'% Similarity')
`
   

1 个答案:

答案 0 :(得分:0)

您的 uploader 函数具有装饰器 @route。当这个装饰器应用于一个函数时,该函数在被调用时会期望一个活动的 request 对象,这意味着如果您调用该函数,它应该是一个 http/https 请求。由于您是从 .py 文件调用它,并且在调用该函数时它不会创建任何请求,因此它将失败。

您可以在没有任何主动请求的情况下手动测试您的代码。如需更多帮助,请参阅此烧瓶文档,了解有关请求上下文以及如何实现所需的更多信息。 FLASK DOCS REQUEST

相关问题