wsgi简单web
简单的wsgi web
1.server.py
from wsgiref.simple_server import make_server
import time
def f1(request):
return [b'<h1>hello Book!</h1>']
def f2(request):
return [b'<h1>hello web!</h1>']
def current_time(request):
# 当前时间
cur_time = time.ctime(time.time())
f = open("current_time.html",'rb')
data = f.read()
data = str(data,"utf8").replace("!current_time!",str(cur_time))
return [data.encode("utf8")]
def routers():
urlpatterns = (
('/book', f1),
('/web', f2),
('/web2', f2),
('/current_time', current_time),
)
return urlpatterns
def application(environ, start_response):
# 通过environ封装了所有请求的信息dict对象
# print('environ',environ)
# print('environ',environ['PATH_INFO']) #访问127.0.0.1:8000/test --> 打印/test
start_response('200 OK', [('Content-Type', 'text/html')])
path = environ['PATH_INFO'] #path="/web"
urlpatterns = routers() #urlpatterns元组
func = None
for item in urlpatterns: #第一次item为('/book', f1)
if item[0] == path:
func = item[1] #item[1]对应函数名
break
if func:
return func(environ)
else:
return [b"<h1>404</h1>"]
# if path == "/book":
# return f1(environ)
# elif path == "/web":
# return f2(environ)
# else:
# return [b"<h1>404</h1>"]
# start_response可以很方便的设置响应头
# start_response('200 OK', [('Content-Type','text/html')])
# return [b'<h1>hello web!</h1>']
#封装socket对象和准备过程(socket,bind,listen)
httpd = make_server('', 8000, application)
print('Serving Http on port 8000...')
#开始监听HTTP请求
httpd.serve_forever()
2.current_time.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>current_time: !current_time!</h1>
</body>
</html>

浙公网安备 33010602011771号