it is simple wsgi application handles GET and POST methods
but i think someone can optimize algorithm for lesser code
#!/usr/bin/env python
"""
(c) Anton Dutov
WSGI example python 2.5.2
"""
import os ,re, time, cgi, StringIO
from wsgiref.simple_server import make_server
#==============================================================================
# Maximum line length for reading. (64KB)
# Fixes memory error when upload large files such as 700+MB ISOs.
readBlockSize = 65368
#==============================================================================
class WSGIReturn(Exception):
def __init__(self, value):
self.value = value
MAX_SIZE_POST = 2000000
def test_wsgi_app(env, response):
GET = {}
POST = {}
FILES = {}
headers = {'Content-Type':'text/html; charset=UTF-8'}
try:
# Parsing query sting as GET
for name, value in cgi.parse_qsl( env['QUERY_STRING'], True):
GET[ name ] = value
# If current method not POST
if env['REQUEST_METHOD'] != 'POST':
raise WSGIReturn('200 OK')
try: cLen = int( env['CONTENT_LENGTH'] )
except:
raise WSGIReturn('411 Length Required')
if cLen > MAX_SIZE_POST:
raise WSGIReturn('413 Request Entity Too Large')
cType, cTypeOpt = cgi.parse_header( env.get('CONTENT_TYPE',
'application/x-www-form-urlencoded') )
if cType.startswith("application/x-www-form-urlencoded"):
for name, value in cgi.parse_qsl( env['wsgi.input'].read
( cLen ), True):
POST[ name ] = value
raise WSGIReturn('200 OK')
if not cType.startswith("multipart/"): raise WSGIReturn('501
Not Implemented')
if 'boundary' not in cTypeOpt: raise WSGIReturn('400
Bad Request')
iBnd = re.compile("--" + re.escape( cTypeOpt['boundary'] ) +
"(--)?\r?\n")
iSock = env['wsgi.input']
iEnd = False
iHead = {}
iData = None
pLine = ''
tFile = ''
while not iEnd:
iLine = iSock.readline( readBlockSize )
iMatch = iBnd.match(iLine)
if (not iLine) or iMatch:
if iData:
iData.write( pLine[-2:]=='\r\n' and pLine[:-2] or
pLine[-1:]=='\n' and pLine[:-1])
dSize = iData.tell()
iData.seek(0)
iName = iHead['Content-Disposition'][1]['name']
if 'filename' in iHead['Content-Disposition']
[1].keys():
fName = iHead['Content-Disposition'][1]
['filename']
cType = iHead['Content-Type'][0]
FILES[ iName ] = { 'filename': fName,
'tmp_name': tFile, 'type': cType, 'size': dSize}
else:
POST[ iName ] = iData.read()
iData.close()
iHead = {}
iData = None
pLine = ''
iEnd = (not iLine) or (iMatch.group(1) is not None)
continue
if iData:
iData.write( pLine )
pLine = iLine
continue
if iLine not in ('\n','\r\n'):
h, v = iLine.split(":", 1)
iHead[ h.strip() ] = cgi.parse_header( v )
continue
elif len(iHead.keys()) == 0:
continue
tFile = '/tmp/wsgi_tmp_%.07f' % time.time()
if 'filename' in iHead['Content-Disposition'][1].keys()\
and iHead['Content-Disposition'][1]['filename']:
iData = open( tFile, 'w+b')
else:
iData = StringIO.StringIO()
raise WSGIReturn('200 OK')
except WSGIReturn, e:
response( e.value, headers.items() )
yield '''
Simple Form:
<form method="post">
<input name="test_note" type="text">
<input type="submit">
</form>'''
yield '''
File form
<form enctype="multipart/form-data" method="post">
<input name="test_file" type="file">
<input name="test_note" type="text">
<input type="submit">
</form>'''
yield '<h1>%s</h1><br>' % e.value
yield '<b>GET</b><hr>%s<hr>' % str(GET)
yield '<b>POST</b><hr>%s<hr>' % str(POST)
yield '<b>FILES</b><hr>%s<hr>' % str(FILES)
httpd = make_server('', 8000, test_wsgi_app )
httpd.serve_forever()
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"modwsgi" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/modwsgi?hl=en
-~----------~----~----~----~------~----~------~--~---