Python 做一个简单的web框架

from wsgiref.simple_server import make_server
import time
def login(req):
print(req["QUERY_STRING"])
return b"welcome"

def signup(req):
pass

def foo1(req):
f=open("index1.html","rb")
date = f.read()
return date

def foo2(req):
f = open("index2.html","rb")
date = f.read()
return date
def show_time(req):
times=time.ctime()
f=open("show_time.html","rb")
data=f.read()
data=data.decode("utf8")
data=data.replace("{{time}}",str(times))
# return ("

time:%s

"%str(times)).encode("utf8")
return data.encode("utf8")
def router():
url_patterns=[
("/login",login),
("/signup",signup),
("/yuan",foo2),
("/alex",foo1),
("/show_time",show_time),
]
return url_patterns

def application(environ,start_respone):

print("path",environ["PATH_INFO"])
path=environ["PATH_INFO"]
start_respone('200 OK',[('Content-Type','text/html')])

url_patterns=router()

func=None
for item in url_patterns:
if item[0]==path:
func=item[1]
break
if func:
return [func(environ)]
else:
return [b"404"]
httpd = make_server('',8080,application)

print('Serving Http on port 8080...')
#开始监听http请求
httpd.serve_forever()

你可能感兴趣的:(Python 做一个简单的web框架)