WSGI(Web Server Gateway Interface)不是服务器,python模块,框架,API或者任何软件,只是一种规范,描述web server如何与web application通信的规范。
WSGI协议主要包含了server和application两部分
1.web server/getway:接受客户端的请求,并提供并发响应,将request转发给applicaiton,将application返回的response返回给客户端。每个并发中的线程调用web application处理业务逻辑。通常采用C/C++编写,代表有:apache、nginx、IIS。
2.web application/framework:接收server的request,并将处理结果response返回给server。application中可以包含多个栈式的中间件(middlewares),这些中间件必须同时实现server和application,因此可以在WSGI服务器和WSGI服务器之间起到调节作用。
参考:
https://www.cnblogs.com/-wenli/p/10884168.html
简介
WSGI不是server,不是module,不是framework,不是API,不是任何一种software.它只是一个接口规范,规定server和application如何交流.具体规范可以在PEP 3333查看.
WSGI通过callable object实现,比如function,method,class,或者拥有object.__call__
的instance.callable object必须:
1.接收两个positional param:
1)(dictionary) CGI 变量
2)回调函数,来发送HTTP status code/message 和 HTTP headers 去服务端
2.返回(str)response body
Application Interface
# The application interface is a callable object
def application (environ,start_response):# 两个参数,第一个是CGI,第二个是callback
# Build the response body possibly
# using the supplied environ dictionary
response_body = 'Request method: %s' % environ['REQUEST_METHOD']
# HTTP response code and message
status = '200 OK'
# HTTP headers expected by the client
# They must be wrapped as a list of tupled pairs:
# [(Header name, Header value)].
response_headers = [
('Content-Type', 'text/plain'),
('Content-Length', str(len(response_body)))
]
# Send them to the server using the supplied function
start_response(status, response_headers)
# Return the response body. Notice it is wrapped
# in a list although it could be any iterable.
return [response_body]
Environment Dictionary
#! /usr/bin/env python
# Python's bundled 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] # 不能改成return response_body,因为会遍历返回值,如果不是列表则会遍历字符串,所以会变慢
# Instantiate the server
httpd = make_server (
'localhost', # The host name
8051, # A port number where to wait for the request
application # The application object name, in this case a function
)
# Wait for a single request, serve it and quit
httpd.handle_request()
Response Iterable
Parsing the Request - Get
Parsing the Request - Post
参考:
http://wsgi.tutorial.codepoint.net/intro