#13809: FileField open method is only accepting 'rb' modes
------------------------------------------------+---------------------------
Reporter: canassa | Owner: nobody
Status: reopened | Milestone:
Component: File uploads/storage | Version: 1.2
Resolution: | Keywords:
Triage Stage: Accepted | Has patch: 0
Needs documentation: 0 | Needs tests: 0
Patch needs improvement: 0 |
------------------------------------------------+---------------------------
Changes (by yishai@…):
* component: Documentation => File uploads/storage
Comment:
Replying to [comment:3 russellm]:
> I don't think it's unreasonable to expect that when you access a file
through a model field, it will be open ready for reading. The best
solution I can see here is documenting the fact that files are opened "rb"
when accessed, and if you want to perform write operations, you'll need to
close the file first.
I think this is a little more subtle than that; since the underlying file
object is "automatically" opened (with 'rb' mode) upon direct access, the
main reason one would call {{{FieldFile.open}}} is to open the file in
another mode. Having {{{FieldFile.open(mode='w')}}} return a bad file
descriptor (for writing) without complaining is hardly optimal.
>
> I'm open to any other suggestions, but I'll accept this as a
documentation issue for now.
Even if deciding that one should always close first before opening the
file for writing, calling {{{FieldFile.close()}}} is not enough as it will
skip the underlying file object if it was not opened yet. This code will
not work:
{{{
obj = MyModel.objects.get(pk=1)
obj.myFileField.close() # would expect this to close the underlying file
object, so it's ready to be reopened for writing
obj.myFileField.open('w')
obj.myFileField.write('something')
}}}
If we rewrite {{{FieldFile.close()}}} from:
{{{
def close(self):
file = getattr(self, '_file', None)
if file is not None:
file.close()
}}}
to:
{{{
def close(self):
self.file.close()
}}}
then the above snippet will work as advertised - the underlying file will
be opened (rb) and then closed again. Currently the snippet needs to be:
{{{
obj = MyModel.objects.get(pk=1)
obj.myFileField.file.close() # works, but hardly nice
obj.myFileField.open('w')
obj.myFileField.write('something')
}}}
which works, but accessing the underlying (undocumented?) file object
directly is probably not what we really want here.
--
Ticket URL: <http://code.djangoproject.com/ticket/13809#comment:4>
Django <http://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/django-updates?hl=en.