Python自帶的 wsgiref
WSGI application
一个接口与两个参数
application(environ, start_response)
Demo#! /usr/bin/env python
# Our tutorial's WSGI server
from wsgiref.simple_server import make_server
def application(environ, start_response):
# Sorting and stringifying the environment key, value pairs
response_body = ['%s: %s' % (key, value)
for key, value in sorted(environ.items())]
response_body = '\n'.join(response_body)
status = '200 OK'
response_headers = [('Content-Type', 'text/plain'),
('Content-Length', str(len(response_body)))]
start_response(status, response_headers)
return [response_body]
# Instantiate the WSGI server.
# It will receive the request, pass it to the application
# and send the application's response to the client
httpd = make_server(
'localhost', # The host name.
8051, # A port number where to wait for the request.
application # Our application object name, in this case a function.
)
httpd.serve_forever()
wsgiref的simple_server說明
server的主要作用是接受client的請求,並把的收到的請求交給RequestHandlerClass處理,
RequestHandlerClass處理完成後回傳結果給client
WSGIServer繼承關系
WSGIServer-->HTTPServer-->SocketServer.TCPServer-->BaseServer
主要處理流程
serve_forever
_handle_request_noblock()
process_request
finish_request--> RequestHandlerClass()
close_request
serve_forever循環接受client請求, 如果有請求來,
經finish_request方法把請求交給RequestHandlerClass處理,
RequestHandlerClass調用handle()方法處理request,
WSGIRequestHandler的handle()方法把request又交給ServerHandler處理,
ServerHandler調用run執行application方法, 回傳綱頁的結果(含http header及綱頁內容)給client
WSGIRequestHandler繼承關系
WSGIRequestHandler-->BaseHTTPRequestHandler-->StreamRequestHandler-->BaseRequestHandler
BaseRequestHandler主要方法及處理流程
1、setup()
2、handle()
3、finish()
WSGIRequestHandler主要方法及處理流程
1、get_environ 增加env
2、handle (override)
handler = ServerHandler
handler.run(self.server.get_app())
ServerHandler繼承關系
ServerHandler-->SimpleHandler-->BaseHandler
run方法
setup_environ
self.result = application(self.environ, self.start_response)
self.finish_response