白季飞龙的个人主页

WSGI大杂烩

什么是WSGI

WSGIPython Web Server Gateway Interface,也就是Python的Web服务器网关接口,定义了Python的Web应用与服务端的交互规范,类似于Java中的Servlet规范。

实现了WSGI规范的Python模块主要有wsgiref(Python官方的WSGI参考实现)、werkzeug.serving(Flask用)和twisted.web等。

WSGI之HelloWorld(lambda版)

from wsgiref.simple_server import make_server

make_server('localhost', 8088, lambda _, rsp: [
    [
        rsp("200 OK", []),
        "Hello World"
    ][-1].encode()
]).serve_forever()

其中,传给make_server的第三个参数即WSGI规范

多次访问服务器之后的控制台输出

127.0.0.1 - - [19/Mar/2019 17:29:20] "GET / HTTP/1.1" 200 11
127.0.0.1 - - [19/Mar/2019 17:29:21] "GET / HTTP/1.1" 200 11
127.0.0.1 - - [19/Mar/2019 17:29:22] "GET / HTTP/1.1" 200 11

HelloWorld之Class版

from wsgiref.simple_server import make_server


class App:
    def __call__(self, _, rsp):
        rsp("200 OK", [])
        return ["Hello World".encode()]


make_server('localhost', 8088, App()).serve_forever()

HelloWorld之Function版

from wsgiref.simple_server import make_server


def app(_, rsp):
    rsp("200 OK", [])
    return ["Hello World".encode()]


make_server('localhost', 8088, app).serve_forever()

WSGI容器

WSGI容器,即支持运行WSGI应用的Web容器。常用的有uWSGIgUnicorn

gUnicorn(pip install gunicorn)为例,运行方式:

gunicorn foo:app 启动foo.py文件中名字为app的WSGI应用

示例示例输出

[2019-03-19 22:19:31 +0800] [59137] [INFO] Starting gunicorn 19.9.0
[2019-03-19 22:19:31 +0800] [59137] [INFO] Listening at: http://127.0.0.1:8000 (59137)
[2019-03-19 22:19:31 +0800] [59137] [INFO] Using worker: sync
[2019-03-19 22:19:31 +0800] [59140] [INFO] Booting worker with pid: 59140

文章首发: https://baijifeilong.github.io


漫漫路,莫论逍遥;潜心修,只为悟道