日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > windows >内容正文

windows

视图系统CBV 和 response

發(fā)布時間:2024/4/17 windows 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 视图系统CBV 和 response 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

?CBV和FBV

  • FBV(function based view )

  • CBV(class based view)

  • 1. CBV的定義

    # 增加出版社 CBV from django.views import Viewclass AddPublisher(View):def get(self, request):passdef post(self, request):pass

    2. CBV使用

    url(r'^add_publisher/', views.AddPublisher.as_view()),

    3. CBV的流程

    views.AddPublisher.as_view() 程序加載的時候執(zhí)行 ——》 view函數(shù)

    當請求到來的時候執(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ū)別

  • 不使用method_decorator

  • 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

    ?

    request對象(常用的) **

    需要記幾個常用的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中獲取文件對象

    print(request.is_ajax()) #是否是ajax請求 print(request.get_host()) print(request.get_full_path()) # 路徑信息 + 參數(shù)

    ?

    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/json

    template

    <!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()

  • ?

    JsonResponse 作用是做序列化的?

    服務(wù)器--->瀏覽器

    Contenttype:json

    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)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。