如何理解wsgi - 知乎

寫了幾年的python web,卻還不知道WSGI是什麼東西,是否是大有人在。 說來也正常,由於做爲開發者不多須要去了解wsgi是什麼,也能把網站作出來。前端

可是若是你想本身寫個web框架玩玩,就不得不去了解wsgi了。python

回顧一下,咱們在用python作web開發的時候,通常基於某個web框架來開發,django或者是flask等其它框架。 業務開發完成後,就要部署到某臺服務器中提供對外的訪問。web

這時候你去網上一搜,他們都會告訴你須要用 gunicorn或者是uwsgi 來部署。 那麼gunicorn、uwsgi 又是什麼玩意。django

看這個圖你就明白了flask


這裏的uwsgi或者gunicorn扮演的角色就是web服務器的角色,這裏的服務器是軟件層面的服務器,用於處理瀏覽器發過來的HTTP請求以及將響應結果返回給前端。而Web框架的主要任務就是處理業務邏輯生成結果給web服務器,再由web服務器返回給瀏覽器。瀏覽器

而web框架和web服務器之間的通訊須要遵循一套規範,這個規範就是WSGI了。服務器

爲何要搞這麼一套規範出來? 規範就是爲了統一標準,方便你們所用app

想象一下,咱們手機充電的接口如今都是Type-c的,Type-c 就是一種規範, 手機廠商按照這個規範去生產手機, 充電器廠商按照Type-c的規範生產充電器,不一樣廠商的手機就能夠和不一樣廠商的充電器搭配使用。 而蘋果卻自成一套規範,最後致使Android充電器沒法給蘋果充電。框架

那如何寫出一個符合 WSGI規範的應用(框架)程序和服務器呢?curl



如上圖所示,左邊是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

  • environ是一個字典,裏面儲存了HTTP request相關的全部內容,好比header、請求參數等等
  • start_response是一個WSGI 服務器傳遞過來的函數,用於將response header,狀態碼傳遞給Server。

調用 start_response 函數負責將響應頭、狀態碼傳遞給服務器, 響應體則由application函數返回給服務器, 一個完整的http response 就由這兩個函數提供。

但凡是實現了wsgi的web框架都會有這樣一個可調用對象

服務器

WSGI 服務器端作的事情就是每次接收HTTP請求,構建environ對象,而後調用application對象,最後將HTTP Response返回給瀏覽器。

下面就是一個完整的wsgi server 的代碼

import socket
import sys
from io import StringIO


class 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', 8080


def make_server(server_address, application):
    server = WSGIServer(server_address)
    server.set_app(application)
    return server


if __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

相關文章
相關標籤/搜索