[Zope] RE: Q: How to check if Image exists (inside REQUEST object)?

Alexander Staubo alex@mop.no
Mon, 25 Oct 1999 12:22:05 +0200


> From: Samu Mielonen [mailto:ex@uiah.fi]
> Sent: 25. oktober 1999 11:59
> To: Alexander Staubo
> Cc: Zope Mailing List
> Subject: RE: Q: How to check if Image exists (inside REQUEST object)?

> My question:
> > > You wouldn't know how to test if a REQUEST.image1 exists 
> or not before
> > > actually using manage_addImage or manage_upload on that image?
> 
> Alexander Staubo [mailto:alex@mop.no] :
> > Test on the content type of the file object, or check 
> whether the file
> > object's file attribute contains a non-zero file (eg., call 
> seek(0, 2)
> > and then check if tell() returns > 0).
> 
> > The following code illustrates the latter:
> > 
> >   <dtml-if "REQUEST.has_key('MyFile')">
> >     <dtml-if "(MyFile.file.seek(0, 2) or MyFile.file.tell()) > 0">
> >       <!-- file is valid -->
> >     </dtml-if>
> >   </dtml-if>
> 
> Excellent! Thanks! It works. I don't yet understand how, but 
> it works.

When ZPublisher receives an HTTP request, it builds the REQUEST variable
from the request header. In the case of POSTs, in addition the header
the request also contains a body. When using the multipart/form-data
encoding type, this body follows a standard MIME format, wherein each
piece of named data is bundled in a "multipart" attachment.

Uploaded "files" have a content type, file name and binary contents,
usually base64-encoded. For each such attachment, ZPublisher creates a
FileObject instance (see lib/Python/ZPublisher/HTTPRequest.py). This
FileObject has a filename attribute, a headers dictionary attribute, and
a file attribute. The file attribute behaves like a standard Python
file, and contains methods such as tell(), seek(), read() and so forth.

Given such a variable MyFile, the Python expression

	(MyFile.file.seek(0, 2) or MyFile.file.tell()) > 0

will yield the value 1 if tell() returns > 0. The seek() doesn't return
anything, so it will evaluate to None. This is handy shortcut in the
Python language to make verbose tests more compact. It does not enhance
readability, but reduces typing and in the context of Zope, faster than
doing each operation separately.

Anyway, a simpler test is checking the file name. Just testing whether
the filename attribute is empty should do it.

[snip]

> Thanks again,
> 	Samu Mielonen

-- 
Alexander Staubo             http://www.mop.no/~alex/
The difference between theory and practice is that, in theory,
there is no difference between theory and practice.