国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python實現(xiàn)手寫一個類似django的web框架示例

2020-02-15 22:28:33
字體:
供稿:網(wǎng)友

本文實例講述了Python實現(xiàn)手寫一個類似django的web框架。分享給大家供大家參考,具體如下:

用與django相似結(jié)構(gòu)寫一個web框架。

啟動文件代碼:

from wsgiref.simple_server import make_server #導(dǎo)入模塊from views import *import urlsdef routers():  #這個函數(shù)是個元組  URLpattern=urls.URLpattern  return URLpattern #這個函數(shù)執(zhí)行后返回這個元組def application(environ,start_response):  print("ok1")  path=environ.get("PATH_INFO")  print("path",path)  start_response('200 OK',[('Content-Type','text/html')])  urlpattern=routers() #講函數(shù)的返回值元組賦值  func=None  for item in urlpattern: #遍歷這個元組    if path==item[0]:  #item[0]就是#路徑后面的斜杠內(nèi)容      func=item[1]  #item[1]就是對應(yīng)的函數(shù)名      break  if func: #如果路徑內(nèi)容存在函數(shù)就存在    return func(environ) #執(zhí)行這個函數(shù)  else:    print("ok5")    return [b"404"] #如果不存在就返回404if __name__=='__main__':  print("ok0")  t=make_server("",9700,application)  print("ok22")  t.serve_forever()

urls.py文件代碼:

from views import *URLpattern = (  ("/login", login),  ("/alex", foo1),  ("/egon", foo2),  ("/auth", auth))

views.py文件代碼:

def foo1(request): # 定義函數(shù)  f=open("templates/alex.html","rb") #打開html 以二進制的模式  data=f.read() #讀到data里  f.close() #關(guān)閉  return [data] #返回這個datadef foo2(request):  f=open("templates/egon.html","rb")  data=f.read()  f.close()  return [data]def login(request):  f=open("templates/login.html","rb")  data=f.read()  f.close()  return [data]def auth(request):  print("+++",request)  user_union,pwd_union=request.get("QUERY_STRING").split("&")  _,user=user_union.split("=")  _,pwd=pwd_union.split("=")  if user=='Yuan' and pwd=="123":    return [b"login,welcome"]  else:    return [b"user or pwd is wriong"]

templates目錄下的html文件:

alex.html

<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <meta http-equiv="x-ua-compatible" content="IE=edge">  <meta name="viewport" content="width=device-width, initial-scale=1">  <title>Title</title></head><body><div>alex</div></body></html>

login.html

<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <title>Title</title></head><body><h2>登錄頁面</h2><form action="http://127.0.0.1:9700/auth">  <p>姓名:<input type="text" name="user"></p>  <p>密碼:<input type="password" name="pwd"></p>  <p>    <input type="submit">  </p></form></body></html>

下面如圖,是目錄結(jié)構(gòu)

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 英超| 金乡县| 湘潭县| 阿尔山市| 金川县| 威海市| 福安市| 鸡泽县| 汤阴县| 云林县| 安多县| 太保市| 卓尼县| 吉林省| 新源县| 清徐县| 巨鹿县| 武汉市| 越西县| 白河县| 南木林县| 平谷区| 永善县| 厦门市| 宣化县| 噶尔县| 磐安县| 察雅县| 龙胜| 林甸县| 凤庆县| 前郭尔| 朔州市| 海淀区| 芮城县| 兴业县| 科技| 黑河市| 富源县| 黑山县| 景洪市|