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

Flask error when request file from server

嗨,我在上传功能中遇到错误我有另一个文件索引 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')
`
   

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

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