python - How to use pyramid.response.FileIter -
i have following view code attempts "stream" zipfile client download:
import os import zipfile import tempfile pyramid.response import fileiter def zipper(request): _temp_path = request.registry.settings['_temp'] tmpfile = tempfile.namedtemporaryfile('w', dir=_temp_path, delete=true) tmpfile_path = tmpfile.name ## creating zipfile , adding files z = zipfile.zipfile(tmpfile_path, "w") z.write('somefile1.txt') z.write('somefile2.txt') z.close() ## renaming zipfile new_zip_path = _temp_path + '/somefilegroup.zip' os.rename(tmpfile_path, new_zip_path) ## re-opening zipfile new name z = zipfile.zipfile(new_zip_path, 'r') response = fileiter(z.fp) return response however, response in browser:
could not convert return value of view callable function newsite.static.zipper response object. value returned .
i suppose not using fileiter correctly.
update:
since updating michael merickel's suggestions, fileiter function working correctly. however, still lingering mime type error appears on client (browser): resource interpreted document transferred mime type application/zip: "http://newsite.local:6543/zipper?data=%7b%22ids%22%3a%5b6%2c7%5d%7d"
to better illustrate issue, have included tiny .py , .pt file on github: https://github.com/thapar/zipper-fix
fileiter not response object, error message says. iterable can used response body, that's it. zipfile can accept file object, more useful here file path. let's try writing tmpfile, rewinding file pointer start, , using write out without doing fancy renaming.
import os import zipfile import tempfile pyramid.response import fileiter def zipper(request): _temp_path = request.registry.settings['_temp'] fp = tempfile.namedtemporaryfile('w+b', dir=_temp_path, delete=true) ## creating zipfile , adding files z = zipfile.zipfile(fp, "w") z.write('somefile1.txt') z.write('somefile2.txt') z.close() # rewind fp start of file fp.seek(0) response = request.response response.content_type = 'application/zip' response.app_iter = fileiter(fp) return response i changed mode on namedtemporaryfile 'w+b' per docs allow file written and read from.
Comments
Post a Comment