devops——7、django基础类视图和分页处理

一、基于类的视图

视图是一个可调用的对象,它接收一个请求然后返回一个响应,这个可调用对象可以不只是函数,Django提供一些可以用作视图的类
基于类的视图使用Python 对象实现视图,它提供除函数视图之外的另外一种方式
View
属性:http_method_names
方法:
as_view() #将类转成函数
dispatch()
http_method_not_allowed()

dashboard/views.py
from django.http import HttpResponse,QueryDict
from django.views import View
#采用函数视图
def login(request, *args, **kwargs):
    #get请求,展示用户登录页面
    if request.method == "GET":
        return HttpResponse("展示用户登录页面")
    #post请求,验证用户名与密码
    elif request.method == "POST":
        return HttpResponse("验证用户名与密码")
    return HttpResponse("")
#采用类视图
class LoginView(View):
    def get(self, request, *args, **kwargs):
        return HttpResponse("展示用户登录页面")

    def post(self, request, *args, **kwargs):
        return HttpResponse("验证用户名与密码")
        
class UserView(View):
    http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace', 'list']
    def get(self, request, *args, **kwargs):
        return HttpResponse("用户信息")

    def post(self, request, *args, **kwargs):
        return HttpResponse("修改用户信息")

    def delete(self, request, *args, **kwargs):
        return HttpResponse("删除用户信息")

    def put(self, request, *args, **kwargs):
        return HttpResponse("添加用户信息")

    def list(self, request, *args, **kwargs):
        return HttpResponse("用户列表")        
 #如果不添加上面的定义list请求会返回报错Method Not Allowed (LIST): /dashboard/user/       
class IndexView(View):
    def get(self, request, *args, **kwargs):
        return HttpResponse("index view")    

编写URL

dashboard/urls.py
from django.conf.urls import url,include
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^index/$', views.IndexView.as_view(), name="IndexView"),
    #采用函数视图
    url(r'^login/$', views.login),
    #采用类视图
    url(r'^loginview/$', views.LoginView.as_view()),
    url(r'^user/$', views.UserView.as_view()),
    ]

类视图登陆验证

from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
class FooView(View):
      @method_decorator(login_required)
      def get(request, *args, **kwargs):
            return HttpResponse("hello world")

二、分页

  • Paginator对象
  • Page对象

官方文档: https://docs.djangoproject.com/en/1.11/topics/pagination/

2.1 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, 当前显示的是第几页

2.2 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() 返回当前页上的最后一个对象,相对于分页列表的所有对象的序号

分页实例:
分页显示环境准备:创建100个用户:

(python36env) [vagrant@localhost devops]$ python manage.py shell
In [1]: from django.contrib.auth.models import User 
In [2]: for n in range(1,101): 
   ...:     username = "rock-{}".format(n) 
   ...:     User.objects.create_user(username, "{}@changecan.com".format(username), "123456") 
   ...:     

编写URL

dashboard/urls.py
from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    #
    url(r'^user/$', views.UserView.as_view()),
    url(r'^user2/$', views.UserViewV2.as_view()),
]

编写视图

dashboard/views.py
from django.http import HttpResponse,QueryDict,JsonResponse
from django.views import View
from django.contrib.auth.models import User
from django.core.paginator import Paginator
#方法一:通过queryset进行分页处理
class UserView(View):
    http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace', 'list']
    def get(self, request, *args, **kwargs):
        per = 10
        try:
            page = int(request.GET.get("page"))
        except:
            page = 1
        if page < 1:
            page = 1
        end = page * 10
        start = end - per
        queryset = User.objects.all()[start:end]

        data = [{"id": user.id, "email": user.email, "username":user.username} for user in queryset]
        return JsonResponse(data, safe=False)
#方法二:通过paginator进行分页处理
class UserViewV2(View):
    def get(self, request, *args, **kwargs):
        queryset = User.objects.all()
        paginator = Paginator(queryset, 10)

        page = request.GET.get("page")
        page = paginator.page(page)
        #print(page.object_list)

        data = [{"id": user.id, "email": user.email, "username":user.username} for user in page.object_list]
        return JsonResponse(data, safe=False)

页面访问:
法一:http://127.0.0.1:8000/dashboard/user/?page=6
法二:http://127.0.0.1:8000/dashboard/user2/?page=6
页面结果显示:

[{"id": 51, "email": "[email protected]", "username": "rock-49"}, {"id": 52, "email": "[email protected]", "username": "rock-50"}, {"id": 53, "email": "[email protected]", "username": "rock-51"}, {"id": 54, "email": "[email protected]", "username": "rock-52"}, {"id": 55, "email": "[email protected]", "username": "rock-53"}, {"id": 56, "email": "[email protected]", "username": "rock-54"}, {"id": 57, "email": "[email protected]", "username": "rock-55"}, {"id": 58, "email": "[email protected]", "username": "rock-56"}, {"id": 59, "email": "[email protected]", "username": "rock-57"}, {"id": 60, "email": "[email protected]", "username": "rock-58"}]

你可能感兴趣的:(python)