WSGI協(xié)議
介紹
- Python Web開發(fā)中,后臺(tái)服務(wù)端程序可以分為兩個(gè)部分:Web Server 和 Web Application
- Web Server負(fù)責(zé)通過socket監(jiān)聽client的請(qǐng)求,當(dāng)出現(xiàn)請(qǐng)求時(shí),調(diào)用Web Application,進(jìn)行具體的邏輯處理。
- WSGI是 Web Server 和 Web Application 之間的一種協(xié)議或規(guī)范。旨在解決眾多 web 框架和web server軟件的兼容問題。只要是實(shí)現(xiàn)了WSGI協(xié)議的Web 框架就可以和實(shí)現(xiàn)了WSGI協(xié)議的Web Server進(jìn)行組合使用。

WSGI Application
WSGI規(guī)定Web Application:
- 需要是一個(gè)可調(diào)用的對(duì)象。(即應(yīng)用程序可以是函數(shù),實(shí)現(xiàn)iter方法的Class,實(shí)現(xiàn)call方法的Object)
- 可調(diào)用對(duì)象需要接收兩個(gè)參數(shù): environ 和 start_response(environ包含了所有請(qǐng)求有關(guān)的信息,包括headers, body等。start_response是一個(gè)回調(diào)函數(shù),后臺(tái)服務(wù)處理完業(yè)務(wù)后調(diào)用這個(gè)函數(shù)將response傳給wsgi server,server再傳給客戶端。)
- 可調(diào)用對(duì)象要返回一個(gè)值,這個(gè)值是可迭代的
例如:
# my_wsgi_app.py
HELLO_WORLD = b"Hello world!\n"
# callable function
def simple_app(environ, start_response):
"""Simplest possible application object"""
status = '200 OK'
response_headers = [('Content-type', 'text/plain')]
start_response(status, response_headers)
return [HELLO_WORLD]
# callable class
class AppClass:
"""Produce the same output, but using a class
(Note: 'AppClass' is the "application" here, so calling it
returns an instance of 'AppClass', which is then the iterable
return value of the "application callable" as required by
the spec.
If we wanted to use *instances* of 'AppClass' as application
objects instead, we would have to implement a '__call__'
method, which would be invoked to execute the application,
and we would need to create an instance for use by the
server or gateway.
"""
def __init__(self, environ, start_response):
self.environ = environ
self.start = start_response
def __iter__(self):
status = '200 OK'
response_headers = [('Content-type', 'text/plain')]
self.start(status, response_headers)
yield HELLO_WORLD
# callable object
class ApplicationObj(object):
def __call__(self, environ, start_response):
return [HELL_WORLD]
WSGI Server
- 一個(gè)WSGI Server需要完成的工作是:
- 監(jiān)聽某端口
- 當(dāng)收到用戶請(qǐng)求時(shí)對(duì)應(yīng)用程序需要的兩個(gè)參數(shù)environ 和 start_response進(jìn)行設(shè)置
- 調(diào)用WSGI Application
- 迭代訪問應(yīng)用程序的返回結(jié)果,并將其傳回客戶端
一個(gè)簡(jiǎn)易的WSGI Server:
# my_wsgi_server.py
import socket
import sys
class WSGIServer:
def __init__(self):
self.listener = socket.socket()
self.listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.listener.bind(('0.0.0.0', 4000))
self.listener.listen(1)
print('Serving HTTP on 0.0.0.0 port 4000....')
self.app = None
self.headers_set = None
def set_app(self, application):
self.app = application
def start_response(self, status, headers):
self.headers_set = [status, headers]
def server_forever(self):
while True:
listener = self.listener
client_connnection, client_address = listener.accept()
print(f'server received connection from:{client_address}')
request = client_connnection.recv(1024)
print(f'request we received:{request}')
method, path, _ = request.split(b' ',2)
environ = {
'wsgi.version': (1, 0),
'wsgi.url_scheme': 'http',
'wsgi.input': request,
'wsgi.errors': sys.stderr,
'wsgi.multithread': False,
'wsgi.multiprocess': False,
'wsgi.run_once': False,
'REQUEST_METHOD': method.decode('utf-8'),
'PATH_INFO': path.decode('utf-8'),
'SERVER_NAME': '127.0.0.1',
'SERVER_PORT': '4000',
}
app_result = self.app(environ, self.start_response)
response_status, response_headers = self.headers_set
response = f'HTTP/1.1 {response_status}\r\n'
for header in response_headers:
response += f'{header[0]}:{header[1]}\r\n'
response += '\r\n'
response = response.encode('utf-8')
for data in app_result:
response += data
print(response)
client_connnection.send(response)
client_connnection.close()
if __name__ == '__main__':
if len(sys.argv) < 2:
sys.exit('Argv Error')
app_path = sys.argv[1]
module, app = app_path.split(":")
module = __import__(module)
app = getattr(module, app)
server = WSGIServer()
server.set_app(app)
server.server_forever()
- 通過以下命令運(yùn)行server和application:
python my_wsgi_server.py my_wsgi_application:simple_app
用瀏覽器訪問localhost:4000,屏幕中就會(huì)顯示 Hello world!
基于WSGI的Web框架
Web Application
一個(gè)Web Application框架應(yīng)具備的最基本功能包括:
- 請(qǐng)求體解析
- 路由
- session管理
如果不采用前后端分離架構(gòu),框架需支持:
- 模板引擎
- 靜態(tài)文件支持
如果支持關(guān)系型數(shù)據(jù)庫操作,框架需支持:
- ORM功能
常見的Web applicatioan有Django, Flask。它們都支持上述的基本功能和模板引擎。Flask本身不支持ORM,但可與ORM框架sqlalchemy結(jié)合。
Web Server
一個(gè)Web Server框架應(yīng)具備socket監(jiān)聽并調(diào)用Web application的功能。
如果希望Web Server有更好的并發(fā)性能,需要實(shí)現(xiàn)負(fù)載均衡。
常見的Web Server有Gunicorn, uwsgi。