欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python Web开发中的WSGI协议简介

程序员文章站 2023-10-31 22:32:46
在Python Web开发中,我们一般使用Flask、Django等web框架来开发应用程序,生产环境中将应用部署到Apache、Nginx等web服务器时,还需要uWSGI或者Gunicorn。一个完整的部署应该类似这样: 要弄清这些概念之间的关系,就需要先理解WSGI协议。 WSGI是什么 WS ......

 在python web开发中,我们一般使用flask、django等web框架来开发应用程序,生产环境中将应用部署到apache、nginx等web服务器时,还需要uwsgi或者gunicorn。一个完整的部署应该类似这样:

web server(nginx、apache) <-----> wsgi server(uwsgi、gunicorn) <-----> app(flask、django)

要弄清这些概念之间的关系,就需要先理解wsgi协议。

wsgi是什么

wsgi的全称是python web server gateway interface,wsgi不是web服务器,python模块,或者web框架以及其它任何软件,它只是一种规范,描述了web server如何与web application进行通信的规范。pep-3333有关于wsgi的具体定义。

为什么需要wsgi

我们使用web框架进行web应用程序开发时,只专注于业务的实现,http协议层面相关的事情交于web服务器来处理,那么,web服务器和应用程序之间就要知道如何进行交互。有很多不同的规范来定义这些交互,最早的一个是cgi,后来出现了改进cgi性能的fasgcgi。java有专用的servlet规范,实现了servlet api的java web框架开发的应用可以在任何实现了servlet api的web服务器上运行。wsgi的实现受servlet的启发比较大。

wsgi的实现

在wsgi中有两种角色:一方称之为server或者gateway, 另一方称之为application或者framework。application可以提供一个可调用对象供server调用。server先收到用户的请求,然后调用application提供的可调用对象,调用的结果会被封装成http响应后发送给客户端。

the application/framework side

wsgi对application的要求有3个:

   - 实现一个可调用对象

   - 可调用对象接收两个参数,environ(一个dict,包含wsgi的环境信息)与start_response(一个响应请求的函数)

   - 返回一个iterable可迭代对象

可调用对象可以是一个函数、类或者实现了__call__方法的类实例。
environ和start_response由server方提供。
environ是包含了环境信息的字典。
start_response也是一个callable,接受两个必须的参数,status(http状态)和response_headers(响应消息的头),可调用对象返回前调用start_response。

下面是pep-3333实现简application的代码:

hello_world = b"hello world!\n"

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]

class appclass:

    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

代码分别用函数与类对application的可调用对象进行了实现。类实现中定义了__iter__方法,返回的类实例就变为了iterable可迭代对象。

我们也可以用定义了__call__方法的类实例做一下实现:

class appclass:

    def __call__(self, environ, start_response):
        status = '200 ok'
        response_headers = [('content-type', 'text/plain')]
        start_response(status, response_headers)
        return [hello_world]

the server/gateway side

server要做的是每次收到http请求时,调用application可调用对象,pep文档代码:

import os, sys

enc, esc = sys.getfilesystemencoding(), 'surrogateescape'

def unicode_to_wsgi(u):
    # convert an environment variable to a wsgi "bytes-as-unicode" string
    return u.encode(enc, esc).decode('iso-8859-1')

def wsgi_to_bytes(s):
    return s.encode('iso-8859-1')

def run_with_cgi(application):
    environ = {k: unicode_to_wsgi(v) for k,v in os.environ.items()}
    environ['wsgi.input']        = sys.stdin
    environ['wsgi.errors']       = sys.stderr
    environ['wsgi.version']      = (1, 0)
    environ['wsgi.multithread']  = false
    environ['wsgi.multiprocess'] = true
    environ['wsgi.run_once']     = true

    if environ.get('https', 'off') in ('on', '1'):
        environ['wsgi.url_scheme'] = 'https'
    else:
        environ['wsgi.url_scheme'] = 'http'

    headers_set = []
    headers_sent = []

    def write(data):
        out = sys.stdout

        if not headers_set:
             raise assertionerror("write() before start_response()")

        elif not headers_sent:
             # before the first output, send the stored headers
             status, response_headers = headers_sent[:] = headers_set
             out.write(wsgi_to_bytes('status: %s\r\n' % status))
             for header in response_headers:
                 out.write(wsgi_to_bytes('%s: %s\r\n' % header))
             out.write(wsgi_to_bytes('\r\n'))

        out.write(data)
        out.flush()

    def start_response(status, response_headers, exc_info=none):
        if exc_info:
            try:
                if headers_sent:
                    # re-raise original exception if headers sent
                    raise exc_info[1].with_traceback(exc_info[2])
            finally:
                exc_info = none     # avoid dangling circular ref
        elif headers_set:
            raise assertionerror("headers already set!")

        headers_set[:] = [status, response_headers]

        # note: error checking on the headers should happen here,
        # *after* the headers are set.  that way, if an error
        # occurs, start_response can only be re-called with
        # exc_info set.

        return write

    result = application(environ, start_response)
    try:
        for data in result:
            if data:    # don't send headers until body appears
                write(data)
        if not headers_sent:
            write('')   # send headers now if body was empty
    finally:
        if hasattr(result, 'close'):
            result.close()

代码中server组装了environ,定义了start_response函数,将两个参数提供给application并且调用,最后输出http响应的status、header和body:

if __name__ == '__main__':
    run_with_cgi(simple_app)

输出:

status: 200 ok
content-type: text/plain

hello world!

environ

environ字典包含了一些cgi规范要求的数据,以及wsgi规范新增的数据,还可能包含一些操作系统的环境变量以及web服务器相关的环境变量,具体见。

首先是cgi规范中要求的变量:
  - request_method: http请求方法,'get', 'post'等,不能为空
  - script_name: http请求path中的初始部分,用来确定对应哪一个application,当application对应于服务器的根,可以为空
  - path_info: path中剩余的部分,application要处理的部分,可以为空
  - query_string: http请求中的查询字符串,url中?后面的内容
  - content_type: http headers中的content-type内容
  - content_length: http headers中的content-length内容
  - server_nameserver_port: 服务器域名和端口,这两个值和前面的script_name, path_info拼起来可以得到完整的url路径
  - server_protocol: http协议版本,'http/1.0'或'http/1.1'
  - http_variables: 和http请求中的headers对应,比如'user-agent'写成'http_user_agent'的格式

wsgi规范中还要求environ包含下列成员:
  - wsgi.version:一个元组(1, 0),表示wsgi版本1.0
  - wsgi.url_scheme:http或者https
  - wsgi.input:一个类文件的输入流,application可以通过这个获取http请求的body
  - wsgi.errors:一个输出流,当应用程序出错时,可以将错误信息写入这里
  - wsgi.multithread:当application对象可能被多个线程同时调用时,这个值需要为true
  - wsgi.multiprocess:当application对象可能被多个进程同时调用时,这个值需要为true
  - wsgi.run_once:当server期望application对象在进程的生命周期内只被调用一次时,该值为true

我们可以使用python官方库wsgiref实现的server看一下environ的具体内容:

def demo_app(environ, start_response):
    from stringio import stringio
    stdout = stringio()
    print >>stdout, "hello world!"
    print >>stdout
    h = environ.items()
    h.sort()
    for k,v in h:
        print >>stdout, k,'=', repr(v)
    start_response("200 ok", [('content-type','text/plain')])
    return [stdout.getvalue()]

if __name__ == '__main__':
    from wsgiref.simple_server import make_server
    httpd = make_server('', 8000, demo_app)
    sa = httpd.socket.getsockname()
    print "serving http on", sa[0], "port", sa[1], "..."
    import webbrowser
    webbrowser.open('http://localhost:8000/xyz?abc')
    httpd.handle_request()  # serve one request, then exit
    httpd.server_close()

打开的网页会输出environ的具体内容。

使用environ组装请求url地址:

from urllib.parse import quote
url = environ['wsgi.url_scheme']+'://'

if environ.get('http_host'):
    url += environ['http_host']
else:
    url += environ['server_name']

    if environ['wsgi.url_scheme'] == 'https':
        if environ['server_port'] != '443':
           url += ':' + environ['server_port']
    else:
        if environ['server_port'] != '80':
           url += ':' + environ['server_port']

url += quote(environ.get('script_name', ''))
url += quote(environ.get('path_info', ''))
if environ.get('query_string'):
    url += '?' + environ['query_string']

start_resposne

start_response是一个可调用对象,接收两个必选参数和一个可选参数:

  - status: 一个字符串,表示http响应状态字符串,比如'200 ok'、'404 not found'
  - headers: 一个列表,包含有如下形式的元组:(header_name, header_value),用来表示http响应的headers
  - exc_info(可选): 用于出错时,server需要返回给浏览器的信息

start_response必须返回一个。
我们知道http的响应需要包含status,headers和body,所以在application对象将body作为返回值return之前,需要先调用start_response,将status和headers的内容返回给server,这同时也是告诉server,application对象要开始返回body了。

关系

由此可见,server负责接收http请求,根据请求数据组装environ,定义start_response函数,将这两个参数提供给application。application根据environ信息执行业务逻辑,将结果返回给server。响应中的status、headers由start_response函数返回给server,响应的body部分被包装成iterable作为application的返回值,server将这些信息组装为http响应返回给请求方。

在一个完整的部署中,uwsgi和gunicorn是实现了wsgi的server,django、flask是实现了wsgi的application。两者结合起来其实就能实现访问功能。实际部署中还需要nginx、apache的原因是它有很多uwsgi没有支持的更好功能,比如处理静态资源,负载均衡等。nginx、apache一般都不会内置wsgi的支持,而是通过扩展来完成。比如apache服务器,会通过扩展模块mod_wsgi来支持wsgi。apache和mod_wsgi之间通过程序内部接口传递信息,mod_wsgi会实现wsgi的server端、进程管理以及对application的调用。nginx上一般是用proxy的方式,用nginx的协议将请求封装好,发送给应用服务器,比如uwsgi,uwsgi会实现wsgi的服务端、进程管理以及对application的调用。

uwsgi与gunicorn的比较,由可知: 

在响应时间较短的应用中,uwsgi+django是个不错的组合(测试的结果来看有稍微那么一点优势),但是如果有部分阻塞请求 gunicorn+gevent+django有非常好的效率, 如果阻塞请求比较多的话,还是用tornado重写吧。

middleware

wsgi除了server和application两个角色外,还有middleware中间件,middleware运行在server和application中间,同时具备server和application的角色,对于server来说,它是一个application,对于application来说,它是一个server:

from piglatin import piglatin

class latiniter:

    def __init__(self, result, transform_ok):
        if hasattr(result, 'close'):
            self.close = result.close
        self._next = iter(result).__next__
        self.transform_ok = transform_ok

    def __iter__(self):
        return self

    def __next__(self):
        if self.transform_ok:
            return piglatin(self._next())   # call must be byte-safe on py3
        else:
            return self._next()

class latinator:

    # by default, don't transform output
    transform = false

    def __init__(self, application):
        self.application = application

    def __call__(self, environ, start_response):

        transform_ok = []

        def start_latin(status, response_headers, exc_info=none):

            # reset ok flag, in case this is a repeat call
            del transform_ok[:]

            for name, value in response_headers:
                if name.lower() == 'content-type' and value == 'text/plain':
                    transform_ok.append(true)
                    # strip content-length if present, else it'll be wrong
                    response_headers = [(name, value)
                        for name, value in response_headers
                            if name.lower() != 'content-length'
                    ]
                    break

            write = start_response(status, response_headers, exc_info)

            if transform_ok:
                def write_latin(data):
                    write(piglatin(data))   # call must be byte-safe on py3
                return write_latin
            else:
                return write

        return latiniter(self.application(environ, start_latin), transform_ok)


from foo_app import foo_app
run_with_cgi(latinator(foo_app))

可以看出,latinator调用foo_app充当server角色,然后实例被run_with_cgi调用充当application角色。

uwsgi、uwsgi与wsgi的区别

  - uwsgi:与wsgi一样是一种通信协议,是uwsgi服务器的独占协议,据说该协议是fastcgi协议的10倍快。

  - uwsgi:是一个web server,实现了wsgi协议、uwsgi协议、http协议等。

django中wsgi的实现

每个django项目中都有个wsgi.py文件,作为application是这样实现的:

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

源码:

from django.core.handlers.wsgi import wsgihandler

def get_wsgi_application():

    django.setup(set_prefix=false)
    return wsgihandler()

wsgihandler:

class wsgihandler(base.basehandler):
    request_class = wsgirequest

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.load_middleware()

    def __call__(self, environ, start_response):
        set_script_prefix(get_script_name(environ))
        signals.request_started.send(sender=self.__class__, environ=environ)
        request = self.request_class(environ)
        response = self.get_response(request)

        response._handler_class = self.__class__

        status = '%d %s' % (response.status_code, response.reason_phrase)
        response_headers = [
            *response.items(),
            *(('set-cookie', c.output(header='')) for c in response.cookies.values()),
        ]
        start_response(status, response_headers)
        if getattr(response, 'file_to_stream', none) is not none and environ.get('wsgi.file_wrapper'):
            response = environ['wsgi.file_wrapper'](response.file_to_stream)
        return response

application是一个定义了__call__方法的wsgihandler类实例,首先加载中间件,然后根据environ生成请求request,根据请求生成响应response,status和response_headers由start_response处理,然后返回响应body。

django也自带了wsgi server,当然性能不够好,一般用于测试用途,运行runserver命令时,django可以起一个本地wsgi server,文件:

def run(addr, port, wsgi_handler, ipv6=false, threading=false, server_cls=wsgiserver):
    server_address = (addr, port)
    if threading:
        httpd_cls = type('wsgiserver', (socketserver.threadingmixin, server_cls), {})
    else:
        httpd_cls = server_cls
    httpd = httpd_cls(server_address, wsgirequesthandler, ipv6=ipv6)
    if threading:
        httpd.daemon_threads = true
    httpd.set_app(wsgi_handler)
    httpd.serve_forever() 

实现的wsgiserver,继承自wsgiref:

class wsgiserver(simple_server.wsgiserver):
    """basehttpserver that implements the python wsgi protocol"""

    request_queue_size = 10

    def __init__(self, *args, ipv6=false, allow_reuse_address=true, **kwargs):
        if ipv6:
            self.address_family = socket.af_inet6
        self.allow_reuse_address = allow_reuse_address
        super().__init__(*args, **kwargs)

    def handle_error(self, request, client_address):
        if is_broken_pipe_error():
            logger.info("- broken pipe from %s\n", client_address)
        else:
            super().handle_error(request, client_address)

参考链接

  - 

  - wsgi简介

  - python web开发最难懂的wsgi协议,到底包含哪些内容