标签:att query 字符 art engine use 检查 内存缓存 整数
request.COOKIES["key"] request.get_signed_cookie(key, default=RAISE_ERROR, salt="", max_age=None) # 参数 # default:默认值 # salt:加密盐 # max_age:后台控制过期时间
rep = HttpResponse(...) 或 rep = render(request, ...) rep.set_cookie(key, value, ...) rep.set_signed_cookie(key, value, salt="加密盐", ...) # 如果只有key、value默认关闭浏览器后cookie就失效了,这里可以设置以下一些参数来自定义 # 参数 # key, 键 # value="", 值 # max_age=None, 超时时间,默认秒 # expires=None, 超时时间,到什么时候截止 # path="/", Cookie生效的路径,/表示跟路径,特殊的:跟路径的cookie可以被任何url的页面访问 # domain=None, Cookie生效的域名 # secure=False, https传输 # httponly=False, 只能http协议传输,无法被JavaScript获取(不是绝对,底层抓包可以获取到也可以被覆盖)
<script src="/static/js/jquery.cookie.js"></script> $.cookie("list_pager_num", 30, {path:"/"});
from django.conf.urls import url from django.contrib import admin from django.conf.urls import include from app01 import views urlpatterns = [ url(r‘^admin/‘, admin.site.urls), url(r‘^login/‘, views.login), url(r‘^index/‘, views.index), ]
user_info = { "dachengzi" : {"pwd": "123123"}, "kangbazi": {"pwd": "kkkkkk"}, } def login(request): if request.method == "GET": return render(request, "login.html") if request.method == "POST": u = request.POST.get("username") p = request.POST.get("password") dic = user_info.get(u) if not dic: return render(request, "login.html") if dic["pwd"] == p: res = redirect("/index/") res.set_cookie("username", u) return res else: return render(request, "login.html") def index(request): # 获取当前已经登录的用户名 v = request.COOKIES.get("username") if not v: return redirect("/login") return render(request, "index.html", {"current_user": v})
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/login/" method="POST"> <input type="text" name="username" placeholder="用户名"/> <input type="password" name="password" placeholder="密码"/> <input type="submit" /> </form> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>欢迎登录,{{ current_user }}</h1> </body> </html>
这里引入了一个jQuery的插件 jquery.cookie.js
<!--设置cookie--> $.cookie("per_page_count", v, {path: "/user_list/"}); <!--获取cookie--> $.cookie("per_page_count");
from django.conf.urls import url from django.contrib import admin from django.conf.urls import include from app01 import views urlpatterns = [ url(r‘^admin/‘, admin.site.urls), url(r‘^user_list/‘, views.user_list), ]
from django.shortcuts import render from django.shortcuts import HttpResponse from django.shortcuts import redirect # Create your views here. from django.urls import reverse from utils import pagination LIST = [] for i in range(1009): 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") print(val) if val: 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}) else: page_obj = pagination.Page(current_page, len(LIST)) data = LIST[page_obj.start:page_obj.end] page_str = page_obj.page_str("/user_list/") rep = render(request, "user_list.html", {"li": data, "page_str": page_str}) rep.set_cookie("per_page_count", "10", path="/user_list/") return rep
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .pagination .page{ display: inline-block; padding: 5px; background-color: cyan; margin: 5px; } .pagination .page.active{ background-color: brown; color: black; } </style> </head> <body> <ul> {% for item in li %} {% include "li.html" %} {% endfor %} </ul> <div> <select id="px" 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"); $("#px").val(v); }); function changePageSize(ths) { var v = $(ths).val(); $.cookie("per_page_count", v, {path: "/user_list/"}); location.reload(); } </script> </body> </html>
Django中默认支持Session,其内部提供了5中类型的Session共开发者使用,Session是保存在服务器端的键值对
数据库(默认)
缓存
文件
缓存+数据库
加密cookie
Django默认支持Session,并且默认是将Session数据存储在数据库中,即:django_session 表中。 a. 配置 settings.py SESSION_ENGINE = ‘django.contrib.sessions.backends.db‘ # 引擎(默认) 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_CLOSE = False # 是否关闭浏览器使得Session过期(默认) SESSION_SAVE_EVERY_REQUEST = False # 是否每次请求都保存Session,默认修改之后才保存(默认) b. 使用 def index(request): # 获取、设置、删除Session中数据 request.session[‘k1‘] request.session.get(‘k1‘,None) request.session[‘k1‘] = 123 request.session.setdefault(‘k1‘,123) # 存在则不设置 del request.session[‘k1‘] # 所有 键、值、键值对 request.session.keys() 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失效策略。
a. 配置 settings.py SESSION_ENGINE = ‘django.contrib.sessions.backends.cache‘ # 引擎 SESSION_CACHE_ALIAS = ‘default‘ # 使用的缓存别名(默认内存缓存,也可以是memcache),此处别名依赖缓存的设置 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_CLOSE = False # 是否关闭浏览器使得Session过期 SESSION_SAVE_EVERY_REQUEST = False # 是否每次请求都保存Session,默认修改之后才保存 b. 使用 同上
a. 配置 settings.py SESSION_ENGINE = ‘django.contrib.sessions.backends.file‘ # 引擎 SESSION_FILE_PATH = None # 缓存文件路径,如果为None,则使用tempfile模块获取一个临时地址tempfile.gettempdir() # 如:/var/folders/d3/j9tj0gz93dg06bmwxmhh6_xm0000gn/T 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_CLOSE = False # 是否关闭浏览器使得Session过期 SESSION_SAVE_EVERY_REQUEST = False # 是否每次请求都保存Session,默认修改之后才保存 b. 使用 同上
数据库用于做持久化,缓存用于提高效率 a. 配置 settings.py SESSION_ENGINE = ‘django.contrib.sessions.backends.cached_db‘ # 引擎 b. 使用 同上
a. 配置 settings.py SESSION_ENGINE = ‘django.contrib.sessions.backends.signed_cookies‘ # 引擎 b. 使用 同上
from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r‘^admin/‘, admin.site.urls), url(r‘^login/‘, views.login), url(r‘^index/‘, views.index), url(r‘^logout/‘, views.logout), ]
from django.shortcuts import render from django.shortcuts import redirect from django.shortcuts import HttpResponse # Create your views here. def login(request): if request.method == "GET": return render(request, "login.html") elif request.method == "POST": user = request.POST.get("user") pwd = request.POST.get("pwd") if user == "root" and pwd == "123": # 1生成随机字符串 # 2写回用户浏览器cookie # 3保存至session中 # 在随机字符串对应的字典中设置相关内容... request.session["username"] = user request.session["is_login"] = True if request.POST.get("rmb", None) == "1": # 人为的设置超时间接 request.session.set_expiry(10) return redirect("/index/") else: return render(request, "login.html") def index(request): # 获取当前用户随机字符串 # 根据随机字符串获取对应的信息 if request.session.get("is_login", None): return render(request, "index.html", {"username": request.session["username"]}) else: return HttpResponse("滚") def logout(request): request.session.clear() return redirect("/login/")
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/login/" method="POST"> <input type="text" name="user"/> <input type="password" name="pwd"/> <input type="checkbox" name="rmb" value="1"> 10秒免登录 <input type="submit" name="提交"/> </form> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>欢迎,{{ username }}, {{ request.session.username }}</h1> <a href="/logout/">注销</a> </body> </html>
标签:att query 字符 art engine use 检查 内存缓存 整数
原文地址:http://www.cnblogs.com/qiang8216/p/7243283.html