Tuesday, February 1, 2022

Resource leaks from FieldFile's implicit open?

Dear group,

despite a lot of reading and searching I still don't understand how FieldFiles work.

The documentation at https://docs.djangoproject.com/en/4.0/ref/models/fields/#django.db.models.fields.files.FieldFile says:

> The API of FieldFile mirrors that of File, with one key difference: The object wrapped by the class is not necessarily a wrapper around Python's built-in file object. Instead, it is a wrapper around *** the result of the Storage.open() method ***, which may be a File object, or it may be a custom storage's implementation of the File API.

(I added markers to indicate the portion that I have trouble with.)

As far as I understand this, whenever a `FieldFile` is instantiated, `Storage.open()` is called. Thus, if the underlying storage is the `FileSystemStorage`, a Python file object is opened.

However, how is this file handle closed again?

It looks as if it stays open until garbage collected, that is, possibly for a very long time.

Another consequence besides the potential resource leak seems to be that the implicit open will raise an exception if the file that the `FieldFile` refers to doesn't exist. As I don't exactly understand when this opening occurs, a lot of code must be wrapped in try-except blocks to handle this?

Best regards,
Carsten

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/eb81a066-4328-4f36-87a2-ead61aba6679%40cafu.de.

No comments:

Post a Comment