Django 視圖層

1.1 request請求對象 屬性/方法

  • django將請求報文中的請求行、首部信息、內容主體封裝成 HttpRequest 類中的屬性
(1)request.GET 相似於字典對象,包含HTTP GET全部參數 (2)request.POST 相似於字典對象,請求中包含表單數據,將這些數據封裝成 QueryDict 對象。 (3)request.body 一個字符串,表明請求報文的主體 (4)request.path 一個字符串,請求路徑的組件 (5)request.method 一個字符串,表示請求使用的HTTP 方法。必須使用大寫。 (6)request.get_full_path() 返回請求路徑組件(包含數據部分) (7)request.files 一個相似於字典的對象,包含全部的上傳文件的信息 注:FILES 中的每一個鍵爲<input type="file" name="" /> 中的name,值則爲對應的數據。 ,FILES 只有在請求的方法爲POST 且提交的<form>帶有enctype="multipart/form-data" 的狀況下才會包含數據。不然,FILES 將爲一個空的相似於字典的對象。 -------------------------------------------- 注: form表單,不寫method ,默認是get請求 #get與post應用場景 1 get:請求數據,請求頁面, 2 post請求:向服務器提交數據 
  • 代碼:
模板:
<body>
    {#不寫method ,默認是get請求#}
<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>
</body>

  

 urls: re_path('^index1/',views.index1) views: def index1(request): print(type(request )) #<class 'django.core.handlers.wsgi.WSGIRequest'> print(request) #<WSGIRequest: GET '/index1/'> print(request.POST ) #<QueryDict: {}> #< QueryDict: {'name': ['hh'], 'password': ['77'], 'myfile': ['']} > print(request .GET) #<QueryDict: {}> print(request.path) # 請求路徑的組件/index1/ print(request.get_full_path()) #請求組件,包含數據部分 print(HttpResponse) #<class 'django.http.response.HttpResponse'> print(request.body) # b'' get 請求沒有內容,post請求內容爲b'name=rr&password=tt' return render(request ,'index.html') 

1.2 HttpResponse響應對象

1.2.1 形式一 HttpResponse():

  • HttpResponse()括號內直接跟一個具體的字符串做爲響應體

1.2.2 形式二 render():

  • 做用:結合一個給定的模板和一個給定的上下文字典,並返回一個渲染後的 HttpResponse 對象
  • 格式:
render(request, template_name[, context]) 參數: (1)request用於生成響應的請求對象。 (2)template_name:要使用的模板的完整名稱,可選的參數 (3)context:添加到模板上下文的一個字典。默認是一個空字典。若是字典中的某個值是可調用的,視圖將在渲染模板以前調用它。 例: book_list=Book.objects.all() return render(request,'book_list.html',{'book_list':book_list}) 

1.2.3 形式三 redirect()

  • 重定向url
def my_view(request):
    return redirect('/some/url/')
    
或者是完整的url:
def my_view(request):
    return redirect('http://www.baidu.com/') 

  

  • 代碼:
 obj=render(request,'index.html')
    print(obj) #<HttpResponse status_code=200, "text/html; charset=utf-8">
    print(type(obj)) #<class 'django.http.response.HttpResponse'>
    return obj
    
    obj = redirect('/index2/')
    print(obj) #<HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/index2/">
    return obj

  

1.3 JsonResponse

  • 向前端返回一個json格式字符串的兩種方式
方式一:
import json
    dic={'name':'lqz',"age":33}
    return HttpResponse(json.dumps(dic))
方式二:
from django.http import JsonResponse
    dic = {'name': 'lqz', "age": 33}
    return JsonResponse (dic)

  

--------------------------------------- 注:在返回列表的時候要設置safe=False from django.http import JsonResponse li = [1, 2, 3, 4] return JsonResponse(li,safe=False) 

1.4 CBV和FBV

  • CBV基於類的視圖(Class base view)和FBV基於函數的視圖(Function base view)

1.4.1 CBV

views:
from django.views import View
# 先導入View,並繼承
class Test(View):
     #對請求進行判斷,分發
     def dispatch(self, request, *args,**kwargs ):
        #加邏輯
        print('eeeee')  #先打印eeeee,而後執行get/post請求函數,再打印fffff
        obj=super().dispatch(request, *args,**kwargs) #繼承父類屬性
        #加邏輯
        print('fffff')
        return obj
        
    def get(self,request):
        obj=render(request,'index.html')
        print(type(obj)) #<class 'django.http.response.HttpResponse'>
        return obj
    def post(self,request):
        print(request.POST) #<QueryDict: {'name': ['hh'], 'password': ['ff']}>
        return HttpResponse ('ok')

urls:
 path('test/',views.Test.as_view()) #.as_view()固定寫法

  

1.5 文件上傳

模板:
<body>
    {#不寫method ,默認是get請求;在請求的方法爲POST 且提交的<form>帶有enctype="multipart/form-data" 的狀況下才會包含數據#}
<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>
</body>

視圖函數:
from django.views import View
class Test(View):
     def get(self,request):
        obj=render(request,'index.html')
        print(type(obj)) #<class 'django.http.response.HttpResponse'>
        return obj
    def post(self,request):
        print(request.POST) #<QueryDict: {'name': ['hh'], 'password': ['ff']}>
        # ff是文件對象,能夠取出內容保存到本地 <MultiValueDict: {'myfile': [<InMemoryUploadedFile: 響應狀態碼.PNG (text/plain)>]}>
        ff=request .FILES.get('myfile')
        # print(ff.name) # 調get方法取出文件 響應狀態碼.PNG
        file_name=ff.name
        print(type(ff))  #<class 'django.core.files.uploadedfile.InMemoryUploadedFile'>
        with open(file_name ,'wb') as f:
            for line in ff.chunks():
                f.write(line)
        return HttpResponse ('ok')

urls:
path('test/',views.Test.as_view()) #.as_view()固定寫法
相關文章
相關標籤/搜索