標籤:控制器 服務 ring submit write ext 資料互動 rect 連接埠
django1與2路由的差別
在django1中的url在django2中為re_pathdjango2中新增了path 1.from django.urls import path 2.不支援正則,精準匹配 3.有5個轉換器(int,str,slug,path,uuid) 4.自訂轉換器: 1 寫一個類:class Test:regex = ‘[0-9]{4}‘def to_python(self, value):# 寫一堆處理value=value+‘aaa‘return valuedef to_url(self, value):return ‘%04d‘ % value2 from django.urls import register_converter3 register_converter(Test,‘ttt‘)4 path(‘index/<ttt:year>‘, views.index,name=‘index‘),
MVC和MTV
M T Vmodels template viewsM V C(路由+views)models 模板 控制器其實MVC與MTV是一樣的,django中為MTV,資料互動層,視圖層以及控制層
視圖層:request對象
request對象:# form表單,不寫method ,預設是get請求# 1 什麼情況下用get:請求資料,請求頁面,# 2 用post請求:向伺服器提交資料# request.GET 字典# request.POST 字典# 請求的類型# print(request.method)# 路徑# http://127.0.0.1:8000/index/ppp/dddd/?name=lqz# 協議:ip地址和連接埠/路徑?參數(資料) # print(request.path) -->/index/ppp/dddd/# print(request.get_full_path()) -->/index/ppp/dddd/?name=lqz
三件套
renderHttpResponseredirect
JsonResponse向前端頁面發json格式字串
封裝了jsonfrom django.http import JsonResponsedic={‘name‘:‘lqz‘,‘age‘:18}li=[1,2,3,4]return JsonResponse(li,safe=False)
CBV和FBV
CBV(class base view)和FBV(function base view)cbv:from django.views import Viewclass Test(View):def dispatch(self, request, *args, **kwargs): # 分發# 可加邏輯判斷語句obj=super().dispatch(request, *args, **kwargs)# 可加邏輯判斷語句return objdef get(self,request):obj= render(request,‘index.html‘)print(type(obj))return objdef post(self,request):return HttpResponse(‘ok‘)urls中:re_path(r‘index/‘, views.Test.as_view()),
簡單檔案上傳
html中:<form action="" method="post" enctype="multipart/form-data">使用者名稱:<input type="text" name="name">密碼:<input type="text" name="password">檔案:<input type="file" name="myfile"><input type="submit"></form>views中class Cbv(View): def dispatch(self, request, *args, **kwargs): obj = super().dispatch(request, *args, **kwargs) return obj def get(self,request): return render(request,‘index.html‘) def post(self,request): aaa = request.FILES.get(‘myfile‘) with open(aaa.name,‘wb‘) as f: for line in aaa.chunks(): f.write(line) return HttpResponse(‘ok‘)
python學習第七十一天:django2與1的差別和視圖