本文地址:http://blog.csdn.net/spch2008/article/details/8997579
本文中程序的放置路径及运行方式在 Window + Apache + WSGI 配置指明。
第一WSGI程序
def spch_wsgi(environ, start_response):
status = '200 OK'
response_headers = [('Content-Type', 'text/plain')]
start_response(status, response_headers)
return ['Hello World!']
application = spch_wsgi
WSGI server检索application函数, 并传递两个参数environ, start_response。
environ 为一个字典,包含环境变量。
start_response 为一个函数, 用于返回状态信息。
一个WSGI程序要完成两件事:
其一:返回HTTP header。本例中, 状态‘200 OK‘, 表明一切正常。
其二:返回一个iterable containing, 本例中是一个list。
输出environ信息
def application(environ, start_response):
response_body = ""
for k in environ:
tmp = "%s = %s \n" % (k, environ[k])
response_body += tmp
status = '200 OK'
response_headers = [('Content-Type', 'text/plain')]
start_response(status, response_headers)
return [response_body]
wsgi.multiprocess = False
SERVER_PROTOCOL = HTTP/1.1
SERVER_SOFTWARE = Apache/2.2.22 (Win32) mod_wsgi/3.3 Python/2.7.4
SCRIPT_NAME = /wsgi
mod_wsgi.handler_script =
SERVER_SIGNATURE =
REQUEST_METHOD = GET
PATH_INFO =
PATHEXT = .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
QUERY_STRING =
HTTP_USER_AGENT = Mozilla/5.0 (Windows NT 6.2; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0
HTTP_CONNECTION = keep-alive
SERVER_NAME = localhost
REMOTE_ADDR = 127.0.0.1
mod_wsgi.request_handler = wsgi-script
wsgi.url_scheme = http
mod_wsgi.callable_object = application
SERVER_PORT = 80
mod_wsgi.version = (3, 3)
mod_wsgi.input_chunked = 0
SERVER_ADDR = 127.0.0.1
DOCUMENT_ROOT = D:/Program Files (x86)/Apache Software Foundation/Apache2.2/htdocs
mod_wsgi.process_group =
COMSPEC = C:\Windows\system32\cmd.exe
SCRIPT_FILENAME = C:/wsgi_app/wsgi_handler.py
SERVER_ADMIN = admin@localhost.com
wsgi.input = <mod_wsgi.Input object at 0x01379DE0>
HTTP_HOST = localhost
wsgi.multithread = True
SystemRoot = C:\Windows
REQUEST_URI = /wsgi
HTTP_ACCEPT = text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
WINDIR = C:\Windows
wsgi.version = (1, 1)
GATEWAY_INTERFACE = CGI/1.1
wsgi.run_once = False
wsgi.errors = <mod_wsgi.Log object at 0x01379D40>
REMOTE_PORT = 64214
HTTP_ACCEPT_LANGUAGE = zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3
mod_wsgi.application_group = 192.168.209.1|/wsgi
mod_wsgi.script_reloading = 1
wsgi.file_wrapper = <built-in method file_wrapper of mod_wsgi.Adapter object at 0x012E1770>
HTTP_ACCEPT_ENCODING = gzip, deflate
上述代码也可以通过类来实现,类中要重载__call__,这样的好处是可以从其它类继承,复用代码。
class MyApp:
def __call__(self, environ, start_response):
response_body = ['Hello World!']
status = '200 OK'
response_headers = [('Content-Type', 'text/plain')]
start_response(status, response_headers)
return response_body
application = MyApp()