Skip to content

Instantly share code, notes, and snippets.

@elianbarci
Last active September 21, 2022 22:52
Show Gist options
  • Save elianbarci/c0a027caf41ffe6030469ec46b797067 to your computer and use it in GitHub Desktop.
Save elianbarci/c0a027caf41ffe6030469ec46b797067 to your computer and use it in GitHub Desktop.
Return HttpResponse object with a .zip file with one or more elements attached to it
zip_file_location = './zipFileName.zip'
zip = zipfile.ZipFile(zip_file_location,'w')
file_location_one = f'{fileNameOne}.json'
with open(file_location_one, 'w') as file:
json.dump(elementsOne, file, default=str)
zip.write(file_location_one)
os.remove(file_location_one)
file_location_two = f'{fileNameTwo}.json'
with open(file_location_two, 'w') as file:
json.dump(elementsTwo, file, default=str)
zip.write(file_location_two)
os.remove(file_location_two)
zip.close()
try:
folder_file = open(zip_file_location, 'rb')
response = HttpResponse(FileWrapper(folder_file), content_type='application/zip')
response['Access-Control-Expose-Headers'] = "filename"
response.headers["filename"] = "zipFileName.zip"
folder_file.close()
os.remove(zip_file_location)
except IOError:
response = HttpResponseNotFound('<h1>File not exist</h1>')
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment