WSGI

作者: Alex_Dj | 来源:发表于2018-02-09 20:51 被阅读0次

简介

Web服务器网关接口(WSGI)是用于Python编程语言的Web服务器(Web Server)Web应用程序或框架(Web application or frameworks)之间的简单通用接口的规范。

WSGI有两端:一端是“服务器(server)”或“网关(gateway)”(通常是诸如Apache或Nginx的Web服务器);另一端是“应用程序”或“框架”。为了处理WSGI请求,服务器端执行应用程序,并向应用程序端提供环境信息和回调函数。应用程序处理请求,并使用它提供的回调函数将响应返回给服务器端。

在服务器和应用程序之间可能会有一个WSGI中间件,它实现了两端的API。服务器收到来自客户端的请求,并将其转发给中间件。处理完成后,它向应用程序发送一个请求。应用程序的响应由中间件转发到服务器,最终转发给客户端。可能有多个中间件形成一个WSGI兼容应用程序的堆栈。

“中间件”组件可以实现如下功能:

  • 根据环境变量,将目标URL的请求路由到不同的应用程序对象。
  • 允许多个应用程序或框架在同一个进程中并行运行
  • 负载均衡和远程处理,通过网络转发请求和响应
  • 执行后处理,例如应用XSLT样式表

Python WSGI接口

我们来看下整体的结构图:


WSGI结构图
应用端接口

再Python 3.5中,应用程序端的接口如下所示:

def application(environ, start_response):
    body = b'Hello world!\n'
    status = '200 OK'
    headers = [('Content-type', 'text/plain')]
    start_response(status, headers)
    return [body]

这里的应用程序对象的规范是:

  • 必须是包含environ和start_response参数的可调用对象---environ包含了所有的请求信息,start_response是application处理完后需要调用的函数,参数是状态码、响应头部还有错误信息
  • 在发送body之前必须调用start_response回调函数
  • 必须返回一个包含body的迭代器
服务器端接口

WSGI服务器与这个应用程序的接口如下:

def write(chunk):
    '''Write data back to client'''
    ...

def send_status(status):
   '''Send HTTP status code'''
   ...

def send_headers(headers):
    '''Send HTTP headers'''
    ...

def start_response(status, headers):
    '''WSGI start_response callable'''
    send_status(status)
    send_headers(headers)
    return write

# Make request to application
response = application(environ, start_response)
try:
    for chunk in response:
        write(chunk)
finally:
    if hasattr(response, 'close'):
        response.close()
参考
  1. Web Server Gateway Interface
  2. WSGI: The Server-Application Interface for Python
  3. flask 源码解析:应用启动流程

相关文章

  • python wsgi+Odoo 的启动

    参考:WSGI初探Odoo web 机制浅析python的 WSGI 简介python wsgi 简介 wsgi的...

  • wsgi&uwsgi

    WSGI协议 WSGI, aka Web Server Gateway Interface, WSGI 不是服务器...

  • wsgi简介

    wsgi是什么? WSGI:Web Server Gateway Interface。WSGI接口定义非常简单,它...

  • WSGI简介

    结合案例Python部署 & 示例代码wsgi-demo All in One WSGI WSGI = Pytho...

  • gunicorn使用

    WSGI 了解gunicorn之前先了解WSGI WSGI是Python Web Server Gateway I...

  • flask的deamon简单分析

    代码样例 分析所谓的wsgi应用,wsgi应用一定要有call函数。这样最后才能被wsgi调用,并将wsgi应用处...

  • 关于网络的记录

    WSGI等 WSGI是一种通信协议。WSGI将Web组件分成了三类:Web 服务器(WSGI Server)、We...

  • flask源码分析

    wsgi协议 关于wsgi协议就不赘述了,以下是最简单的符合wsgi的应用 app attriabute app....

  • Flask流程

    回顾一下Flask的流程: WSGI Server 到 WSGI App 图中可以看到HTTP请求都是通过WSGI...

  • WSGI

    settings.py中 WSGI_APPLICATION = 'WebCsdn.wsgi.application...

网友评论

      本文标题:WSGI

      本文链接:https://www.haomeiwen.com/subject/fugxtftx.html