def application (environ, start_response):
"""This demonstrates a minimal http upload CGI.
It can operate as a standard CGI or as a CGIplus script.
It accepts a GIF, JPEG or PNG file and displays it in the browser.
"""
# caters for Python 2 and 3
if hasattr(importlib,'reload'):
importlib.reload(cgi)
else:
reload(cgi)
if os.environ["REQUEST_METHOD"] == "POST":
display_uploaded_file (start_response)
else:
print_html_form (start_response)
return ('')
def print_html_form (start_response):
"""This prints out the html form. Note that the action is set to
the name of the script which makes this is a self-posting form.
In other words, this cgi both displays a form and processes it.
"""
HTML_TEMPLATE = """
WSGI_test4.py
WSGI_test4.py
"""
wsgi_write = start_response('200 OK',[('Content-type','text/html')])
wsgi_write (HTML_TEMPLATE % {'SCRIPT_NAME':os.environ['SCRIPT_NAME']})
def display_uploaded_file (start_response):
"""This display an image file uploaded by an HTML form.
"""
form = cgi.FieldStorage()
if not 'image_file' in form: return
fileitem = form['image_file']
if not fileitem.file: return
if not fileitem.filename: return
filename = fileitem.filename.lower()
status = '200 OK';
if filename.rfind(".gif") != -1:
response_headers = [('Content-type','image/gif')]
elif filename.rfind(".jpg") != -1:
response_headers = [('Content-type','image/jpeg')]
elif filename.rfind(".pdf") != -1:
print ("content-type: application/pdf")
elif filename.rfind(".png") != -1:
response_headers = [('Content-type','image/png')]
else:
wsgi_write = start_response(status,[('Content-type','text/html')])
wsgi_write ("Only GIFs, JPEGs, PDFs and PNGs handled by this test.")
return
response_headers += [('expires','01 Jan 2005 00:00:00 GMT')]
wsgi_write = start_response(status,response_headers)
while 1:
chunk = fileitem.file.read(100000)
if not chunk: break
wsgi_write (chunk)
del fileitem
import wasd;
import importlib
import cgi
import cgitb; cgitb.enable()
import os, sys
wasd.wsgi_run(application)