python WSGI

wsgi
是python 一个内置的web 服务器(其实就是帮助建立socket 连接,完成一些底层的操作)
wsgi全称是"Web Server Gateway Interfacfe",web服务器网关接口,wsgi在python2.5中加入,是web服务器和web应用的标准接口,任何实现了该接口的web服务器和web应用都能无缝协作。

浏览器 <-- Server <---WSGI--> App

python 文件

from wsgiref.simple_server import  make_server
import  time
#定义一个函数,environ 存储客户端的请求的内容 , start_response 设置响应内容
def application(environ,start_response):
    #print(environ)
    #获取请求的URL , 可以通过这个URL 进行判断,返回不同的信息
    path=environ["PATH_INFO"]

    #设置响应头
    start_response('200 OK',[('Content-type','text/html')])


    #如果路径是/getTime, 则获取当前时间
    if path == '/getTime':

        f = open("getTime.html","rb")
        data = f.read()
        #获取当前时间
        cTime = time.ctime(time.time())

        print("ctime:",cTime)
        #将当前时间设置到HTML 中 , 将HTML 中的${cTime} 替换成 当前时间
        data= str(data,"utf8").replace("${cTime}",str(cTime))
        return [data.encode("utf8")]

    #设置响应体
    return [b'<h1>hello WSGI</h1>']


httpd = make_server('',8002,application)

print('serving HTTP on 8002')

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

getTime.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>current time is : ${cTime}</h1>
</body>
</html>
原文地址:https://www.cnblogs.com/gaizhongfeng/p/8471523.html