Search code examples
pythonuploadcgimosso

python upload - where are tmp/FILES?


I'm running python 2.4 from cgi and I'm trying to upload to a cloud service using a python api. In php, the $_FILE array contains a "tmp" element which is where the file lives until you place it where you want it. What's the equivalent in python?

if I do this

fileitem = form['file']

fileitem.filename is the name of the file

if i print fileitem, the array simply contains the file name and what looks to be the file itself.

I am trying to stream things and it requires the tmp location when using the php api.


Solution

  • The file is a real file, but the cgi.FieldStorage unlinked it as soon as it was created so that it would exist only as long as you keep it open, and no longer has a real path on the file system.

    You can, however, change this...

    You can extend the cgi.FieldStorage and replace the make_file method to place the file wherever you want:

    import os
    import cgi
    
    class MyFieldStorage(cgi.FieldStorage):
        def make_file(self, binary=None):
            return open(os.path.join('/tmp', self.filename), 'wb')
    

    You must also keep in mind that the FieldStorage object only creates a real file if it recieves more than 1000B (otherwise it is a cStringIO.StringIO)

    EDIT: The cgi module actually makes the file with the tempfile module, so check that out if you want lots of gooey details.