2021年2月9日星期二

Secure contents of file uploaded using flask

I am new to web development and trying to build a website using Flask which asks a user to upload a file, processes it and gives some statistics related to the contents. I am planning to deploy this on heroku(free version). I wanted to make sure the contents of the file are secured. Currently I am deleting the file uploaded and closing file handler after reading the contents. What I have so far:

    class UploadForm(FlaskForm):          file = FileField()        @app.route('/', methods=['GET', 'POST'])          def upload():              form = UploadForm()              if form.validate_on_submit():                  filename = secure_filename(form.file.data.filename)                  session['filename'] = filename                  form.file.data.save(filename)                  return redirect(url_for('stats'))                        return render_template('upload.html', form=form)      @app.route('/stats', methods=['GET'])          def stats():              try:                  file_handle = open(session['filename'], encoding="utf8", mode="r")                  file_contents = file_handle.read()                  #processing done in this method                  data = prepare_stats(file_contents)                                     #to delete the uploaded file                  @after_this_request                  def remove_file(response):                      try:                          file_handle.close()                          os.remove(session['filename'])                      except Exception as error:                          app.logger.error(                              "Error removing or closing downloaded file handle", error)                      return response                  return render_template("stats.html", data)              except Exception:                  print(traceback.format_exc())  

Is there any scope to improve this further in order to avoid the contents of file being exposed?

https://stackoverflow.com/questions/66131145/secure-contents-of-file-uploaded-using-flask February 10, 2021 at 01:01PM

没有评论:

发表评论