Cookie、Session和自定义分页
Django中操作Cookie
获取Cookie
request.COOKIES['key'] request.get_signed_cookie(key,default=RAISE_ERROR, salt=' ', max_age = None)
参数:
default:默认值
salt:加盐
max_age:后台控制过期时间
设置Cookie
rep = HttpResponse(...) rep = render(reuest, ...) 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 hash’t been already。)
path = ‘/’,Cookie生效的路径,/表示根路径,特殊的:根路径的cookie可以被任何url的页面访问
domain = None,Cookie生效的域名
secure = False,https传输
secure = False只能http协议传输,无法被JavaScript获取(不是绝对,底层抓包可以获取到也可以被覆盖)
删除Cookie
def logout(request): rep = redirect('/login') rep.delete_cookie('user') #删除用户浏览器上之前设置的usercookie值 return rep
Cookie版登陆校验
def check_login(func): @wraps(func) def inner(request, *args, **kwargs): next_url = request.get_full_path() if request.get_signed_cookie('login',salt='SSS',default=None) == 'yes': #已经登录用户... return func(request,*args, **kwargs) else: #没有登录的用户,跳转刚到登录的页面 return redirect('/login/?next={}'.format(next_url)) return inner def login(request): if request.method =='POST': username = request.POST.get('username') password = request.POST.get('password') if username == 'xxx' and password == 'dashabi': next_url = request.GET.get('next') if next_url and next_url !='/logout/': response = redirect(next_url) else: response = redirect('/class_list/') reponse.set_signed_cookie('login', 'yes', salt='SSS') return repose return render(request, 'login.html')
Session
Django中默认支持Session,其内部提供了5中类型的Session供开发者使用:
1、数据库(默认)
2、缓存
3、文件
4、缓存+数据库
5、加密cookie
数据库Session
SESSION_ENGINE = ‘django.contrib.sessions.backends.db’ #引擎(默认)
缓存Session
SESSION_ENGINE = ‘django.contrib.sessions.backends.cache’ #引擎 SESSION_CACHE_ALIAS = 'default' #使用的缓存别名(默认内存缓存,也可以是memcache),此处别名依赖缓存的设置
文件Session
SESSION_ENGINE=‘django.contrib.sessions.backends.file’ #引擎
SESSION_FILE_PATH = None #缓存文件路径,如果为None,则使用tempfile模块获取一个临时地址tempfile.gettempdir()
缓存+数据库
SESSION_ENGINE = 'django.contrib.sessions.backends.signed_db' #引擎
加密Cookie Seesion
SESSION_ENGINE = ‘django.contrib.sessions.backends.signed_cookies’ #引擎
其他公用设置项:
SESSION_COOKIE_NAME = 'sessionid' #Session的cookie保存在浏览器上时的key,即:sessionid = 随机字符串(默认) SESSION_COOKIE_PATH= ‘/’ #Session的cookie保存的路径(默认) SESSION_COOKIE_DOMAIN = None #Session的cookie保存的域名(默认) SESSION_COOKIE_SECURE = False #是否Https传输cookie(默认) SESSION_COOKIE_HTTPONLY = True #是否Session的cookie只支持http传输(默认) SESSION_COOKIE_AGE = 1209600 #Session的cookie失效日期(2周)(默认) SESSION_EXPIRE_AT_BROWSER_CLLOSE = Flase #是否关闭浏览器使得Session过期(默认) SESSION_SAVE_EVERY_REQUEST = False #是否每次请求都保存Session,默认修改之后保存(默认)
不管你怎么设置Session,使用方式都一样:
def index(request): #获取,设置,删除Session中的数据 request.session['k1'] request.session.get('k1',None) request.session['k1'] = 123 request.session.setdafault('k1',123) #存在不设置 del request.session['k1'] #所有 键,值,键值对 request.session.keys(0 request.session.values() request.session.items() request.session.iterkeys() request.session.itervalues() request.session.iteritems() #用户session的随机字符串 request.session.session_key #将所有Session失效日期小于当前日期的数据删除 request.session.clear_expired() #检查 用户session的随机字符串 在数据库中是否 request.session.exists('session_key') #删除当前用户的所有Session数据 request.session.delete('session_key') request.session.set_expiry(value) *如果value是个整数,session会在秒数后失效 *如果value是个datatime或timedelta,session就会在这个时间后失效 *如果value是个0,用户关闭浏览器session就会失效 *如果value是None,session会依赖全局session失效策略
练习Session版登录验证
CBV中加装饰器相关
from django utils.decorators impoet method_decorator
1、加在get或post方法上
class LoginView(view): def dispatch(self,request, *args, **kwargs): return super(LoginView,self).dispatch(request, *args, **kwargs) def get(self,request): return render(request,'login.html') @method_decorator(test) def post(self, request): user = request.POST.get('user') pwd = request.POST.get('pwd') if user == 'alxe' and pwd == '123456': #生成随机字符串 #写在浏览器cookie:session_id:随机字符串 #写到服务端session: #{ ‘随机字符串’:{‘user_info’:‘alxe’} #} request.session['user_info'] = 'alex' return redirect('/index/') return redier(request, 'login.html')
2、加在dispatch方法上
class LoginView(View): @method_decorator(test) def dispatch(self,request, *args, **kwargs): return super(LoginView,self).dispatch(request,*args,**kwargs) def get(self, request): return render(request, 'login.html') def post(self, request): user = request.POST.get('user') pwd = request.POST.get('pwd') if user == 'alex' and pwd == '123456': #生成随机字符串 #写在浏览器cookie:session_id:随机字符串 #写到服务端session: #{ # ‘随机字符串’:{‘user_info’:‘alex’} #} request.session['user_info'] = 'alex' return redirect('/index/') return render(request, 'Login.html')
3. 加在类上
@method_decorator(test,name='get') class LoginView(View): def dispatch(self, request, *args, **kwargs): return super(LoginView,self).dispatch(request, *args, **kwargs) def get(self,request): return render(request,'login.html') def post(self,request): user = request.POST.get('user') pwd = request.POST.get('pwd') if user == 'alex' and pwd == "alex3714": # 生成随机字符串 # 写浏览器cookie: session_id: 随机字符串 # 写到服务端session: # { # "随机字符串": {'user_info':'alex} # } request.session['user_info'] = "alex" return redirect('/index/) return render(request, 'login.html')
4. CSRF Token相关只能加到dispatch方法上
备注:
- csrf_protect,为当前函数强制设置防跨站请求伪造功能,即便settings中没有设置全局中间件。
- csrf_exempt,取消当前函数防跨站请求伪造功能,即便settings中设置了全局中间件。
from django.views.decorators.csrf import csrf_exempt, csrf_protect class LoginView(View): @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return super(LoginView,self).dispatch(request, *args, **kwargs) def get(self,request): return render(request,'login.html') def post(self,request): user = request.POST.get('user') pwd = request.POST.get('pwd') if user == 'alex' and pwd == "alex3714": # 生成随机字符串 # 写浏览器cookie: session_id: 随机字符串 # 写到服务端session: # { # "随机字符串": {'user_info':'alex} # } request.session['user_info'] = "alex" return redirect('/index/') return render(request, 'login.html')
自定义分页
data = [] for i in range(1, 302): tmp = {"id": i, "name": "alex-{}".format(i)} data.append(tmp) print(data) def user_list(request): # user_list = data[0:10] # user_list = data[10:20] try: current_page = int(request.GET.get("page")) except Exception as e: current_page = 1 per_page = 10 # 数据总条数 total_count = len(data) # 总页码 total_page, more = divmod(total_count, per_page) if more: total_page += 1 # 页面最多显示多少个页码 max_show = 11 half_show = int((max_show-1)/2) if current_page <= half_show: show_start = 1 show_end = max_show else: if current_page + half_show >= total_page: show_start = total_page - max_show show_end = total_page else: show_start = current_page - half_show show_end = current_page + half_show # 数据库中获取数据 data_start = (current_page - 1) * per_page data_end = current_page * per_page user_list = data[data_start:data_end] # 生成页面上显示的页码 page_html_list = [] # 加首页 first_li = '首页 ' page_html_list.append(first_li) # 加上一页 if current_page == 1: prev_li = '上一页 ' else: prev_li = '上一页 '.format(current_page - 1) page_html_list.append(prev_li) for i in range(show_start, show_end+1): if i == current_page: li_tag = '{0} '.format(i) else: li_tag = '{0} '.format(i) page_html_list.append(li_tag) # 加下一页 if current_page == total_page: next_li = '下一页 ' else: next_li = '下一页 '.format(current_page+1) page_html_list.append(next_li) # 加尾页 page_end_li = '尾页 '.format(total_page) page_html_list.append(page_end_li) page_html = "".join(page_html_list) return render(request, "user_list.html", {"user_list": user_list, "page_html": page_html})
class Pagination(object): def __init__(self, current_page, total_count, base_url, per_page=10, max_show=11): """ :param current_page: 当前页 :param total_count: 数据库中数据总数 :param per_page: 每页显示多少条数据 :param max_show: 最多显示多少页 """ try: current_page = int(current_page) except Exception as e: current_page = 1 self.current_page = current_page self.total_count = total_count self.base_url = base_url self.per_page = per_page self.max_show = max_show # 总页码 total_page, more = divmod(total_count, per_page) if more: total_page += 1 half_show = int((max_show - 1) / 2) self.half_show = half_show self.total_page = total_page @property def start(self): return (self.current_page - 1) * self.per_page @property def end(self): return self.current_page * self.per_page def page_html(self): if self.current_page <= self.half_show: show_start = 1 show_end = self.max_show else: if self.current_page + self.half_show >= self.total_page: show_start = self.total_page - self.max_show show_end = self.total_page else: show_start = self.current_page - self.half_show show_end = self.current_page + self.half_show # 生成页面上显示的页码 page_html_list = [] # 加首页 first_li = '首页 '.format(self.base_url) page_html_list.append(first_li) # 加上一页 if self.current_page == 1: prev_li = '上一页 ' else: prev_li = '上一页 '.format(self.base_url, self.current_page - 1) page_html_list.append(prev_li) for i in range(show_start, show_end + 1): if i == self.current_page: li_tag = '{1} '.format(self.base_url, i) else: li_tag = '{1} '.format(self.base_url, i) page_html_list.append(li_tag) # 加下一页 if self.current_page == self.total_page: next_li = '下一页 ' else: next_li = '下一页 '.format(self.base_url, self.current_page + 1) page_html_list.append(next_li) # 加尾页 page_end_li = '尾页 '.format(self.base_url, self.total_page) page_html_list.append(page_end_li) return "".join(page_html_list)
def user_list(request): pager = Pagination(request.GET.get("page"), len(data), request.path_info) user_list = data[pager.start:pager.end] page_html = pager.page_html() return render(request, "user_list.html", {"user_list": user_list, "page_html": page_html})
Django内置分页
from django.shortcuts import render from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger L = [] for i in range(999): L.append(i) def index(request): current_page = request.GET.get('p') paginator = Paginator(L, 10) # per_page: 每页显示条目数量 # count: 数据总个数 # num_pages:总页数 # page_range:总页数的索引范围,如: (1,10),(1,200) # page: page对象 try: posts = paginator.page(current_page) # has_next 是否有下一页 # next_page_number 下一页页码 # has_previous 是否有上一页 # previous_page_number 上一页页码 # object_list 分页之后的数据列表 # number 当前页 # paginator paginator对象 except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) return render(request, 'index.html', {'posts': posts})
"en"> "UTF-8">
-
{% for item in posts %}
- {{ item }} {% endfor %}
class="pagination">
class="step-links">
{% if posts.has_previous %}
"?p={{ posts.previous_page_number }}">Previous
{% endif %}
class="current">
Page {{ posts.number }} of {{ posts.paginator.num_pages }}.
{% if posts.has_next %}
"?p={{ posts.next_page_number }}">Next
{% endif %}