#26469: FieldFile.open() does not properly set mode when opening file
----------------------------------------------+--------------------
     Reporter:  george_edison                 |      Owner:  nobody
         Type:  Bug                           |     Status:  new
    Component:  Database layer (models, ORM)  |    Version:  1.9
     Severity:  Normal                        |   Keywords:
 Triage Stage:  Unreviewed                    |  Has patch:  0
Easy pickings:  0                             |      UI/UX:  0
----------------------------------------------+--------------------
 Consider the following model definition:

 {{{
 class Thing(models.Model):
     file = models.FileField(upload_to="things")
 }}}

 Let's suppose I have an existing model instance and I want to open the
 file for writing:

 {{{
 t = Thing.objects.get(pk=1)
 t.file.open('wb')
 t.file.write(data)
 }}}

 This raises an unexpected exception:

 {{{
 IOError: File not open for writing
 }}}

 Here's the source code for `FieldFile.open()`:

 {{{
 def open(self, mode='rb'):
     self._require_file()
     self.file.open(mode)
 }}}

 The second line in the body accesses `self.file` - a property which is
 defined as follows:

 {{{
 def _get_file(self):
     self._require_file()
     if not hasattr(self, '_file') or self._file is None:
         self._file = self.storage.open(self.name, 'rb')
     return self._file

 # ...

 file = property(_get_file, ...
 }}}

 If `self._file` is `None` (which is the case in my example above), the
 storage backend is then instructed to open the file with mode 'rb' instead
 of the mode that was originally passed to `FieldFile.open()`. The newly
 opened `File` instance is returned and control resumes in
 `FieldFile.open()` which invokes the `open()` method on the `File`
 instance.

 Here are the first few lines of `File.open()`:

 {{{
 def open(self, mode=None):
     if not self.closed:
         self.seek(0)
     elif self.name and os.path.exists(self.name):
         self.file = open(self.name, mode or self.mode)
     # ...
 }}}

 Since the file is already open, `not self.closed` evaluates to `True` and
 the file remains open in read-only mode. It is not possible to write to
 the file.

--
Ticket URL: <https://code.djangoproject.com/ticket/26469>
Django <https://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 unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/056.f3077e03e8b34bc9d5d285f0d6d936a6%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to