Django基礎之三(類檢視)

wanghui發表於2019-02-16

類檢視

簡介

檢視是一個可呼叫的物件,它接收一個請求然後返回一個響應,這個可呼叫物件可以不只是函式,Django提供一些可以用作檢視的類
基於類的檢視使用Python 物件實現檢視,它提供除函式檢視之外的另外一種方式

view

  • 屬性

http_method_names:新增未知的請求方法

  • 方法

as_view():將類檢視轉換成可被呼叫的函式檢視
dispatch(): 根據請求去匹配http_method_names下的對應函式去處理請求
http_method_not_allowed():返回405錯誤

  • 例項
from django.views import View
class IndexView(View):
    http_method_names = [`get`, `post`, `put`, `patch`, `delete`, `head`, `options`, `trace`,`list`]
    def get(self,request,*args,**kwargs):
        return HttpResponse(IndexView)

    def post(self,request,*args,**kwargs):
        data = request.POST
        return HttpResponse(data)
    #需要將list方法加入 http_method_names,否則會經過,dispatch,http_method_not_allowed():返回405錯誤
    def list(self,request,*args,**kwargs):
        return HttpResponse("ListView")
請求方式:
In [27]: import requests                                                                
In [28]: url = `http://192.168.33.10:8080/dashboard/index/`                             
In [29]: res = requests.request(`list`,url)                                             
In [30]: res.content                                                                    
Out[30]: b`ListView`

資料分頁

基於sql切片的方式分頁

資料準備

In [3]: from django.contrib.auth.models import User
In [4]: for n in range(1,101): 
...:     User.objects.create_user(`wanghui-{}`.format(n),`wanghui-{}@alibaba.com`.format(n),`123456`) 
In [5]: User.objects.all()[1:10]      

類檢視

class UserView(View):
    #http_method_names = [`get`, `post`, `put`, `patch`, `delete`, `head`, `options`, `trace`,`list`]
    def get(self,request,*args,**kwargs):
      #展示資料
        # queryset = User.objects.all()
        # return HttpResponse(queryset)
        try:
            page = int(request.GET.get(`page`))
        except:
            page = 1
        if page < 1:
            page = 1
        per = 10
        end = page * per
        start = end - per
        queryset = User.objects.all()[start:end]
        data = [{"id":user.id,"username":user.username,"email":user.email} for user in queryset]
        return JsonResponse(data,safe=False)

基於Paginator物件的分頁

class Paginator(object_list, per_page, orphans=0, allow_empty_first_page=True)
屬性
- Paginator.count 所有頁面的objects總數
- Paginator.num_pages 頁面總數
- Paginator.page_range 頁碼的範圍,從1開始,例如[1, 2, 3, 4]
方法
- Paginator.page(number) 返回一個page物件,number, 當前顯示的是第幾頁

Page物件

class Page(object_list, number, paginator)

方法
- Page.has_next() 如果有下一頁,返回True
- Page.has_previous() 如果有上一頁,返回 True
- Page.has_other_pages() 如果有上一面或下一頁,返回True
- Page.next_page_number() 返回下一頁的頁碼.如果不存在,丟擲InvalidPage異常
- Page.previous_page_number() 返回上一頁的頁碼.如果不存在,丟擲InvalidPage異常
- Page.start_index() 返回當前頁上的第一個物件,相對於分頁列表的所有物件的序號
- Page.end_index() 返回當前頁上的最後一個物件,相對於分頁列表的所有物件的序號

建立使用者小例子

from django.core.paginator import Paginator
class UserViewV2(View):
    def get(self,request,*args,**kwargs):
        queryset = User.objects.all()
        paginator = Paginator(queryset,10)
        try:
            page = int(request.GET.get("page"))
        except:
            page = 1
        if page < 1:
            page = 1
        page = paginator.page(page)
        data = [{"id":user.id,"username":user.username,"email":user.email} for user in page.object_list]
        return JsonResponse(data,safe=False)

    def post(self,request,*args,**kwargs):
        username = request.POST.get("username")
        userpass = request.POST.get("userpass")
        email = request.POST.get(`email`)
        if not username or userpass or not email:
            return JsonResponse({"errormsg":"引數有誤!"})
        user = User.objects.create(username,email,userpass)
        return JsonResponse({"id":user.id,"username":user.username,"email":user.email})

請求方式

In [1]: import requests                                                                     
In [2]: url = "http://192.168.33.10:8080/dashboard/userview/"                
In [3]: data = {}                                                                                         
In [4]: data["username"] = "zhangsan"                                                     
In [5]: data["userpass"] = `123456`                                                           
In [6]: data["email"] = "zhangsan@alibaba.com"                                     
In [7]: requests.post(url,data)                                                                 
Out[7]: <Response [200]>

相關文章