title: Django and dynamically generated images
body: <p>I have a view in my Django application that automatically creates an image using the PIL, stores it in the Nginx media server, and returns a html template with a img tag pointing to it's url.</p>
  
  <p>This works fine, but I notice an issue. For every 5 times I access this view, in 1 of them the image doesn't render.</p>
  
  <p>I did some investigation and I found something interesting, this is the HTTP response header when the image renders properly:</p>
  
  <pre><code>Accept-Ranges:bytes
  Connection:keep-alive
  Content-Length:14966
  Content-Type:image/jpeg
  Date:Wed, 18 Aug 2010 15:36:16 GMT
  Last-Modified:Wed, 18 Aug 2010 15:36:16 GMT
  Server:nginx/0.5.33
  </code></pre>
  
  <p>and this is the header when the image doesn't load:</p>
  
  <pre><code>Accept-Ranges:bytes
  Connection:keep-alive
  Content-Length:0
  Content-Type:image/jpeg
  Date:Wed, 18 Aug 2010 15:37:47 GMT
  Last-Modified:Wed, 18 Aug 2010 15:37:46 GMT
  Server:nginx/0.5.33
  </code></pre>
  
  <p>Notice the Content-Lenth equals to zero. What could have caused this? Any ideas on how could I further debug this problem?</p>
  
  <p><strong>Edit:</strong>
  When the view is called, it calls this "draw" method of the model. This is basically what it does (I removed the bulk of the code for clarity):</p>
  
  <pre><code>def draw(self):
      # Open/Creates a file
      if not self.image:
          (fd, self.image) = tempfile.mkstemp(dir=settings.IMAGE_PATH, suffix=".jpeg")
          fd2 = os.fdopen(fd, "wb")
      else:
          fd2 = open(os.path.join(settings.SITE_ROOT, self.image), "wb")
  
      # Creates a PIL Image
      im = Image.new(mode, (width, height))
  
      # Do some drawing
      .....
  
      # Saves
      im = im.resize((self.get_size_site(self.width),
                      self.get_size_site(self.height)))
      im.save(fd2, "JPEG")
      fd2.close()
  </code></pre>
  
  <p><strong>Edit2:</strong> This is website:
  <a href="http://xxxcnn7979.hospedagemdesites.ws:8000/cartao/99/" rel="nofollow noreferrer">http://xxxcnn7979.hospedagemdesites.ws:8000/cartao/99/</a></p>
  
  <p>if you keep hitting F5 the image on the right will eventually render.</p>