先說下 WSGI 的表面意思,Web Server Gateway Interface 的縮寫,即 Web 服務器網關介面,
之前不知道 WSGI 意思的伙伴,看了上面的解釋后,我估計也還是不清楚,所以下面結合實際場景說明,先讓大家有個大致的認識,最后我們再自己實作一個,加深對 WSGI 的理解,
我們現在使用 Python 撰寫 Web 應用,可以用比較流行的 Flask、Django 框架,也可以按自己的想法直接寫一個,可選的服務器軟體也特別多,比如常見的有 Apache、Nginx、IIS 等,除此外,也有很多小眾的軟體,但是,現在問題來了,我該怎么部署?在沒有 WSGI 規范之前,一個服務器調度 Python 應用是用這種方式,另一款服務器使用的是那種方式,這樣的話,撰寫出來的應用部署時只能選擇局限的某個或某些服務器,達不到通用的效果,
注意:下文中的代碼基于 Python 3.6 撰寫,
假如有這么一個服務器
wsgi/server.py
# coding=utf-8
import socket
listener = socket.socket()
listener.setsockopt(socket.SOL_SOCKET,
socket.SO_REUSEADDR, 1)
listener.bind(('0.0.0.0', 8080))
listener.listen(1)
print('Serving HTTP on 0.0.0.0 port 8080 ...')
while True:
client_connection, client_address = \
listener.accept()
print(f'Server received connection'
f' from {client_address}')
request = client_connection.recv(1024)
print(f'request we received: {request}')
response = b"""
HTTP/1.1 200 OK
Hello, World!
"""
client_connection.sendall(response)
client_connection.close()
實作比較簡單,就是監聽 8080 埠,如果有請求在終端進行列印,并回傳 Hello, World! 的回應,
終端中啟動服務器
? wsgi python server.py
Serving HTTP on 0.0.0.0 port 8080 ...
再開一個終端,請求下
? ~ curl 127.0.0.1:8080
HTTP/1.1 200 OK
Hello, World!
說明服務器作業正常,
另外有一個 Web 應用
wsgi/app.py
# coding=utf-8
def simple_app():
return b'Hello, World!\r\n'
現在要部署(也就是讓這個整體跑起來),簡單粗暴的做法就是在服務器里面直接呼叫 app 中相應的方法,就像這樣
wsgi/server2.py
# coding=utf-8
import socket
listener = socket.socket()
listener.setsockopt(socket.SOL_SOCKET,
socket.SO_REUSEADDR, 1)
listener.bind(('0.0.0.0', 8080))
listener.listen(1)
print('Serving HTTP on 0.0.0.0 port 8080 ...')
while True:
client_connection, client_address = \
listener.accept()
print(f'Server received connection'
f' from {client_address}')
request = client_connection.recv(1024)
print(f'request we received: {request}')
from app import simple_app
response = 'HTTP/1.1 200 OK\r\n\r\n'
response = response.encode('utf-8')
response += simple_app()
client_connection.sendall(response)
client_connection.close()
運行腳本
注意:因為使用埠相同的緣故,請先關閉上次的腳本,然后再執行,不然會由于埠沖突而報錯,
? wsgi python server2.py
Serving HTTP on 0.0.0.0 port 8080 ...
然后請求一下看看效果
? ~ curl 127.0.0.1:8080
Hello, World!
嗯,可以了,但是,上面的服務器和應用整體是跑起來了,那么我換一個服務器或者應用呢,由于服務器與應用之間怎么互動完全沒有規范,比如服務器應該如何把請求資訊傳給應用,應用處理完畢后又怎么告訴服務器開始回傳回應,如果都是各搞各的,服務器需要定制應用,應用也要定制服務器,這要一個應用能跑起來也太麻煩了點吧,
所以,WSGI 的出現就是為了解決上面的問題,它規定了服務器怎么把請求資訊告訴給應用,應用怎么把執行情況回傳給服務器,這樣的話,服務器與應用都按一個標準辦事,只要實作了這個標準,服務器與應用隨意搭配就可以,靈活度大大提高,
WSGI 規范了些什么,下圖能很直觀的說明,
[圖片]
首先,應用必須是一個可呼叫物件,可以是函式,也可以是實作了 __call__() 方法的物件,
每收到一個請求,服務器會通過 application_callable(environ, start_response) 呼叫應用,
應用在處理完畢準備回傳資料的時候,先呼叫服務傳給它的函式 start_response(status, headers, exec_info),最后再回傳可迭代物件作為資料,(不理解可迭代物件的伙伴可以看下我之前的一篇文章《搞清楚Python的迭代器、可迭代物件、生成器》)
其中,environ 必須是一個字典,包括了請求的相關資訊,比如請求方式、請求路徑等等,start_response 是應用處理完畢后,需要呼叫的函式,用于告訴服務設定回應的頭部資訊或錯誤處理等等,
status 必須是 999 Message here 這樣的字串,比如 200 OK、404 Not Found 等,headers 是一個由 (header_name, header_value) 這樣的元祖組成的串列,最后一個 exec_info 是可選引數,一般在應用出現錯誤的時候會用到,
知道了 WSGI 的大致概念,下面我們來實作一個,
首先是應用
wsgi/wsgi_app.py
# coding=utf-8
def simple_app(environ, start_response):
status = '200 OK'
response_headers = [('Content-type', 'text/plain')]
start_response(status, response_headers)
return [f'Request {environ["REQUEST_METHOD"]}'
f' {environ["PATH_INFO"]} has been'
f' processed\r\n'.encode('utf-8')]
這里定義了一個函式(可呼叫物件),它可以使用服務器傳給它的請求相關的內容 environ,這里使用了 REQUEST_METHOD 和 PATH_INFO 資訊,在回傳之前呼叫了 start_response,方便服務器設定一些頭部資訊,
然后是服務器
wsgi/wsgi_server.py
# coding=utf-8
import socket
listener = socket.socket()
listener.setsockopt(socket.SOL_SOCKET,
socket.SO_REUSEADDR, 1)
listener.bind(('0.0.0.0', 8080))
listener.listen(1)
print('Serving HTTP on 0.0.0.0 port 8080 ...')
while True:
client_connection, client_address = \
listener.accept()
print(f'Server received connection'
f' from {client_address}')
request = client_connection.recv(1024)
print(f'request we received: {request}')
headers_set = None
def start_response(status, headers):
global headers_set
headers_set = [status, headers]
method, path, _ = request.split(b' ', 2)
environ = {'REQUEST_METHOD': method.decode('utf-8'),
'PATH_INFO': path.decode('utf-8')}
from wsgi_app import simple_app
app_result = simple_app(environ, start_response)
response_status, response_headers = 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
client_connection.sendall(response)
client_connection.close()
服務器監聽相關代碼沒怎么變化,主要是處理請求的時候有些不同,
首先定義了 start_response(status, headers) 函式,自身并不會呼叫,
然后呼叫應用,將當前的請求資訊 environ 和上面的 start_response 函式傳給它,讓其自己決定使用什么請求資訊以及在處理完成準備回傳資料之前呼叫 start_response 設定頭部資訊,
好了,啟動服務器后(即執行服務器代碼,和之前的類似,這里不贅述),然后請求看看結果
? ~ curl 127.0.0.1:8080/user/1
Request GET /user/1 has been processed
嗯,程式是正常的,
上面為了說明,代碼耦合性較大,如果服務器需要更換應用的話,還得修改服務器代碼,這顯然是有問題的,現在原理差不多說清楚了,我們把代碼優化下
wsgi/wsgi_server_oop.py
# coding=utf-8
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', 8080))
self.listener.listen(1)
print('Serving HTTP on 0.0.0.0'
' port 8080 ...')
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 serve_forever(self):
while True:
listener = self.listener
client_connection, client_address = \
listener.accept()
print(f'Server received connection'
f' from {client_address}')
request = client_connection.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': '8080',
}
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
client_connection.sendall(response)
client_connection.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.serve_forever()
基本原理沒變,只是使用了面向物件的方式修改了下原來的代碼,同時 environ 添加了一些必要的環境資訊,
可以使用以前的應用
? wsgi python wsgi_server_oop.py wsgi_app:simple_app
Serving HTTP on 0.0.0.0 port 8080 ...
請求
? ~ curl 127.0.0.1:8080/user/1
Request GET /user/1 has been processed
得到和之前相同的結果,
Flask 應用能行嗎?來試一試,先新建一個
wsgi/flask_app.py
# coding=utf-8
from flask import Flask
from flask import Response
flask_app = Flask(__name__)
@flask_app.route('/user/<int:user_id>',
methods=['GET'])
def hello_world(user_id):
return Response(
f'Get /user/{user_id} has been'
f' processed in flask app\r\n',
mimetype='text/plain'
)
重新啟動服務器
? wsgi python wsgi_server_oop.py flask_app:flask_app
Serving HTTP on 0.0.0.0 port 8080 ...
請求
? ~ curl 127.0.0.1:8080/user/1
Get /user/1 has been processed in flask app
因為 Flask 也是遵守 WSGI 規范的,所以執行也沒有問題,
至此,一個粗略的 WSGI 規范就實作了,雖說代碼不優雅,一些核心的東西還是體現出來了,不過畢竟忽略了很多東西,比如錯誤處理等,要在生產環境中使用的話還遠遠不夠,想知道得更全面的伙伴可以去看看 PEP 3333,
目前流行的 Web 應用框架比如 Django、Bottle 等,服務器 Apahce、Nginx、Gunicorn 等也都支持這個規范,因此,框架和應用隨意搭配基本沒什么問題,
參考
- https://www.python.org/dev/peps/pep-3333
- http://ruslanspivak.com/lsbaws-part2
- https://www.toptal.com/python/pythons-wsgi-server-application-interface
- https://gist.github.com/thomasballinger/5807241
原文鏈接:https://www.kevinbai.com/articles/27.html
關注「小小后端」公眾號獲取最新文章推送!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/90823.html
標籤:Python
