views:

98

answers:

2

Hi,

I am trying to implement a file upload solution using app engine and python. The thing which I am struggling with checking whether there is actually a file attached to the form or not. I am setting the enctype="multipart/form-data" and in principle it works. My python handler looks like this:

fileupload = self.request.POST["content"]

if not fileupload:
    return self.error(400)

This works if there is no file attached. However if there is a file attached it gives the following error:

  File "D:\eclipse_dev\workspace\test\src\handlers.py", line 351, in post
    if not fileupload:
  File "C:\Python25\lib\cgi.py", line 633, in __len__
    return len(self.keys())
  File "C:\Python25\lib\cgi.py", line 609, in keys
    raise TypeError, "not indexable"
TypeError: not indexable

How can I safely check that an upload is present before doing anything else in the handler?

Thanks for any help.

Regards, Robin

+1  A: 

How about:

fileupload = self.request.POST["content"]

if fileupload is None:
    return self.error(400)
Adam Crossland
I've tried this, but it does not trigger the error. I'm quite new to python. Is there any otherway of checking the value of a variable.
Robin_S
A: 

Well, I've got this working using:

import cgi
.
.
fileupload = self.request.POST["content"]

if not isinstance(fileupload, cgi.FieldStorage):
   return self.error(400)

Not sure if that's the best solution, but it seems to work.

Robin_S
This works for me so I am going to accept my own answer. I hope that's OK.
Robin_S