zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python编程:WSGI服务器的参考实现wsgiref模块

Python服务器模块编程 实现 参考 WSGI
2023-09-14 09:07:14 时间

WSGI的全称是Web Server Gateway Interface,Web服务器网关接口

具体的来说,WSGI是一个规范,定义了Web服务器如何与Python应用程序进行交互

WSGI 相当于是Web服务器和Python应用程序之间的桥梁

Web服务器
WSGI
Python应用程序

使用python内置的模块实现一个服务器

python3下示例

# WSGI服务器的参考实现

# 【应用程序】
# 处理函数
def application(environ, start_response):
    start_response("200 OK", [('Content-Type', 'text/html')])
    body = "<h1>hello world %s<h1>"% (environ["PATH_INFO"][1:] or "web")
    return [ body.encode()]


# 【服务器】
from wsgiref.simple_server import make_server

# 创建一个服务器,是application
server = make_server("localhost", 9999, application)

print("服务启动,按Ctrl+C终止... http://localhost:9999/")

# 开始监听HTTP请求
server.serve_forever()

参考

  1. WSGI接口- 廖雪峰博客
  2. WGSI简易教程