?????????????? Python? web開發(fā)簡單流程------->wsgiref
一,基礎(chǔ)入門:
from wsgiref.simple_server import make_server???? #引入wsgire模塊中的服務(wù)器,用作web服務(wù)器
def application(env, response):???????? # 定義web接口函數(shù)'''??? 定義了一個(gè)web接口函數(shù),可以接受瀏覽器客戶端發(fā)送的url地址,調(diào)用執(zhí)行函數(shù) 通過url地址調(diào)用執(zhí)行函數(shù)
:param env: 環(huán)境,表示瀏覽器發(fā)送的請(qǐng)求環(huán)境
:param response: 響應(yīng):表示服務(wù)器給瀏覽器客戶端 返回?cái)?shù)據(jù)【響應(yīng)數(shù)據(jù)】
response('200 OK', [('Content-type', 'text/html;charset=utf-8')])?? # 定義響應(yīng)內(nèi)容的格式[返回?cái)?shù)據(jù)的格式]
# 定義返回的數(shù)據(jù) msg =‘你好’
# 返回?cái)?shù)據(jù)【列表~表示可以返回很多數(shù)據(jù)——返回二進(jìn)制數(shù)據(jù)[字節(jié)數(shù)據(jù)]】??
# 擴(kuò)展;字符->字節(jié)encode? 字節(jié)->字符decode? ?
return [msg.encode('utf-8')]
if __name__ == "__main__":?
http_server = make_server('', 8000, application)? ? # 將接口函數(shù)(web項(xiàng)目)部署到服務(wù)器
# 參數(shù)1:web服務(wù)器部署的ip地址;空字符串表示本機(jī)地址? ? # 參數(shù)2:服務(wù)器部署的端口號(hào)? ? # 參數(shù)3:服務(wù)器中部署的web項(xiàng)目[網(wǎng)關(guān)接口函數(shù)]??
print('server is starting...')?
http_server.serve_forever()? ? # 啟動(dòng)服務(wù)器??
最后啟動(dòng)?? python 文件名.py runserver
總結(jié):客戶端通過url,找到web服務(wù)器中的項(xiàng)目,然后服務(wù)器調(diào)用接口函數(shù),得到數(shù)據(jù)
二,網(wǎng)頁視圖:
from wsgiref.simple_server import make_server
def application(env, response):
? ? response('200 OK', [('Content-type', 'text/html;charset=utf-8')])
? ? # 讀取網(wǎng)頁數(shù)據(jù)
? ? # with open('index.html', 'rb') as f:
? ? #? ? msg = f.read()
? ? f = open('index.html', 'rb') #(需要打開的網(wǎng)頁名稱)
? ? msg = f.read()
? ? f.close()
? ? # 返回?cái)?shù)據(jù)
? ? return [msg]
# 部署項(xiàng)目
if __name__ == "__main__":
? ? # 部署項(xiàng)目
? ? http_server = make_server('', 8000, application)
? ? print('server啟動(dòng)了...')
? ? # 啟動(dòng)項(xiàng)目
? ? http_server.serve_forever()
三,網(wǎng)頁視圖高級(jí)處理:
from wsgiref.simple_server import make_server
import views? #導(dǎo)入處理函數(shù)模塊(自定義的)
def application(env, resp):
? ? # 定義響應(yīng)頭
? ? resp('200 OK', [('Content-type', 'text/html;charset=utf-8')])
? ? # 判斷用戶的請(qǐng)求,跳轉(zhuǎn)不同的網(wǎng)頁
? ? path = env['PATH_INFO']? ? ?? #根據(jù)PATH_INFO來判斷用戶要跳轉(zhuǎn)到哪個(gè)頁面
? ? if path == '/login':??? 例如:
? ? ? ? return views.login(env, resp)
? ? elif path == '/register':
? ? ? ? return views.register(env, resp)
? ? # 讀取網(wǎng)頁數(shù)據(jù)
? ? with open('index.html', 'rb') as f:
? ? ? ? data = f.read()
? ? # 模擬從數(shù)據(jù)庫讀取了一個(gè)數(shù)據(jù)
? ? name = '老王'
? ? # 替換數(shù)據(jù)
? ? data = str(data, 'utf-8').replace('{{name}}', name)
? ? # 返回?cái)?shù)據(jù)
? ? return [data.encode('utf-8')]
# 啟動(dòng)入口
if __name__ == "__main__":
? ? http = make_server('', 9000, application)
? ? print('服務(wù)器啟動(dòng)了...等待客戶端連接中...')
? ? http.serve_forever()