# _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()
