python3 gunicorn flask生成下载文件出错

显示的错误是

UnicodeEncodeError: 'ascii' codec can't encode characters in position 182-205: ordinal not in range(128)

这是因为传输中文url的原因,所以需要把中文url转变一下

   from urllib.parse import quote

   response['Content-Length'] = post.attachment.size

   filename = post.attachment_filename if post.attachment_filename else 'attachment'
   response["Content-Disposition"] = \
            "attachment; " \
            "filenane={ascii_filename};" \
            "filename*=UTF-8''{utf_filename}".format(
                ascii_filename=quote(filename),
                utf_filename=quote(filename)
            )

参考:

  • 一次找不到错误的巨坑的 http header 的 url 编码的 Python 3 迁移问题
  • 正确处理下载文件时HTTP头的编码问题(Content-Disposition)
  • Python urllib.parse.quote() Examples
  • UnicodeEncodeError: 'ascii' codec can't encode characters in position 151-165: ordinal not in range(128)

你可能感兴趣的:(python3 gunicorn flask生成下载文件出错)