django之分页、cookie装饰器

一、分页代码如下

from django.utils.safestring import mark_safe

class Page:
    def __init__(self, current_page, data_count, per_page_count=10, pager_num=7):
        self.current_page = current_page
        self.data_count = data_count
        self.per_page_count = per_page_count
        self.pager_num = pager_num

    @property
    def start(self):
        return (self.current_page - 1) * self.per_page_count

    @property
    def end(self):
        return self.current_page * self.per_page_count

    @property
    def total_count(self):
        v, y = divmod(self.data_count, self.per_page_count)
        if y:
            v += 1
        return v

    def page_str(self, base_url):
        page_list = []

        if self.total_count < self.pager_num:
            start_index = 1
            end_index = self.total_count + 1
        else:
            if self.current_page <= (self.pager_num + 1) / 2:
                start_index = 1
                end_index = self.pager_num + 1
            else:
                start_index = self.current_page - (self.pager_num - 1) / 2
                end_index = self.current_page + (self.pager_num + 1) / 2
                if (self.current_page + (self.pager_num - 1) / 2) > self.total_count:
                    end_index = self.total_count + 1
                    start_index = self.total_count - self.pager_num + 1

        if self.current_page == 1:
            prev = ‘<a class="page" href="javascript:void(0);">上一页</a>‘
        else:
            prev = ‘<a class="page" href="%s?p=%s">上一页</a>‘ % (base_url, self.current_page - 1,)
        page_list.append(prev)

        for i in range(int(start_index), int(end_index)):
            if i == self.current_page:
                temp = ‘<a class="page active" href="%s?p=%s">%s</a>‘ % (base_url, i, i)
            else:
                temp = ‘<a class="page" href="%s?p=%s">%s</a>‘ % (base_url, i, i)
            page_list.append(temp)

        if self.current_page == self.total_count:
            nex = ‘<a class="page" href="javascript:void(0);">下一页</a>‘
        else:
            nex = ‘<a class="page" href="%s?p=%s">下一页</a>‘ % (base_url, self.current_page + 1,)
        page_list.append(nex)

        jump = """
        <input type=‘text‘  /><a onclick=‘jumpTo(this, "%s?p=");‘>GO</a>
        <script>
            function jumpTo(ths,base){
                var val = ths.previousSibling.value;
                location.href = base + val;
            }
        </script>
        """ % (base_url,)

        page_list.append(jump)

        page_str = mark_safe("".join(page_list))

        return page_str

django分页后台代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        .pagination .page{
            display: inline-block;
            padding: 5px;
            background-color: cyan;
            margin: 5px;
        }
        .pagination .page.active{
            background-color: brown;
            color: white;
        }
    </style>
</head>
<body>
    <ul>
        {% for item in li %}
            {% include ‘li.html‘ %}
        {% endfor %}
    </ul>

    <div>
        <select id="ps" onchange="changePageSize(this)">
            <option value="10">10</option>
            <option value="30">30</option>
            <option value="50">50</option>
            <option value="100">100</option>
        </select>
    </div>

    <div class="pagination">
        {{ page_str }}
    </div>
    <script src="/static/jquery-1.12.4.js"></script>
    <script src="/static/jquery.cookie.js"></script>
    <script>

        $(function(){
                var v = $.cookie(‘per_page_count‘, {‘path‘: "/user_list/`"});
                $(‘#ps‘).val(v);
        });

        function changePageSize(ths){
            var v = $(ths).val();
            console.log(v);
            $.cookie(‘per_page_count‘,v, {‘path‘: "/user_list/"});

            location.reload();
        }
    </script>
</body>
</html>

user_list.html

/* li.html */<li>{{ item }}</li>

views.py文件

from  utils import pagination
LIST = []
for i in range(500):
    LIST.append(i)

def user_list(request):
    current_page = request.GET.get(‘p‘, 1)
    current_page = int(current_page)

    val = request.COOKIES.get(‘per_page_count‘,10)
    val = int(val)
    page_obj = pagination.Page(current_page,len(LIST),val)

    data = LIST[page_obj.start:page_obj.end]

    page_str = page_obj.page_str("/user_list/")

    return render(request, ‘user_list.html‘, {‘li‘: data,‘page_str‘: page_str})

二、cookie使用

Cookie 是由 Web 服务器保存在用户浏览器(客户端)上的小文本文件,它可以包含有关用户的信息;cookie的内容主要包括:名字,值,过期时间,路径和域。

1、获取Cookie:


1

2

3

4

5

6

request.COOKIES[‘key‘]

request.get_signed_cookie(key, default=RAISE_ERROR, salt=‘‘, max_age=None)

    参数:

        default: 默认值

           salt: 加密盐

        max_age: 后台控制过期时间

2、设置Cookie:


1

2

3

4

5

6

7

8

9

10

11

12

13

rep = HttpResponse(...) 或 rep = render(request, ...)

rep.set_cookie(key,value,...)

rep.set_signed_cookie(key,value,salt=‘加密盐‘,...)

    参数:

        key,              键

        value=‘‘,         值

        max_age=None,     超时时间

        expires=None,     超时时间(IE requires expires, so set it if hasn‘t been already.)

        path=‘/‘,         Cookie生效的路径,/ 表示根路径,特殊的:跟路径的cookie可以被任何url的页面访问

        domain=None,      Cookie生效的域名

        secure=False,     https传输

        httponly=False    只能http协议传输,无法被JavaScript获取(不是绝对,底层抓包可以获取到也可以被覆盖)

由于cookie保存在客户端的电脑上,所以,JavaScript和jquery也可以操作cookie。


1

2

<script src=‘/static/js/jquery.cookie.js‘></script>

$.cookie("list_pager_num"30,{ path: ‘/‘ });

实例:

def auth(func):
    ‘‘‘

    装饰登录判断是否存在cookie
    ‘‘‘
    def inner(request, *args, **kwargs):
        try:
            #获取加盐cookie
            v = request.get_signed_cookie(‘NID‘, salt=‘dwadwadwa‘)
            if not v:
                return redirect(‘/login/‘)
        except Exception as e:
            return redirect(‘/login/‘)
        return func(request, *args, **kwargs)
    return inner

from django.utils.decorators import method_decorator
from django import views

class Order1(views.View):
    """
    方法一
    CBV --> class Base view
    """
    @method_decorator(auth)
    def get(self,request):
        redirect_to = settings.LOGIN_REDIRECT_URL
        res = redirect(redirect_to)
        res.set_signed_cookie(‘NID‘, ‘user‘, salt="dwadwadwa")
        return res
    @method_decorator(auth)
    def post(self,request):
        redirect_to = settings.LOGIN_REDIRECT_URL
        res = redirect(redirect_to)
        res.set_signed_cookie(‘NID‘, ‘user‘, salt="dwadwadwa")
        return res
class Order2(views.View):
    """
    方法二
    CBV --> class Base view
    """
    @method_decorator(auth)
    def dispatch(self, request, *args, **kwargs):
        return super(Order2,self).dispatch(request,*args,**kwargs)

    def get(self,request):
        redirect_to = settings.LOGIN_REDIRECT_URL
        res = redirect(redirect_to)
        res.set_signed_cookie(‘NID‘, ‘user‘, salt="dwadwadwa")
        return res

    def post(self,request):
        redirect_to = settings.LOGIN_REDIRECT_URL
        res = redirect(redirect_to)
        res.set_signed_cookie(‘NID‘, ‘user‘, salt="dwadwadwa")
        return res

@method_decorator(auth,name=‘dispatch‘)
class Order3(views.View):
    """
    推荐使用:方法三
    CBV --> class Base view
    """

    def get(self,request):
        redirect_to = settings.LOGIN_REDIRECT_URL
        res = redirect(redirect_to)
        res.set_signed_cookie(‘NID‘, ‘user‘, salt="dwadwadwa")
        return res

    def post(self,request):
        redirect_to = settings.LOGIN_REDIRECT_URL
        res = redirect(redirect_to)
        res.set_signed_cookie(‘NID‘, ‘user‘, salt="dwadwadwa")
        return res

def login(request):
    """
    FBV --> func Base view
    """
    redirect_to = settings.LOGIN_REDIRECT_URL
    if request.method == "GET":
        return render(request, ‘login.html‘)
    if request.method == "POST":
        user = request.POST.get(‘username‘)
        passwd = request.POST.get(‘password‘)
        obj = models.Usertype.objects.filter(username=user,password=passwd).first()
        if obj:
            res = redirect(redirect_to)
            """
            登录成功设置cookie
            """
            res.set_signed_cookie(‘NID‘, user, salt="dwadwadwa")
            return res
        else:
            return render(request, ‘login.html‘, {‘password_is_wrong‘: True})

django cookie FBV&CBV使用方法

时间: 2024-11-03 01:37:31

django之分页、cookie装饰器的相关文章

Django基于Cookie装饰器实现用户认证

def login(request): if request.method =="GET": return render(request,"login.html") elif request.method == "POST": u = request.POST.get("user") p = request.POST.get("password") print(u,p) if u ==user and p

Django views 中的装饰器

关于装饰器 示例: 有返回值的装饰器:判断用户是否登录,如果登录继续执行函数,否则跳回登录界面 def auth(func): def inner(request, *args, **kwargs): username = request.COOKIES.get('username') if not username: # 如果无法获取 'username' COOKIES,就跳转到 '/login.html' return redirect('/login.html') # 原函数执行前 re

django 单点登录思路-装饰器

def the_one(func): '''自定义 验唯一证在线 装饰器''' def check_login_status(request): if request.session.get('qq', None): try: hert = request.session.get('hert', None) data=models.Users.objects.filter(qq=request.session.get('qq',None)).values('business_card').fir

python装饰器方法

前几天向几位新同事介绍项目,被问起了@login_required的实现,我说这是django框架提供的装饰器方法,验证用户是否登录,只要这样用就行了,因为自己不熟,并没有做过多解释. 今天查看django官网,忽然发现,装饰器用法并不是django框架提供的,而是python的一种语法,真心汗一个,自以为python用的很熟了,看来是井底之蛙! 恰逢周末,静下心来了解一下python的装饰器方法. 谈到代码里的装饰器,很自然的想到了设计模式中的装饰器模式,为了防止再次张冠李戴,特意翻了翻设计模

simple_tag,filte,分页以及cookie和装饰器

自定义simple_tag 内置的方法 首先Django中包含了很多内置的方法: 这里通过lower实现 在views视图函数中写如下代码: def tp3(request): name= "ABCDEFG" return render(request,"tp3.html",{"name":name}) 在urls路由关系中添加如下: url(r'^tp3/',views.tp3), 在tp3页面中写如下: {{ name }} {{ name|

django之基于cookie和装饰器实现用户认证

一.使用Django自带的decorator 通常情况,使用 函数定义的view,可以直接使用 login_required 直接装饰 @login_required def index(request): if request.method == "GET": return render(request, "index.htm") def user_login(request): if request.method == "GET": retu

django的auth认证,is_authenticate 和装饰器的2个方法,注销的功能,

在django中创建表,会自动创建一些django自带的表,先了解用户认证, 认证登录  先要引用  , from django.contrib import auth 有很多方法, 网站先有登录和认证, authenticate(),提供用户认证,验证用户名和密码是否正确,一般需要username ,password两个关键字参数, 认证信息有效,返回有一个User对象.authrenticate()会在User对象上设置一个属性标识,认证了该用户, 创建一个Book表,然后生成数据库 fro

Django学习笔记第八篇--实战练习四--为你的视图函数自定义装饰器

零.背景: 对于登录后面所有视图函数,都需要验证登录信息,一般而言就是验证cookie里面的一些信息.所以你可以这么写函数: 1 def personinfo(request): 2 if request.COOKIES.get("login_flag") == "1": 3 return HttpResponse("Success!") 4 else: 5 return HttpResponse("Failed!") 这样就

Django中decorators装饰器的使用

1.CBV实现的登录视图 class LoginView(View): def get(self, request): """ 处理GET请求 """ return render(request, 'login.html') def post(self, request): """ 处理POST请求 """ user = request.POST.get('user') pwd = re