WSGI 简介

WSGI 背景

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

  • 服务器程序
  • 应用程序

服务器程序

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

应用程序

负责具体的逻辑处理

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


WSGI 简介_第1张图片
image.png

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

WSGI 简介_第2张图片
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()
  • 命令行执行:python server.py
  • 浏览器输入:http://localhost:8080/ 画面显示 hello world

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

参考 :

  • https://docs.python.org/2/library/wsgiref.html
  • http://blog.csdn.net/yangz_xx/article/details/37508909
  • https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001432012393132788f71e0edad4676a3f76ac7776f3a16000

你可能感兴趣的:(WSGI 简介)