I am using Django to read an ajax uploaded file to store it in a model. The upload request contains the raw uploaded image data.
def my_view(request):
upload = request
model_instance.image_field.save(uniquename, ContentFile(upload.read()))
If it matters, I am using AmazonS3 as my storage backend for uploaded files.
Somewhere in the function that contains this code, I have a memory leak.
Do I need to call upload.close()
after doing this, to free resources/memory?
Or is my memory problem coming from some other issue, elsewhere in this function?
The python garbage collector will close files when they are no longer referenced.
If your upload
variable is a local variable in a function, it'll be cleared when the function returns. Thus, the file upload
referred to will be automatically closed during the normal garbage collection cycle.
That said, it's probably better to close the file. You can use the file as a context manager, and it'll be automatically closed when the context is exited:
with open('yourfilepath.ext') as upload:
model_instance.image_field.save(uniquename, ContentFile(upload.read()))
If upload
is something Django produces for you, open and ready, you can still have it automatically closed with the contextlib.closing
decorator:
import contextlib
with contextlib.closing(upload):
model_instance.image_field.save(uniquename, ContentFile(upload.read()))
To answer the rest of your question: your leak is most likely elsewhere.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With