'ZipFile to File to FileField Django Python
I'm doing a call from a API that give me a zip file with two file in it. I manage to extract the file i need (cause it's a PDF)
and now i just can't find a solution to save it in my filefield without creating the file in my pc.
with ZipFile(io.BytesIO(response3.content)) as z: # response3 is my response to the API
for target_file in z.namelist():
if target_file.endswith('pdf'):
z.extract(member=target_file) # that's how i can have acces to my file and know it is a valid PDF
# here begin the trick
with io.BytesIO() as buf:
z.open(target_file).write(buf)
buf.seek(0)
f = File.open(buf) # File is an import of django.core.files
rbe, created = RBE.objects.update_or_create(file=f)
With this code i get an error with write of z.open(...).write as below:
z.open(target_file).write(buf)
io.UnsupportedOperation: write
Thanks :)
Solution 1:[1]
So with intense hardwork 2 migraine and 1 ragequit i finally manage it.
Hope it might help someone
with ZipFile(io.BytesIO(response3.content), 'r') as z:
for target_file in z.namelist():
if target_file.endswith('pdf'):
with z.open(target_file) as myfile:
with io.BytesIO() as buf:
buf.write(myfile.read())
buf.seek(0)
file = File(buf, target_file) # still the File from django
rbe = RBE.objects.create(file=file, establishment=establishment)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Cyril Gainon |
