這篇文章給大家分享的是有關(guān)一篇文章幫你弄懂什么是WSGI的內(nèi)容。小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧。
成都網(wǎng)絡(luò)公司-成都網(wǎng)站建設(shè)公司創(chuàng)新互聯(lián)十余年經(jīng)驗(yàn)成就非凡,專(zhuān)業(yè)從事成都網(wǎng)站制作、做網(wǎng)站,成都網(wǎng)頁(yè)設(shè)計(jì),成都網(wǎng)頁(yè)制作,軟文發(fā)稿,廣告投放平臺(tái)等。十余年來(lái)已成功提供全面的成都網(wǎng)站建設(shè)方案,打造行業(yè)特色的成都網(wǎng)站建設(shè)案例,建站熱線:18982081108,我們期待您的來(lái)電!
寫(xiě)了幾年的python web,卻還不知道WSGI是什么東西,是不是大有人在。 說(shuō)來(lái)也正常,因?yàn)樽鳛殚_(kāi)發(fā)者很少需要去了解wsgi是什么,也能把網(wǎng)站做出來(lái)。
但是如果你想自己寫(xiě)個(gè)web框架玩玩,就不得不去了解wsgi了。
回顧一下,我們?cè)谟胮ython做web開(kāi)發(fā)的時(shí)候,一般基于某個(gè)web框架來(lái)開(kāi)發(fā),django或者是flask等其它框架。 業(yè)務(wù)開(kāi)發(fā)完成后,就要部署到某臺(tái)服務(wù)器中提供對(duì)外的訪問(wèn)。
這時(shí)候你去網(wǎng)上一搜,他們都會(huì)告訴你需要用 gunicorn或者是uwsgi 來(lái)部署。 那么gunicorn、uwsgi 又是什么玩意。
看這個(gè)圖你就明白了,圖我是從網(wǎng)上找的
這里的uwsgi或者gunicorn扮演的角色就是web服務(wù)器的角色,這里的服務(wù)器是軟件層面的服務(wù)器,用于處理瀏覽器發(fā)過(guò)來(lái)的HTTP請(qǐng)求以及將響應(yīng)結(jié)果返回給前端。而Web框架的主要任務(wù)就是處理業(yè)務(wù)邏輯生成結(jié)果給web服務(wù)器,再由web服務(wù)器返回給瀏覽器。
而web框架和web服務(wù)器之間的通信需要遵循一套規(guī)范,這個(gè)規(guī)范就是WSGI了。
為什么要搞這么一套規(guī)范出來(lái)? 規(guī)范就是為了統(tǒng)一標(biāo)準(zhǔn),方便大家所用
想象一下,我們手機(jī)充電的接口現(xiàn)在都是Type-c的,Type-c 就是一種規(guī)范, 手機(jī)廠商按照這個(gè)規(guī)范去生產(chǎn)手機(jī), 充電器廠商按照Type-c的規(guī)范生產(chǎn)充電器,不同廠商的手機(jī)就可以和不同廠商的充電器搭配使用。 而蘋(píng)果卻自成一套規(guī)范,最后導(dǎo)致Android充電器無(wú)法給蘋(píng)果充電。
](p9-juejin.byteimg.com/tos-cn-i-k3…)
那如何寫(xiě)出一個(gè)符合 WSGI規(guī)范的應(yīng)用(框架)程序和服務(wù)器呢?
如上圖所示,左邊是web服務(wù)器,右邊是web框架,或者說(shuō)應(yīng)用程序。
WSGI規(guī)定應(yīng)用程序必須是一個(gè)可調(diào)用對(duì)象(可調(diào)用對(duì)象可以是函數(shù),也可以是類(lèi),還可以是實(shí)現(xiàn)了 __call__
的實(shí)例對(duì)象),而且必須接受兩個(gè)參數(shù),該對(duì)象的返回值必須是可迭代對(duì)象。
我們可以寫(xiě)個(gè)最簡(jiǎn)單的應(yīng)用程序的例子
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]復(fù)制代碼
application 是一個(gè)函數(shù),肯定是可調(diào)用對(duì)象,然后接收兩個(gè)參數(shù),兩個(gè)參數(shù)分別是:environ和start_response
調(diào)用 start_response 函數(shù)負(fù)責(zé)將響應(yīng)頭、狀態(tài)碼傳遞給服務(wù)器, 響應(yīng)體則由application函數(shù)返回給服務(wù)器, 一個(gè)完整的http response 就由這兩個(gè)函數(shù)提供。
但凡是實(shí)現(xiàn)了wsgi的web框架都會(huì)有這樣一個(gè)可調(diào)用對(duì)象
WSGI 服務(wù)器端做的事情就是每次接收HTTP請(qǐng)求,構(gòu)建environ對(duì)象,然后調(diào)用application對(duì)象,最后將HTTP Response返回給瀏覽器。
下面就是一個(gè)完整的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()復(fù)制代碼
當(dāng)然,如果只是寫(xiě)個(gè)用于開(kāi)發(fā)環(huán)境用的server,用不著這么麻煩自己造輪子,因?yàn)閜ython內(nèi)置模塊中就提供有 wsgi server 的功能。
from wsgiref.simple_server import make_server srv = make_server('localhost', 8080, application) srv.serve_forever()復(fù)制代碼
只要3行代碼就可以提供wsgi服務(wù)器,是不是超級(jí)方便,最后來(lái)訪問(wèn)測(cè)試下瀏覽器發(fā)起一個(gè)請(qǐng)求的效果
感謝各位的閱讀!關(guān)于一篇文章幫你弄懂什么是WSGI就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!
網(wǎng)頁(yè)標(biāo)題:一篇文章幫你弄懂什么是WSGI
分享路徑:http://jinyejixie.com/article2/gcecoc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站收錄、全網(wǎng)營(yíng)銷(xiāo)推廣、手機(jī)網(wǎng)站建設(shè)、品牌網(wǎng)站設(shè)計(jì)、定制開(kāi)發(fā)、網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)