SoFunction
Updated on 2024-11-17

Python Generate and Download File Backend Code Example

txt file

Generate and download the txt file:

@('/download', methods=['GET'])
def download():
  content = "long text"
  response = make_response(content)
  ["Content-Disposition"] = "attachment;   
  filename="
  return response

Once it's running, type in your browser: http://127.0.0.1:5000/download to download the txt file directly.

excel file

Generate and download excel file:

@("/export",methods = ['GET'])
def export():
  out = BytesIO()
  workbook = (out)
  table = workbook.add_worksheet()
  (0, 0, "Column 1")
  (0, 1, "Column 2")
  (0, 2, "Column 3")
  (0, 0, "name")
  (1, 1, "sex")
  (2, 2, "class")
  ()
  (0)
  filename = quote("Entity class download.xlsx")
  rv = send_file(out, as_attachment=True, attachment_filename=filename)
  ['Content-Disposition'] += "; filename*=utf-8''{}".format(filename)
  return rv

After running it, type in your browser: http://127.0.0.1:5000/export to download the excel file directly.

When separating the front-end and back-end, the interface returns with headers in mind

def exportExcel():
  workbook = (encoding='utf-8')
  wSheet = workbook.add_sheet("Plan")
  titleFont = ()
  f = BytesIO()
  (f)
  (0)
  filename = quote(saveFile) # Convert a single string encoding into %xx%xx form
  rv = send_file(f, as_attachment=True, attachment_filename=filename)
  ['Content-Disposition'] += "; filename*=utf-8''{}".format(filename)
  ['Cache-Control'] = 'no-store'      # The point is this.!!!!!!!!!!!!!!!!!
  return rv

This is the whole content of this article.