In Python, there is a loose concept of a "file-like" object.  This means 
that the object behaves like a file under duck-typing, meaning it has 
the right methods to be treated just as if it were a file.  But the 
concept is only loosely defined, and different file-like objects 
implement different numbers of methods, according to their abilities.  
HttpResponse does not implement seek(), and many consumers of file-like 
objects don't ever call seek(), so HttpResponses can be used as files in 
many cases.  ZipFile seems to be one case where it cannot, because 
ZipFile calls seek().

Both the HttpRequest docs 
(http://www.djangoproject.com/documentation/request_response/) and the 
Python file docs (http://docs.python.org/lib/bltin-file-objects.html) 
mention "file-like" obliquely, with reference to methods that are or are 
not, or may or may not, be implemented.

As Malcolm points out, seek() would require buffering, which you can 
provide by using an intermediary like StringIO.

--Ned.
http://nedbatchelder.com/blog

Malcolm Tredinnick wrote:
> On Thu, 2008-02-21 at 03:41 -0800, kip wrote:
>   
>> I thought I would be able to use an HttpResponse object as the file
>> argument for ZipFile, like this:
>>
>> response = HttpResponse(mimetype='application/zip')
>> response['Content-Disposition'] = 'attachment; filename=zipfile.zip'
>> file = zipfile.ZipFile(response, "w")
>>
>> but as soon as I try to write to it I get the error "'HttpResponse'
>> object has no attribute 'seek'".
>>
>> Am I missing something here?
>>     
>
> No, you have all the information that's required to diagnose what you're
> doing wrong. ZipFile apparently expects something with a seek() method
> and HttpResponse doesn't have one (since it outputs content in a linear
> fashion). You also cannot use HttpResponse as a lawn mower or  an a
> floatation device as it's similarly not appropriate.
>
> An HttpResponse is something that is designed to produce a string. That
> string is sent back to the user. Since ZipFile wants something that acts
> as a file, you need to turn the HttpResponse into something like that.
> Try using StringIO.
>
> Regards,
> Malcolm
>
>   

-- 
Ned Batchelder, http://nedbatchelder.com


--~--~---------~--~----~------------~-------~--~----~
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
-~----------~----~----~----~------~----~------~--~---

Reply via email to