前端与后端交互返回当前时间

# _author:来童星
# date:2020/2/20
# wsgi 框架
from wsgiref.simple_server import make_server

# environ为一个对象,封装了客户端的请求信息(environ是一个包含所有请求信息的dict对象)
# start_response为服务器发送给浏览器(客户端)的响应信息
import time
def current_time(request):
cur_time_t = time.ctime(time.time())
f=open('return_time.html','rb')
data=f.read()
#将byte类型转换为字符串类型
data=str(data,'utf8').replace("!cur_time_v!",str(cur_time_t))

#字符串传的时候还是传字节
return [data.encode('utf8')]


def routers():
urlpatterns=(
('/current',current_time),


)
return urlpatterns



def application(environ, start_response):
# print('environ',environ)#为一个字典
# environ {'USERPROFILE': 'C:\\Users', 'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',..}
# print('PATH_INFO:',environ['PATH_INFO'])# 127.0.0.1 - - [20/Feb/2020 17:32:24] "GET /star/come/up HTTP/1.1" 200 18
start_response("200 ok ", [('Content-Type', 'text/html')])
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')]


# wsgi作用:
# 1.wsgi帮我们封装了socket对象以及准备过程(准备过程包括 socket对象的创建,bind,listen)
# 2.通过environ将所有请求信息封装成一个对象
# 3.通过start_response可以很方便的设置响应头
httpd = make_server('', 8080, application)
print('sereing HTTP is running on port 8080 ')

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


posted @ 2020-02-21 12:57  Stary_tx  阅读(1423)  评论(0编辑  收藏  举报