FileField should be a context manager

461 views
Skip to first unread message

Martin Chase

unread,
Dec 8, 2011, 3:07:03 PM12/8/11
to Django developers
This shouldn't be backwards incompatible, just implementing the
__exit__ and __enter__ methods.

Use case:

class Obj(models.Model):
file_field = models.FileField(upload_to="test")
...
obj = Obj()
obj.file_field.save(filename, content)
...
with obj.file_field.open() as a_file:
a_file.read()

Any reason I shouldn't make a ticket and patch for this?

- Martin Chase

Jacob Kaplan-Moss

unread,
Dec 8, 2011, 5:35:12 PM12/8/11
to django-d...@googlegroups.com

Sounds like a good idea to me - go ahead!

Jacob

Alex Gaynor

unread,
Dec 8, 2011, 5:36:53 PM12/8/11
to django-d...@googlegroups.com

--
You received this message because you are subscribed to the Google Groups "Django developers" group.
To post to this group, send email to django-d...@googlegroups.com.
To unsubscribe from this group, send email to django-develop...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-developers?hl=en.


It isn't alreayd?!?!  All file objects django exposes should be context managers, I thought I added that to a base mixin class a while ago, but apparently I didn't add it to the right thing.

Alex

--
"I disapprove of what you say, but I will defend to the death your right to say it." -- Evelyn Beatrice Hall (summarizing Voltaire)
"The people's good is the highest law." -- Cicero

Florian Apolloner

unread,
Dec 9, 2011, 1:49:43 PM12/9/11
to django-d...@googlegroups.com


On Thursday, December 8, 2011 11:36:53 PM UTC+1, Alex_Gaynor wrote:
It isn't alreayd?!?!  All file objects django exposes should be context managers, I thought I added that to a base mixin class a while ago, but apparently I didn't add it to the right thing.

Your memory serves you well ;) I wrote the patch and you commited it: https://code.djangoproject.com/ticket/14749 We added it only to File though.

Florian

Ian Kelly

unread,
Dec 9, 2011, 4:28:11 PM12/9/11
to django-d...@googlegroups.com

FieldFile inherits from File, though, so the methods are present. You
just have to do:

with obj.file_field as f:
...

instead of calling the open() method (which returns None), as the OP
tried. The only catch is that the __enter__ method does not open the
file, so if you close the file and then try the above, you'll get an
exception.

Reply all
Reply to author
Forward
0 new messages