码迷,mamicode.com
首页 > 其他好文 > 详细

django之分页、cookie装饰器

时间:2017-01-05 16:58:55      阅读:284      评论:0      收藏:0      [点我收藏+]

标签:ati   reload   number   join   ide   request   post   表示   span   

一、分页代码如下

技术分享
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使用方法

 

django之分页、cookie装饰器

标签:ati   reload   number   join   ide   request   post   表示   span   

原文地址:http://www.cnblogs.com/patrick0715/p/6252695.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!