视图系统CBV 和 response
?CBV和FBV
CBV(class based view)
1. CBV的定義
# 增加出版社 CBV from django.views import Viewclass AddPublisher(View):def get(self, request):passdef post(self, request):pass2. CBV使用
url(r'^add_publisher/', views.AddPublisher.as_view()),3. CBV的流程
views.AddPublisher.as_view() 程序加載的時候執(zhí)行 ——》 view函數(shù)
self = AddPublisher()
self.request = request
執(zhí)行self.dispatch方法
判斷請求方式是否被允許
允許時,通過反射獲取到AddPublisher中定義的get或者post方法 ——》handler
不允許時,self.http_method_not_allowed ——》handler
執(zhí)行handler 拿到返回結(jié)果 Httpresponse對象
CBV的匹配原理:
通過查看View的源碼,可以看到里面有很多提交方法
http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']使用ajax的時候這些方法都可以使用
這種根據(jù)url 來匹配的方法都是通過反射(getattr)獲得的. 請求發(fā)過來之后,會先走一個dispatch的方法,這個方法在View類中
def dispatch(self, request, *args, **kwargs):# Try to dispatch to the right method; if a method doesn't exist,# defer to the error handler. Also defer to the error handler if the# request method isn't on the approved list.if request.method.lower() in self.http_method_names:handler = getattr(self, request.method.lower(),self.http_method_not_allowed)else:handler = self.http_method_not_allowedreturn handler(request, *args, **kwargs)request.method.lower()將請求方式變成小寫.? 通過反射找到類中的對應(yīng)方法
所有的框架,本質(zhì)都是通過請求方式, 反射不同的函數(shù)
所以CBV的本質(zhì),其實還是用的FBV, 只不過用類封裝了而已
?
4. 給CBV加裝飾器?method_decorator
from django.utils.decorators import method_decorator? ? 加載到某個get 或者 post的方法上:
@method_decorator(timer) def get(self, request):加在self.dispatch方法上:
@method_decorator(timer) def dispatch(self, request, *args, **kwargs):加在類上:
@method_decorator(timer, name='post') @method_decorator(timer, name='get') class AddPublisher(View):5. 區(qū)別
func: <function AddPublisher.dispatch at 0x00000163735176A8>args :<app01.views.AddPublisher object at 0x00000163735F7EF0> <WSGIRequest: GET '/add_publisher/'>
使用method_decorator
func:<function method_decorator.<locals>.dec.<locals>.wrapper.<locals>.bound_func at 0x0000019664B4A378>arsgs: <WSGIRequest: GET '/add_publisher/'>
簡而言之:
不使用method_decorator的時候, 第二個參數(shù)是request
使用method_decorator的時候, 第一個參數(shù)是request
?
print(request.method) # 請求方式? ?GET 、POST print(request.GET) # get的請求數(shù)據(jù) QueryDict{} url攜帶參數(shù) print(request.POST) # post的請求數(shù)據(jù) QueryDict{} form表單提交的post數(shù)據(jù) print(request.path_info) # 路徑信息 不包含IP和端口、參數(shù)
print(request.path) #獲取請求路徑信息
print(request.body) #獲取的是請求體里的數(shù)據(jù)
print(request.FILES) #上傳的文件
? 上傳文件注意事項:
? form表單的enctype:multipart/form-data;
? method="post";
? name="作為鍵";
? {%csrf_token%};
? 取文件對象的方法: chunks();
? request.FILES中獲取文件對象
?
response對象
1. HttpResponse("字符串") --->字符串 2. render(request,"模板文件名",{k:v}) ----->完整的頁面 3. redirect("要跳轉(zhuǎn)的地址")---> 本質(zhì)是響應(yīng)頭:Location:url1. ret=HttpResponse() ret["Location"]=url(設(shè)置響應(yīng)頭)4. JsonResponse({字典}) ContentType:application/json1.傳非字典類型的時候設(shè)置: safe=False?
文件上傳?
view.py
# 上傳文件 def upload(request):if request.method == 'POST':# print(request.body)file = request.FILES.get('f1')with open(file.name, 'wb') as f:for chunk in file.chunks():f.write(chunk)return HttpResponse('上傳成功')return render(request, 'upload.html')import json from django.http import JsonResponsedef json_test(request):data = {'name': 'alex', 'pwd': 'alexdsb'}ret = HttpResponse(json.dumps(data))ret['Content-Type'] = 'application/json'ret['xxx'] = 'axxx'return ret# return HttpResponse(json.dumps(data), content_type='application/json') # Content-Type: text/html; charset=utf-8# return JsonResponse(data) # Content-Type: application/jsontemplate
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title> </head> <body> <form action="" method="post" enctype="multipart/form-data">{% csrf_token %}文件:<input type="file" name="f1"><button>上傳</button> </form> </body> </html>
form表單的enctype = 'multipart/form-data'
request.FILES中獲取文件對象
使用文件對象的chunks()
?
from django.http import JsonResponsedef json_test(request):data = {'name': 'alex', 'pwd': 'alexdsb'}return JsonResponse(data) # Content-Type: application/json# return HttpResponse(json.dumps(data), content_type='application/json') # Content-Type: text/html; charset=utf-8
?
轉(zhuǎn)載于:https://www.cnblogs.com/kenD/p/10066423.html
總結(jié)
以上是生活随笔為你收集整理的视图系统CBV 和 response的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c和c++中的-
- 下一篇: windows系统内实现端口转发