Hello, I have found something a bit odd. I wanted to send an on-the-fly generated file as a response and then delete the file from my disk. I tried to implement it using a file wrapper which deletes the file when it is closed. It worked fine until I tried what happens if a user cancels his request (simply clicks on the "Stop loading this page" button during running the view function or during downloading the generated file). In that case the file wrapper could not delete the file because its close() method was not called at all.
I tried a trick which worked: generate the file as a tempfile.NamedTemporaryFile which can automatically delete itself, then rewind it to its beginning and wrap the open file. When the request was canceled, the close() method was not called but the file was deleted after some time anyway. However, I did not like this solution because of rewinding, leaving open files on their own etc. I started to look for a reason why the close method of the file wrapper is not called. And I found the answer in Django's core/servers/basehttp.py. There is a ServerHandler class with run() method. Its code is closed into a try-except. The except handles error by calling self.handle_error(). Unfortunately, this method does not handle the open file. It just tries to response something reasonable to the user. It seems the file should be closed if an exception in handle_error method occurs but this does not happen for some reason. I consider this as a bug of Django. When I added a single line into handle_error() (just after a logging of the raised exception): if hasattr(self.result,'close'): self.result.close() the file wrapper's close() was called as planned. No side effects has been observed so far. I feel this is a better solution then the trick with NamedTemporaryFile, although I am not 100% sure this is correct. Has anybody experienced something similar? Do you have a better solution? Br, Jyrki -- You received this message because you are subscribed to the Google Groups "Django users" 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-users?hl=en.

