Python on the Web - A Last Example (Page 5 of 6 )
So far you've seen how you can use Python to get forms data, create cookies and send email... in this last example we'll be using as much of what you've learned here as we can (without going over the top).
#!/usr/bin/env python
import cgi, os, sys
sys.stderr = sys.stdout
def uploads(form, name, path, *args):
if form.has_key(name):
#If the form field exists if 'form' then parse the filename to point
#at the desired location.
path = os.path.join(path, os.path.basename(form[name].filename))
for each in args:
#Loop over any available file types and check if the file being
# uploaded is the right format. Checks if the file already exists
if path.endswith(each) and not os.path.isfile(path):
file(path, 'wb').write(str(form[name].value))
#Return True to indicate the file was uploaded successfully.
return True
if __name__ == '__main__':
form = cgi.FieldStorage()
print 'Content-Type: text/htmln'
if uploads(form, 'upload', '', '.txt', '.zip'):
#If the upload was successful then print a message.
print 'Finished uploading file...'
else:
print 'Failed to upload file. Please visit our help center at...'
If you want to give this a go, you'll need a form set up for file upload; something like this one...
<form name="upload" method="POST" action="upload.py" enctype="multipart/form-data">
<input name="upload" type="file" /><input type="submit" name="submit" />
</form>
This is pretty small as functions go, but there's quite a lot going on right from the beginning!
As in our other examples, this starts by importing the modules we need into the programs global namespace. Unlike these examples, our next line redirects errors to standard output; this simply sends error messages, as you would get from Python normally to the web browser instead of the error log.
If you're going to use Python for CGI, then you should definitely take a look at the 'cgitb' module at http://www.python.org/doc/2.2.3/lib/module-cgitb.html
Next: Inside uploads()... >>
More Python Articles
More By Mark Lee Smith