Djangoでzipファイルを作成してレスポンスで返す方法。
PythonのZipFileクラスはファイルライクなオブジェクトに書き込みできるので、HttpResponseのインスタンスをそのまま渡せます。
views.py
from zipfile import ZipFile from django.http import HttpResponse def hello_zip(request): response = HttpResponse(content_type='application/zip') response['Content-Disposition'] = 'attachment; filename=hello.zip' zf = ZipFile(response, 'w') zf.writestr('hello.txt', 'hello world') zf.close() return response
mime-typeってapplication/zipでいいのだろか。いろいろありそうな気がする。