How can I rename a file in a Python Pyramid Response object?(如何重命名Python金字塔响应对象中的文件?)
本文介绍了如何重命名Python金字塔响应对象中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能的重复项:
How to set file name in response
我在MongoDB中存储文件。为了提供来自金字塔的文件,我这样做:
# view file
def file(request):
id = ObjectId(request.matchdict['_id'])
collection = request.matchdict['collection']
fs = GridFS(db, collection)
f = fs.get(id)
filename, ext = os.path.splitext(f.name)
ext = ext.strip('.')
if ext in ['pdf','jpg']:
response = Response(content_type='application/%s' % ext)
else:
response = Response(content_type='application/file')
response.app_iter = FileIter(f)
return response
使用此方法,文件名默认为文件的ObjectId
字符串,该字符串不美观,并且缺少正确的文件扩展名。我在文档中查看了如何/在哪里重命名Response
对象中的文件,但我看不到它。任何帮助都是极好的。
推荐答案
没有100%万无一失的方法来设置文件名。文件名由浏览器决定。
也就是说,您可以使用Content-Disposition
头指定希望浏览器下载文件而不是显示该文件,您还可以建议该文件使用的文件名。如下所示:
Content-Disposition: attachment; filename="fname.ext"
但是,没有可靠的跨浏览器方法来指定包含非ASCII字符的文件名。有关详细信息,请参阅this stackoverflow question。您还必须小心对文件名使用quoted-string
编码;构建一个文件名时,应删除所有非ASCII字符,并使用"
加引号。
现在是金字塔特有的东西。只需在您的响应中添加一个Content-Disposition
头。(请注意,application/file
是not a valid mime type。使用application/octet-stream
作为"通用"字节袋类型。)
# "application/file" is not a valid mime type!
content_subtype = ext if ext in ['jpg','pdf'] else 'octet-stream'
# This replaces non-ascii characters with '?'
# (This assumes f.name is a unicode string)
content_disposition_filename = f.name.encode('ascii', 'replace')
response = Response(content_type="application/%s" % content_subtype,
content_disposition='attachment; filename="%s"'
% content_disposition_filename.replace('"','\"')
)
这篇关于如何重命名Python金字塔响应对象中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:如何重命名Python金字塔响应对象中的文件?


猜你喜欢
- YouTube API v3 返回截断的观看记录 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01