一、視圖層之請求對象def index(request): ''' request:django封裝的對象,它的類是WSGIRequest,它里面包含了所有http請求的東西 ''' print(request) print(type(request)) # from django.core.handlers.wsgi import WSGIRequest #######################1 看前博客 print(request.method) print(request.GET) print(request.POST) ########################2 path里的,get_full_path,META,F(xiàn)IELS,body # 自定制請求頭 # 上傳文件使用的編碼方式是form-data,默認(rèn)編碼方式urlencoded print(request.is_ajax()) # 是不是ajax請求 print(request.path) # 請求路徑 print(request.get_full_path()) # 請求全路徑,帶數(shù)據(jù) # print(request.body) # 請求體,二進制,如果傳文件,這個報錯 ''' 使用form表單,默認(rèn)情況下數(shù)據(jù)被轉(zhuǎn)成name=lqz&password=123放到請求體中 request.POST其實是從body中取出bytes格式的,轉(zhuǎn)成了字典 requet.GET其實是把路徑中?后面的部分拆出來,轉(zhuǎn)成了字典 ''' print(request.encoding) # 客戶端向服務(wù)端傳遞時,使用的編碼方法 print(request.META) # 重點,字典,一堆東西,請求用戶的ip地址,請求頭中數(shù)據(jù),用戶自定制請求頭的數(shù)據(jù) ''' 把請求頭的key值部分統(tǒng)一加HTTP_ 并且全部轉(zhuǎn)成大寫 ''' print(request.META['REMOTE_ADDR']) # 客戶端的ip地址 print(request.FILES) # 客戶端上傳的文件 ########################3 暫時不用關(guān)注(后面會詳解) print(request.COOKIES) # 空字典 print(request.session) # session對象 print(request.user) # 匿名用戶 return HttpResponse('ok') http請求頭,請求編碼格式3種 urlencoded form-data jason
二、視圖層之響應(yīng)對象### 重點:JsonResponse的使用(看源碼) def index(request): # 三件套 # return HttpResponse('ok') # return render(request,'index.html',context={'name':'lili','age':18}) # return redirect('/home') # 重定向自己的地址,重定向第三方地址,經(jīng)常跟反向解析一起使用 # 向客戶端返回json格式數(shù)據(jù) # import json # res=json.dumps({'name':'張三','age':18},ensure_ascii=False) # return HttpResponse(res) # django內(nèi)置提供的JsonResponse # 本質(zhì)還是HttpResponse # ensure_ascii # return JsonResponse({'name':'張三','age':18},json_dumps_params={'ensure_ascii':False}) # safe,轉(zhuǎn)換除字典以外的格式,需要safe=False return JsonResponse([11,12,13,'lili',[1,2,3],{'name':'lili','age':19}],safe=False) http響應(yīng)頭 編碼 content-type:text/html; charset=utf-8 # 返回數(shù)據(jù)的編碼類型 三、cbv和fbvCBV基于類的視圖(Class base view)和FBV基于函數(shù)的視圖(Function base view) # 寫視圖類(還是寫在views.py中) ## 第一步,寫一個類,繼承View from django.views import View class Index(View): def get(self, request): # 當(dāng)url匹配成功,get請求,會執(zhí)行它 return HttpResponse('ok') def post(self,request): return HttpResponse('post') ## 第二步:配置路由 path('index/', views.Index.as_view()), # 前期,全是FBV,后期,drf全是CBV
# 1 請求來了,路由匹配成功執(zhí)行 path('index/', views.Index.as_view()), 執(zhí)行views.Index.as_view()() # 2 本質(zhì)是執(zhí)行as_view()內(nèi)部有個閉包函數(shù)view() # 3 本質(zhì)是view()---》dispatch() # 4 dispatch內(nèi)部,根據(jù)請求的方法(get,post)---->執(zhí)行視圖類中的def get def post 五、簡單文件上傳# html注意編碼方式 <form action="/index/" method="post" enctype="multipart/form-data"> <p>用戶名:<input type="text" name="name"></p> <p>密碼:<input type="password" name="password"></p> <p><input type="file" name="myfile"></p> <p><input type="submit" value="提交"></p> </form> # views.py def index(request): file=request.FILES.get('myfile') # 打開一個空文件,寫入 with open(file.name,'wb') as f: for line in file.chunks(): f.write(line) return HttpResponse('文件上傳成功')
|
|