美文网首页
WSGI 简介

WSGI 简介

作者: 可爱喵星人 | 来源:发表于2018-03-08 09:04 被阅读0次

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

参考 :

相关文章

  • python wsgi+Odoo 的启动

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

  • WSGI 简介

    WSGI 背景 python Web 开发中,服务端程序可以分为两个部分: 服务器程序 应用程序 服务器程序 负责...

  • WSGI简介

    背景 Web开发中,服务器端的程序分为两个部分,一个是服务器程序,负责接收客户端请求和整理客户端请求,一个是应用程...

  • WSGI简介

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

  • wsgi简介

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

  • WSGI--python web服务器接口

    WSGI简介 WSGI:Web Server Gateway Interface是python web服务器网关接...

  • OpenStack Restful API基础简介

    Restful API开发框架简介 WSGI + Paste + Paste_Deploy + Routes + ...

  • WSGI服务器简介

    HTTP协议 http协议是:是基于TCP/IP协议超文本传输协议,它是一个短连接。超文本是指由HTML标签语言编...

  • 深入理解nova api服务

    一、wsgi简介 在构建 Web 应用时,通常会有 Web Server 和 Application Server...

  • wsgi&uwsgi

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

网友评论

      本文标题:WSGI 简介

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