1. 程式人生 > >python學習第七十一天:django2與1的差別和視圖

python學習第七十一天:django2與1的差別和視圖

端口 ddd put res 127.0.0.1 正則 pass 什麽 服務

django1與2路由的差別

在django1中的url在django2中為re_path
django2中新增了path
    1.from django.urls import path
    2.不支持正則,精準匹配
    3.5個轉換器(int,str,slug,path,uuid4.自定義轉換器:
        1 寫一個類:
		class Test:
			regex = ‘[0-9]{4}‘
			def to_python(self, value):
				# 寫一堆處理
				value=value+‘aaa‘
				return value
			def to_url(self, value):
				return ‘%04d‘ % value
		2 from django.urls import register_converter
		3 register_converter(Test,‘ttt‘4 path(‘index/<ttt:year>‘, views.index,name=‘index‘),

MVC和MTV

    M          T                 V

	models	   template         views

	M          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

三件套

render
HttpResponse
redirect

JsonResponse

向前端頁面發json格式字符串
封裝了json
from django.http import JsonResponse

dic={‘name‘:‘lqz‘,‘age‘:18}
li=[1,2,3,4]

return JsonResponse(li,safe=False)

CBV和FBV

CBVclass base view)和FBV(function base view)

cbv:

from django.views import View
class Test(View):
	def dispatch(self, request, *args, **kwargs):   # 分發
		# 可加邏輯判斷語句
		obj=super().dispatch(request, *args, **kwargs)
		# 可加邏輯判斷語句
		return obj
	def get(self,request):
		obj= render(request,‘index.html‘)
		print(type(obj))
		return obj
	def 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>

viewsclass 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的差別和視圖