WSGI接口
无论多么复杂的Web应用程序,入口都是一个WSGI处理函数。
HTTP请求的所有输入信息都可以通过environ获得,HTTP响应的输出都可以通过start_response()加上函数返回值作为Body。
其实一个Web App,就是写一个WSGI的处理函数,针对每个HTTP请求进行响应。
#hello.py def application(environ, start_response): start_response(‘200 OK‘, [(‘Content-Type‘, ‘text/html‘)]) return ‘<h1>Hello, web!<h1>‘
#server.py from wsgiref.simple_server import make_server from hello import application httpd = make_server(‘‘, 8000, application) print ‘Serving Http on port 8000‘ httpd.serve_forever()
python cgi模块
A CGI script is invoked by an HTTP server, usually to process user input submitted through an HTML <FORM> or <ISINDEX> element.
往往用 FieldStorage 去处理表单数据,且FieldStorage的实例就像字典一样处理。
但如果表单中提交的数据为空, 那么那个数据将不会在FieldStorage中显示, 但可以通过设置keep_blank_values=True使其显示
ps:
If the submitted form data contains more than one field with the same name, the object retrieved by form[key] is not a FieldStorage or MiniFieldStorage instance but a list of such instances.
If a field represents an uploaded file, accessing the value via the value attribute or the getvalue() method reads the entire file in memory as a string. This may not be what you want. You can test for an uploaded file by testing either the filename attribute or the file attribute. You can then read the data at leisure from the file attribute.
#form数据在self._environ[‘wsgi.input‘]中, request的数据在self._environ中 form = cgi.FieldStorage(fp=self._environ[‘wsgi.input‘], environ=self._environ, keep_blank_values=True) normal = form[key].value if isinstance(form[key], list): fileitem = form[key] if fileitem.filename: # It‘s an uploaded file; count lines linecount = 0 while 1: line = fileitem.file.readline() if not line: break linecount = linecount + 1