关于python:Python-中的-WSGI-接口和-WSGI-服务

8次阅读

共计 1160 个字符,预计需要花费 3 分钟才能阅读完成。

HTTP 格局

HTTP GET 申请的格局:

GET /path HTTP/1.1
Header1: Value1
Header2: Value2
Header3: Value3

每个 Header 一行一个,换行符是\r\n

HTTP POST 申请的格局:

POST /path HTTP/1.1
Header1: Value1
Header2: Value2
Header3: Value3

body data goes here...

当遇到间断两个 \r\n 时,Header 局部完结,前面的数据全副是 Body。

HTTP 响应的格局:

200 OK
Header1: Value1
Header2: Value2
Header3: Value3

body data goes here...

HTTP 响应如果蕴含 body,也是通过 \r\n\r\n 来分隔的。需注意,Body 的数据类型由 Content-Type 头来确定,如果是网页,Body 就是文本,如果是图片,Body 就是图片的二进制数据。

当存在 Content-Encoding 时,Body 数据是被压缩的,最常见的压缩形式是 gzip。

WSGI 接口

WSGI:Web Server Gateway Interface。

WSGI 接口定义非常简单,只须要实现一个函数,就能够响应 HTTP 申请。

# hello.py

def application(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/html')])
    body = '<h1>Hello, %s!</h1>' % (environ['PATH_INFO'][1:] or 'web')
    return [body.encode('utf-8')]

函数接管两个参数:

  • environ:一个蕴含所有 HTTP 申请信息的 dict 对象;
  • start_response:一个发送 HTTP 响应的函数。

运行 WSGI 服务

Python 内置了一个 WSGI 服务器,这个模块叫 wsgiref,它是用纯 Python 编写的 WSGI 服务器的参考实现。

# server.py

from wsgiref.simple_server import make_server
from hello import application

# 创立一个服务器,IP 地址为空,端口是 8000,处理函数是 application:
httpd = make_server('', 8000, application)
print('Serving HTTP on port 8000...')
# 开始监听 HTTP 申请:
httpd.serve_forever()

在命令行输出 python server.py 即可启动 WSGI 服务器。

启动胜利后,关上浏览器,输出http://localhost:8000/,即可看到后果。

Ctrl+C 能够终止服务器。

正文完
 0