我在S3中有数千个媒体文件。
我想在DJango应用中呈现这些文件。我不想提供用户直接访问S3。在某些情况下,我想在渲染之前修改文件 例如:
我得到了纯文本的第一部分:
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的帮助
答案 0 :(得分:2)
除了kubus添加的内容之外,我还试图弄清楚如何强制"渲染"在浏览器vs"下载"文件。
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.
答案 1 :(得分:1)
您可以使用标准的mimetype模块来确定内容类型和文件名编码,例如:
In [1]: import mimetypes
In [2]: mimetypes.guess_type('hello.txt.gz')
Out[2]: ('text/plain', 'gzip')
In [3]: mimetypes.guess_type('hello.pdf.gz')
Out[3]: ('application/pdf', 'gzip')
In [4]: mimetypes.guess_type('hello.pdf')
Out[4]: ('application/pdf', None)