我在 S3 中有数千个媒体文件。
- 文件可以是 mimetype plain_text、html、xml、pdf、binary、zip 等
- 此外,某些文件也可能被 gzip 压缩
我想在 DJango 应用程序中渲染这些文件。我不想向用户提供对 S3 的直接访问。在某些情况下,我想在渲染文件之前修改它。
例如:
- /base/path/file_name_aaa.txt.gz <--- 从 S3 下载、解压并通过 django 渲染预格式化文本
- /base/path/file_name_aaa.pdf <--- 从 S3 下载并通过 django 渲染为 PDF
- /base/path/file_name_bbb.pdf.gz <--- 从 S3 下载,解压并通过 django 渲染为 PDF
- /base/path/file_name_ccc.xml.gz <--- 从S3下载,解压,替换一些内容,并通过django渲染为解压的xml
我得到了纯文本的第一部分:
from boto.s3.connection import S3Connection
import zlib
def get_gzipped_content(stream):
content = ''
for part in stream_decompress(stream):
content += part
return content
def stream_decompress(stream):
'''
decompress s3 gzipped stream
http://stackoverflow.com/questions/12571913/python-unzipping-stream-of-bytes
'''
dec = zlib.decompressobj(16+zlib.MAX_WBITS) # same as gzip module
for chunk in stream:
rv = dec.decompress(chunk)
if rv:
yield rv
conn = S3Connection(aws_key, aws_secret)
fname = 'aaa/bbb/ccc_1234.txt.gz'
key = conn.get_bucket('my_bucket').get_key(fname)
if fname.lower().endswith('.gz'):
content = get_gzipped_content(key)
else:
content = key.get_contents_as_string()
(render content as string in django)
我希望获得其他 mime 类型/gzip 的帮助
最佳答案
除了 kubus 添加的内容之外,我还试图弄清楚如何在浏览器中强制“渲染”而不是“下载”文件。
response = HttpResponse(ContentFile(content), content_type=mimetypes.guess_type(attach_id)[0])
if <this file should be forced download, and not render in browser>:
response['Content-Disposition'] = "attachment; filename=%s" % filename
# else, it will try to render in browser.
关于python - Django:允许从 S3 下载各种媒体文件而无需创建模型(同时隐藏 s3 存储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22960374/