Gateway - the Protocol between Applications and Web Servers

WSGI

What is WSGI?

WSGI is the Web Server Gateway Interface. It is a specification that describes how a web server communicates with web applications, and how web applications can be chained together to process one request.

WSGI is a Python standard described in detail in PEP 3333.

定义来看,WSGI做了两件事情:

  • 定义 web服务器 <-> web应用 之间的交流规则

  • 处理请求时,web应用 <-> web应用 之间如何串联

另外,WSGI是针对Python定义的,下面就来部署一个简单的Python "Hello World" web应用。

Deploy a WSGI Application

这是一个简单的,遵循WSGI协议的Python应用(https://werkzeug.palletsprojects.com/en/2.3.x/tutorial/#step-0-a-basic-wsgi-introduction)

def application(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/plain')])
    return ['Hello World!'.encode('utf-8')]

gunicorn

Gunicorn 'Green Unicorn' is a Python WSGI HTTP Server for UNIX.

gunicorn原生支持WSGI协议,所以用它来部署python应用很方便,不需要额外的配置。

[root@uco-pdc-mgmt01 tmp]# gunicorn wsgi:app --pythonpath /root
[2020-05-17 16:51:10 +0800] [28843] [INFO] Starting gunicorn 19.9.0
[2020-05-17 16:51:10 +0800] [28843] [INFO] Listening at: http://127.0.0.1:8000 (28843)
[2020-05-17 16:51:10 +0800] [28843] [INFO] Using worker: sync
[2020-05-17 16:51:10 +0800] [28846] [INFO] Booting worker with pid: 28846
[bwu@uco-pdc-mgmt01 ~]$curl localhost:8000
Hello World!

httpd

httpd原生不支持WSGI,所以需要安装mod_wsgi模块,相比gunicorn还要进行一些额外配置

https://flask.palletsprojects.com/en/1.1.x/deploying/mod_wsgi/

CGI

CGI是个比较古老的技术,也是用来定义应用和web服务器之间如何交互,但是它并不限定于某种语言,相比WSGI更加通用。"C"就是Common的意思。

下面还是用httpd来部署一个CGI应用

Deploy a CGI Application

小结

这些"X"GI本质上是一个协议,约定了双方交流的一个规则。不支持这些协议的应用,可以通过添加额外的模块/插件(e.g. httpd的mod_cgi),从而支持这个协议。有的应用从设计之初就支持,比如gunicorn原生支持WSGI,应用程序代码会按照这个协议规则来写,也算原生支持,不过为了开发方便,关于协议实现部分,都被包装在框架里,代码只要专注于业务逻辑实现就行了。

最后更新于