一、cookie
Cookie是key-value结构,类似于一个python中的字典。随着服务器端的响应发送给客户端浏览器。然后客户端浏览器会把Cookie保存起来,当下一次再访问服务器时把Cookie再发送给服务器。 Cookie是由服务器创建,然后通过响应发送给客户端的一个键值对。客户端会保存Cookie,并会标注出Cookie的来源(哪个服务器的Cookie)。当客户端向服务器发出请求时会把所有这个服务器Cookie包含在请求中发送给服务器,这样服务器就可以识别客户端了!
Django中操作cookie
设置cookie
rep = HttpResponse(...)
rep = render(request, ...) rep.set_cookie(key,value,...)
rep.set_signed_cookie(key,value,salt='加密盐',...)
参数:
key, 键
value='', 值
max_age=None, 超时时间,如果参数是None,这个cookie会延续到浏览器关闭为止
expires=None, 超时时间(IE requires expires, so set it if hasn't been already.)
path='/', Cookie生效的路径,浏览器只会把cookie回传给带有该路径的页面,这样可以避免将cookie传给
站点中的其他的应用;/表示根路径,特殊的:根路径的cookie可以被任何url的页面访问
domain=None, Cookie生效的域名
secure=False, 如果设置为True ,浏览器将通过https来回传cookie
httponly=False 只能http协议传输,无法被JavaScript获取(不是绝对,底层抓包可以获取到也可以被覆盖)
获取cookie
request.COOKIES['key']
request.get_signed_cookie(key, default=RAISE_ERROR, salt='', max_age=None)
参数:
default 默认值
salt 加密盐
max_age 后台控制过期时间
删除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_nrl = request.path_info # 访问127.0.0.1:8000/index/拿到的就是/index/
ret = request.get_signed_cookie("check_login", default=None, salt="xxx")
if ret == "": # 已经登录过的用户,继续执行
return func(request, *args, **kwargs)
else: # 没有登录过的用户,将拿到的URL做拼接,然后返回login页面
return redirect("/login/?next={}".format(next_nrl))
return inner def login(request):
if request.method == "POST":
username = request.POST.get("username")
password = request.POST.get("password")
if username == "pd" and password == "":
next_url = request.GET.get("next") # 从URL中取到 next 参数
if next_url: # 判断是否是在其他页面访问登录的
response = redirect(next_url)
else:
response = redirect("/home/")
response.set_signed_cookie("check_login", "", salt="xxx", max_age=30) # 设置一个30秒后失效的加盐cookie
return response # 登录成功后,跳转到原来的页面或指定的页面
return render(request, "login.html") def logout(request):
response = redirect("/login/")
response.delete_cookie("check_login")
return response @check_login
def home(request):
return render(request, "home.html") @check_login
def index(request):
return render(request, "index.html")
views.py
urlpatterns = [
url(r'^login/$', views.login),
url(r'^logout/$', views.logout),
url(r'^home/$', views.home),
url(r'^index/$', views.index),
]
urls.py
<form action="{{ request.get_full_path }}" method="post">
{% csrf_token %}
<h1 style="color: hotpink">这是login页面!</h1>
<p>
<label for="username">账号</label>
<input type="text" id="username" name="username">
</p>
<p>
<label for="password">密码</label>
<input type="password" id="password" name="password">
</p>
<p>
<label for="submit"></label>
<input type="submit" value="登录">
</p>
</form>
login.html
二、session
Cookie虽然在一定程度上解决了“保持状态”的需求,但是由于Cookie本身最大支持4096字节,以及Cookie本身保存在客户端,可能被拦截或窃取,因此就需要有一种新的东西,它能支持更多的字节,并且保存在服务器,有较高的安全性,这就是Session。session依赖于cookie;cookie保存在浏览器,session保存在服务器端。
diango中操作session
获取、设置、删除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的key字符串
request.session.session_key # 将所有Session失效日期小于当前日期的数据删除
request.session.clear_expired() # 检查session的key在数据库中是否存在
request.session.exists("session_key") # 删除当前会话的所有Session数据
request.session.delete()
# 删除当前的会话数据并删除会话的Cookie
request.session.flush()
这用于确保前面的会话数据不可以再次被用户的浏览器访问
例如,django.contrib.auth.logout() 函数中就会调用它 # 设置会话Session和Cookie的超时时间
request.session.set_expiry(value)
* 如果value是个整数,session会在些秒数后失效
* 如果value是个datatime或timedelta,session就会在这个时间后失效
* 如果value是0,用户关闭浏览器session就会失效
* 如果value是None,session会依赖全局session失效策略
django中session配置
Django默认支持Session,其内部提供了5种类型的Session供开发者使用,使用方式都一样,并且默认是将Session数据存储在数据库中,即:django_session 表中。
# settings.py # 数据库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.cached_db' # 加密Cookie Session
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_CLOSE = False # 是否关闭浏览器使得Session过期(默认)
SESSION_SAVE_EVERY_REQUEST = False # 是否每次请求都保存Session,默认修改之后才保存(默认)
session版登录校验
与cookie版几乎相同
def check_login(func):
@wraps(func)
def inner(request, *args, **kwargs):
next_nrl = request.path_info
if request.session.get("user"):
return func(request, *args, **kwargs)
else:
return redirect("/login/?next={}".format(next_nrl))
return inner def login(request):
if request.method == "POST":
username = request.POST.get("username")
password = request.POST.get("password")
if username == "pd" and password == "":
request.session["user"] = username
next_url = request.GET.get("next")
if next_url:
return redirect(next_url)
else:
return redirect("/home/")
return render(request, "login.html") def logout(request):
request.session.flush()
return redirect("/login/") @check_login
def home(request):
return render(request, "home.html") @check_login
def index(request):
return render(request, "index.html")
三、CBV中加装饰器
将前面的FBV版登录改为CBV版,其他FBV修改成CBV也是这样
from django import views class Login(views.View):
def get(self, request):
return render(request, "login.html") def post(self, request):
username = request.POST.get("username")
password = request.POST.get("password")
next_url = request.GET.get("next")
if username == "pd" and password == "":
if next_url:
response = redirect(next_url)
else:
response = redirect("/home/")
request.session["user"] = "xxx"
return response
要在CBV视图中使用上面的 check_login 装饰器,有一下三种方式:
①加在CBV视图的get或post方法上
from django.shortcuts import render,redirect
from functools import wraps
from django import views
from django.utils.decorators import method_decorator def check_login(func):
@wraps(func)
def inner(request, *args, **kwargs):
next_nrl = request.path_info
ret = request.session.get("user")
if ret == "xxx":
return func(request, *args, **kwargs)
else:
return redirect("/login/?next={}".format(next_nrl))
return inner class Login(views.View):
def get(self, request):
return render(request, "login.html") def post(self, request):
username = request.POST.get("username")
password = request.POST.get("password")
next_url = request.GET.get("next")
if username == "pd" and password == "":
if next_url:
response = redirect(next_url)
else:
response = redirect("/home/")
request.session["user"] = "xxx"
return response class Logout(views.View):
def get(self, request):
request.session.flush()
return redirect("/login/") class Home(views.View):
@method_decorator(check_login)
def get(self, request):
return render(request, "home.html") class Index(views.View):
@method_decorator(check_login)
def get(self,request):
return render(request, "index.html") @method_decorator(check_login)
def post(self,request):
pass
②加在dispatch方法上
CBV中首先执行的就是dispatch方法,相当于给get和post方法都加上了登录校验。
# 其他代码参考前面示例 class Home(views.View):
@method_decorator(check_login)
def dispatch(self, request, *args, **kwargs):
return super(Home, self).dispatch(request, *args, **kwargs) def get(self, request):
return render(request, "home.html") def post(self, request):
pass
③直接加在视图类上,但method_decorator必须传 name 关键字参数
如果get方法和post方法都需要登录校验的话就写两个装饰器。
# 其他代码参考前面示例 @method_decorator(check_login, name="get")
@method_decorator(check_login, name="post")
class Index(views.View):
def get(self, request):
return render(request, "index.html") def post(self,request):
pass
补充:
csrf_token装饰器在CBV上只能加在dispatch方法上;或者加在视图类上,然后name参数指定为dispatch方法。
- @csrf_exempt 取消当前函数防跨站请求伪造功能,即便settings中设置了全局中间件
- @csrf_protect 为当前函数强制设置防跨站请求伪造功能,即便settings中没有设置全局中间件
函数视图版:
from django.views.decorators.csrf import csrf_exempt, csrf_protect @csrf_exempt
def login(request):
if request.method == "POST":
username = request.POST.get("username")
password = request.POST.get("password")
next_url = request.GET.get("next")
if username == "pd" and password == "":
if next_url:
response = redirect(next_url)
else:
response = redirect("/show_author/")
response.set_signed_cookie("check_login", "", salt="xxx", max_age=30)
return response
return render(request, "login.html")
类视图版:
①
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from django.utils.decorators import method_decorator
from django import views
class Login(views.View): @method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
return super(Login, self).dispatch(request, *args, **kwargs) def get(self, request):
return render(request, "login.html") def post(self, request):
username = request.POST.get("username")
password = request.POST.get("password")
next_url = request.GET.get("next")
if username == "pd" and password == "":
if next_url:
response = redirect(next_url)
else:
response = redirect("/home/")
request.session["user"] = "xxx"
return response
②
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from django.utils.decorators import method_decorator
from django import views @method_decorator(csrf_exempt, name="dispatch")
class Login(views.View): def dispatch(self, request, *args, **kwargs):
return super(Login, self).dispatch(request, *args, **kwargs) def get(self, request):
return render(request, "login.html") def post(self, request):
username = request.POST.get("username")
password = request.POST.get("password")
next_url = request.GET.get("next")
if username == "pd" and password == "":
if next_url:
response = redirect(next_url)
else:
response = redirect("/home/")
request.session["user"] = "xxx"
return response