web框架实例

s5.py

from wsgiref.simple_server import make_server
def handle_index():
    return [b'<h1>Hello,Index!</h1>']
def handle_date():
    return [b'<h1>Hello,Date!</h1>']

def RunServer(environ,start_response):
    # environ 客户发来的所有数据
    # start_response
封装要返回给用户的数据响应状态码
   
start_response('200 ok',[('Content-Type','text/html')])
    #返回的内容
   
current_url=environ["PATH_INFO"]
    if current_url=="/index":
        return handle_index()
    elif current_url=="/date":
        return handle_date()
    else:
        return [b'<h1>404</h1>']

if __name__=="__main__":
    httpd=make_server('',8000,RunServer)
    print("server http on port 8000...")
    httpd.serve_forever()

s6.py

from wsgiref.simple_server import make_server
def handle_index():
    return [b'<h1>Hello,Index!</h1>']
def handle_date():
    return [b'<h1>Hello,Date!</h1>']

URL_DICT={
    "/index":handle_index,
    "/date":handle_date,
}
def RunServer(environ,start_response):
    # environ 客户发来的所有数据
    # start_response
封装要返回给用户的数据响应状态码
   
start_response('200 ok',[('Content-Type','text/html')])
    #返回的内容
   
current_url=environ["PATH_INFO"]
    func=None
    if
current_url in URL_DICT:
        func=URL_DICT[current_url]
    if func:
        return func()
    else:
        return [b'<h1>404</h1>']
if __name__=="__main__":
    httpd=make_server('',8001,RunServer)
    print("server http on port 8001...")
    httpd.serve_forever()

s7.py

from wsgiref.simple_server import make_server
from Controller import account
URL_DICT={
    "/index":account.handle_index,
    "/date":account.handle_date,
}
def RunServer(environ,start_response):
    # environ 客户发来的所有数据
    # start_response
封装要返回给用户的数据响应状态码
   
start_response('200 ok',[('Content-Type','text/html')])
    #返回的内容
   
current_url=environ["PATH_INFO"]
    func=None
    if
current_url in URL_DICT:
        func=URL_DICT[current_url]
    if func:
        return func()
    else:
        return [b'<h1>404</h1>']
if __name__=="__main__":
    httpd=make_server('',8008,RunServer)
    print("server http on port 8008...")
    httpd.serve_forever()

view-->account.py
def handle_index():
    import time
    local_time = time.localtime(time.time())
    stime = time.strftime('%Y-%m-%d %H:%M:%S', local_time)
    f=open('view/index.html','rb')
    data=f.read()
    f.close()
    data= data.replace(b'@time', str(stime).encode("utf-8"))
    return [data,]
def handle_date():
    return [b'<h1>Hello,Date!</h1>']

Template-->index.py

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>index @time</h1>
</body>
</html>
原文地址:https://www.cnblogs.com/leiwenbin627/p/10965082.html