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金字塔响应对象中的文件?


基础教程推荐
猜你喜欢
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- 症状类型错误:无法确定关系的真值 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01