#27777: File object does not consistently open itself in context manager use
-----------------------------------------------+------------------------
               Reporter:  Raphael Gaschignard  |          Owner:  nobody
                   Type:  Uncategorized        |         Status:  new
              Component:  Uncategorized        |        Version:  1.10
               Severity:  Normal               |       Keywords:
           Triage Stage:  Unreviewed           |      Has patch:  0
    Needs documentation:  0                    |    Needs tests:  0
Patch needs improvement:  0                    |  Easy pickings:  0
                  UI/UX:  0                    |
-----------------------------------------------+------------------------
 Django's {{{File}}} object has an open method that will reseek the file to
 0,  and re-open the file if necessary (after closure).

 Unfortunately, the context manager does not automatically open a file. In
 particular, {{{FieldFile}}} relies on implicit opening via the file
 property to open a file, but caches the object internally. Since the
 context manager for {{{File}}} closes the file after use, this means that
 using the context manager twice in a row fails (since the file is not re-
 opened).

 {{{

 class C(Model):
     pdf = FileField(...)

 c = C.objects.get()

 with c.pdf as pdf: # file not opened yet
      print(c.size) # pdf.size accesses pdf.file, which will implicitly
 open the file
 # file is closed at the end of a context manager

  with c.pdf as pdf:
     print(c.size) # pdf.size now uses cached file, which is already
 closed!
 }}}


 I think it makes sense to have the context manager({{{__enter__}}}) call
 {{{open}}} on the object, so that files can be used in multiple context
 managers without having to to an open-ness check.

 our current workaround is to check for closed-ness on all context manager
 uses:
 {{{

 with c.pdf as pdf:
      if pdf.closed():
          pdf.open() # seeks the file to 0 and opens if necessary
      # do "real" work

 }}}

--
Ticket URL: <https://code.djangoproject.com/ticket/27777>
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 django-updates+unsubscr...@googlegroups.com.
To post to this group, send email to django-updates@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/047.7bb113c2fe8faffa4fbd45a3d42d5795%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to