Wsgi的web框架实例

建立server服务端:

from wsgiref.simple_server import make_server
import  time
def f1(request):
    return [b'<h1>hello,Abook!</h1>']
def f2(request):
    return [b'<h1>hello,Aweb!</h1>']

def cunrrent_time(request):
    cur_time = time.ctime(time.time())
    f=open('cunrrent_time.html','rb')
    data=f.read()
    data=str(data,'utf8').replace("!cur_time!",str(cur_time))
    return [data.encode('utf8')]
    #return  [data]
def routers():  #封装一个元组可以根据点击的URL路径比配到相对应的函数
    urlpatterns=(
    ('/book',f1),
    ('/web',f2),
    ('/time', cunrrent_time),
    )
    return  urlpatterns



def applicattion(environ,start_response):
      #通过environ封装程一个所有请求信息的对象
      #start_response可以很方便的设置响应头
       #print("envire",environ)
       #print("environ",environ['PATH_INFO'])
       start_response('200 OK',[('Content-Types','textl/html'),('contex','text')])
       path=environ['PATH_INFO'];#请求返回的路径
       urlpatterns = routers()
       func = None
       for item in urlpatterns: #遍历循环找出和请求路径一样的地址
          if item[0] == path:
              func = item[1]
              break

       if func:
           return  func(environ)
       else:
           return  ['<h1>404!</h1>'.encode('utf8')]
#封装soket对象以及准备过程(socket,bind,listen)
http=make_server('',8080,applicattion)
print('Serving HTTP on port 8000....')
http.serve_forever()

cunrrent_time文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h11>cunrrent_time:!cur_time!</h11>
</body>
</html>

浏览器请求:

原文地址:https://www.cnblogs.com/lanyinhao/p/9334557.html