WSGI 简介

WSGI 背景

python Web 开发中,服务端程序可以分为两个部分:

  • 服务器程序
  • 应用程序

服务器程序

负责客户端请求接收,整理

应用程序

负责具体的逻辑处理

为了方便应用程序的开发,我们把常用的功能封装起来,成为各种Web开发框架,例如 Django, Flask, Tornado。


image.png

不同的框架有不同的开发方式,但是无论如何,开发出的应用程序都要和服务器程序配合,才能为用户提供服务。否则就会变为如下:

image.png

这时候,标准化就变得尤为重要。我们可以设立一个标准,只要服务器程序支持这个标准,框架也支持这个标准,那么他们就可以配合使用。一旦标准确定,双方各自实现。这样,服务器可以支持更多支持标准的框架,框架也可以使用更多支持标准的服务器。

Python Web开发中,这个标准就是 The Web Server Gateway Interface, 即 WSGI. 这个标准在PEP 333中描述,后来,为了支持 Python 3.x, 并且修正一些问题,新的版本在PEP 3333中描述。

WSGI规定

应用程序的规定

应用程序需要是一个可调用的对象,以下三个都满足。

  • 函数
  • 一个实例,它的类实现了call方法
服务程序的规定

服务器程序需要调用应用程序

实例

1. 应用程序(函数)+服务程序

  • 应用程序(函数)
#hello.py
def application(env, start_response):
    status = '200 OK'
    headers = [('Content-Type', 'text/html')]
    start_response(status, headers)
    return [b"hello world"]
  • 服务程序
#server.py
from wsgiref.simple_server import make_server
from hello import application
httpd = make_server('', 8080, application)
httpd.serve_forever()

2. 应用程序(类)+服务程序

  • 应用程序(类)
# appclass.py
class Application:
    def __init__(self, env, start_response):
        status = '200 OK'
        headers = [('Content-Type', 'text/html')]
        start_response(status, headers)
        pass

    def __iter__(self):
        yield b"Hello world "
  • 服务程序
#server.py
from wsgiref.simple_server import make_server
from appclass import Application

httpd = make_server('', 8080, Application)
httpd.serve_forever()

3. 应用程序(类实例)+服务程序

  • 应用程序(类实例)
# appclassobj.py
class ApplicationObj:
    def __call__(self, env, start_response):
        status = '200 OK'
        headers = [('Content-Type', 'text/html')]
        start_response(status, headers)

        return [b"hello world"]
  • 服务程序
#server.py
from wsgiref.simple_server import make_server
from appclassobj import ApplicationObj

app = ApplicationObj()
httpd = make_server('', 8080, app)
httpd.serve_forever()

疑问

如果对于代码中的 wsgiref有疑问的话,请参考另一篇 《WSGI servers-wsgiref》

from wsgiref.simple_server import make_server

参考 :

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,156评论 19 139
  • 谈论WEB编程的时候常说天天在写CGI,那么CGI是什么呢?可能很多时候并不会去深究这些基础概念,再比如除了CGI...
    __七把刀__阅读 2,226评论 2 11
  • # Python 资源大全中文版 我想很多程序员应该记得 GitHub 上有一个 Awesome - XXX 系列...
    小迈克阅读 3,067评论 1 3
  • 背景 Web开发中,服务器端的程序分为两个部分,一个是服务器程序,负责接收客户端请求和整理客户端请求,一个是应用程...
    范一婷阅读 511评论 0 1
  • 《三国演义》这样的名著,相信很多人都读过了。今年7月我重新读,感觉读出了一些以前没有关注到的东西。 我本来只关注诸...
    逆水行舟eli阅读 1,304评论 2 2