寫了幾年的python web,卻還不知道WSGI是什麼東西,是不是大有人在。說來也正常,因為身為開發者很少需要去了解wsgi是什麼,也能把網站做出來。
但如果你想自己寫個web框架玩玩,就得去了解wsgi了。
回顧一下,我們在用python做web開發的時候,一般基於某個web框架來開發,django或者是flask等其它框架。業務開發完成後,就要部署到某台伺服器中提供對外的存取。
這時候你去網路上一搜,他們都會告訴你需要用 gunicorn或是uwsgi 來部署。那麼gunicorn、uwsgi 又是什麼玩意。
看這張圖就明白了,圖我是從網路找的
#這裡的uwsgi或是gunicorn扮演的角色就是web伺服器的角色,這裡的伺服器是軟體層面的伺服器,用於處理瀏覽器發送過來的HTTP請求以及將回應結果傳回給前端。而Web框架的主要任務就是處理業務邏輯產生結果給web伺服器,再由web伺服器回傳給瀏覽器。
而web框架和web伺服器之間的通訊需要遵循一套規範,這個規範就是WSGI了。
為什麼要搞這麼一套規範出來?規範就是為了統一標準,方便大家所用
想像一下,我們手機充電的介面現在都是Type-c的,Type-c 就是一種規範, 手機廠商依照這個規範去生產手機, 充電器廠商依照Type-c的規格生產充電器,不同廠商的手機就可以和不同廠商的充電器搭配使用。而蘋果卻自成一套規範,最後導致Android充電器無法為蘋果充電。
](p9-juejin.byteimg.com/tos-cn-i-k3…)
那如何寫出一個符合WSGI規範的應用(框架)程序和伺服器呢?
如上圖所示,左邊是web伺服器,右邊是web框架,或者說應用程式。
WSGI規定應用程式必須是可呼叫物件(可呼叫物件可以是函數,也可以是類,也可以是實作了__call__
的實例物件),而且必須接受兩個參數,該物件的回傳值必須是可迭代物件。
我們可以寫個最簡單的應用程式的例子
HELLO_WORLD = b"Hello world!\n"def application(environ, start_response): status = '200 OK' response_headers = [('Content-type', 'text/plain')] start_response(status, response_headers) return [HELLO_WORLD]复制代码
application 是一個函數,肯定是可呼叫對象,然後接收兩個參數,兩個參數分別是:environ和start_response
呼叫 start_response 函數負責將回應頭、狀態碼傳遞給伺服器, 回應體則由application函數傳回給伺服器, 一個完整的http response 就由這兩個函式提供。
但凡是實作了wsgi的web框架都會有這樣一個可呼叫物件
WSGI 伺服器端所做的事情就是每次接收HTTP請求,建構environ對象,然後呼叫application對象,最後將HTTP Response回傳給瀏覽器。
下面就是一個完整的wsgi server 的程式碼
import socketimport sysfrom io import StringIOclass WSGIServer(object): address_family = socket.AF_INET socket_type = socket.SOCK_STREAM request_queue_size = 1 def __init__(self, server_address): # Create a listening socket self.listen_socket = listen_socket = socket.socket( self.address_family, self.socket_type ) # Allow to reuse the same address listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Bind listen_socket.bind(server_address) # Activate listen_socket.listen(self.request_queue_size) # Get server host name and port host, port = self.listen_socket.getsockname()[:2] self.server_name = socket.getfqdn(host) self.server_port = port # Return headers set by Web framework/Web application self.headers_set = [] def set_app(self, application): self.application = application def serve_forever(self): listen_socket = self.listen_socket while True: # New client connection self.client_connection, client_address = listen_socket.accept() # Handle one request and close the client connection. Then # loop over to wait for another client connection self.handle_one_request() def handle_one_request(self): self.request_data = request_data = self.client_connection.recv(1024) # Print formatted request data a la 'curl -v' print(''.join( '< {line}\n'.format(line=line) for line in request_data.splitlines() )) self.parse_request(request_data) # Construct environment dictionary using request data env = self.get_environ() # It's time to call our application callable and get # back a result that will become HTTP response body result = self.application(env, self.start_response) # Construct a response and send it back to the client self.finish_response(result) def parse_request(self, text): request_line = text.splitlines()[0] request_line = request_line.rstrip('\r\n') # Break down the request line into components (self.request_method, # GET self.path, # /hello self.request_version # HTTP/1.1 ) = request_line.split() def get_environ(self): env = {} # The following code snippet does not follow PEP8 conventions # but it's formatted the way it is for demonstration purposes # to emphasize the required variables and their values # # Required WSGI variables env['wsgi.version'] = (1, 0) env['wsgi.url_scheme'] = 'http' env['wsgi.input'] = StringIO.StringIO(self.request_data) env['wsgi.errors'] = sys.stderr env['wsgi.multithread'] = False env['wsgi.multiprocess'] = False env['wsgi.run_once'] = False # Required CGI variables env['REQUEST_METHOD'] = self.request_method # GET env['PATH_INFO'] = self.path # /hello env['SERVER_NAME'] = self.server_name # localhost env['SERVER_PORT'] = str(self.server_port) # 8888 return env def start_response(self, status, response_headers, exc_info=None): # Add necessary server headers server_headers = [ ('Date', 'Tue, 31 Mar 2015 12:54:48 GMT'), ('Server', 'WSGIServer 0.2'), ] self.headers_set = [status, response_headers + server_headers] # To adhere to WSGI specification the start_response must return # a 'write' callable. We simplicity's sake we'll ignore that detail # for now. # return self.finish_response def finish_response(self, result): try: status, response_headers = self.headers_set response = 'HTTP/1.1 {status}\r\n'.format(status=status) for header in response_headers: response += '{0}: {1}\r\n'.format(*header) response += '\r\n' for data in result: response += data # Print formatted response data a la 'curl -v' print(''.join( '> {line}\n'.format(line=line) for line in response.splitlines() )) self.client_connection.sendall(response) finally: self.client_connection.close() SERVER_ADDRESS = (HOST, PORT) = 'localhost', 8080def make_server(server_address, application): server = WSGIServer(server_address) server.set_app(application) return serverif __name__ == '__main__': httpd = make_server(SERVER_ADDRESS, application) print('WSGIServer: Serving HTTP on port {port} ...\n'.format(port=PORT)) httpd.serve_forever()复制代码
當然,如果只是寫個用來開發環境用的server,用不著這麼麻煩自己造輪子,因為python內建模組就提供有wsgi server 的功能。
from wsgiref.simple_server import make_server srv = make_server('localhost', 8080, application) srv.serve_forever()复制代码
只要3行程式碼就可以提供wsgi伺服器,是不是超級方便,最後來訪問測試下瀏覽器發起一個請求的效果
以上就是wsgi簡介,深入了解wsgi可以熟悉下PEP333
相關免費學習推薦:python影片教學
以上是一定要懂WSGI是什麼的詳細內容。更多資訊請關注PHP中文網其他相關文章!