day08
cookie与session
'''
HTTP协议四大特性:
1.基于请求响应
2.基于TCP,IP作用于应用层之上协议
3.无状态
服务端无法识别客户端的状态
4.无连接
'''
cookie
保存在客户端上跟用户信息(状态)相关的数据
session
保存在服务端上跟用户信息(状态)相关的数据
ps:session的工作需要依赖于cookie
需要使用cookie(客户端浏览器有权是否保存cookie)
Django操作cookie
如果想让客户端浏览器保存cookie需要HttpResponse对象调用方法
obj = HttpResponse()或者render()或者redirect()或者JsonRepsonse()
obj.操作cookie的方法
return obj
获取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(request, ...)
rep.set_cookie(key,value,...)
rep.set_signed_cookie(key,value,salt='加密盐', max_age=None, ...)
参数:
- 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
def logout(request):
rep = redirect("/login/")
rep.delete_cookie("user") # 删除用户浏览器上之前设置的usercookie值
return rep
## 创建新Django项目day63,应用名app01
需求,当直接访问login,登录成功之后直接跳到home首页;当直接访问index页面,需要先登录,登录成功之后直接跳到index页面
1.urls.py
path('home/', views.home),
path('index/', views.index),
path('login/', views.login),
2.views.py
def login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
if username == 'jason' and password == '123':
target_path = request.GET.get('next')
if target_path:
obj = redirect(target_path) # 如果有值,则跳转到指定页面
else:
obj = redirect('/home/') # 如果没有值,则跳转到首页
obj.set_cookie('name', 'jason')
return obj
return render(request, 'login.html')
def login_auth(func_name):
def inner(request, *args, **kwargs):
if request.COOKIES.get('name'):
res = func_name(request, *args, **kwargs)
return res
else:
target_path = request.path_info
# 跳转到登录页面,同时携带要想访问的地址
return redirect(f'/login/?next={target_path}')
return inner
@login_auth
def home(request):
return HttpResponse('home页面,只有登录才能查看')
@login_auth
def index(request):
return HttpResponse('index页面,只有登录才能查看')
3.templates创建html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
{% load static %}
<script src="{% static 'jquery.js' %}"></script>
<link rel="stylesheet" href="{% static 'bootstrap-3.4.1-dist/css/bootstrap.min.css' %}">
<script src="{% static 'bootstrap-3.4.1-dist/js/bootstrap.min.js' %}"></script>
</head>
<body>
<form action=""method="post">
<p>username:
<input type="text" name="username">
</p>
<p>password:
<input type="text" name="password">
</p>
<input type="submit" value="登录">
</form>
</body>
</html>
4.启动Django,浏览器访问http://127.0.0.1:8000/login 和http://127.0.0.1:8000/index
Django操作session
请求来之后服务端产生随机字符串并发送给客户端保存,服务端存储随机字符串与用户信息的对应关系,之后客户端携带随机字符串,服务端自动校验
1.Django默认的session失效时间14天
2.客户端会接收到键值对,键默认是sessionid,值是加密的随机字符串(令牌)
request.session['name'] = 'jason'
1.Django自动产生一个随机字符串返回给客户端(对name加密)
2.往Django_session创建数据(对jason加密)
request.session.get('name')
1.自动从请求中获取sessionid对应的随机字符串
2.拿着随机字符串去django_session中匹配数据
3.如果匹配上,还会自动解密数据并展示
session的存储位置有5种模式
1. 数据库Session
SESSION_ENGINE = 'django.contrib.sessions.backends.db' # 引擎(默认)
2. 缓存Session
SESSION_ENGINE = 'django.contrib.sessions.backends.cache' # 引擎
SESSION_CACHE_ALIAS = 'default' # 使用的缓存别名(默认内存缓存,也可以是memcache),此处别名依赖缓存的设置
3. 文件Session
SESSION_ENGINE = 'django.contrib.sessions.backends.file' # 引擎
SESSION_FILE_PATH = None # 缓存文件路径,如果为None,则使用tempfile模块获取一个临时地址tempfile.gettempdir()
4. 缓存+数据库
SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db' # 引擎
5. 加密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的相关方法
# 获取、设置、删除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和Cookie的超时时间
request.session.set_expiry(value)
* 如果value是个整数,session会在些秒数后失效。
* 如果value是个datatime或timedelta,session就会在这个时间后失效。
* 如果value是0,用户关闭浏览器session就会失效。
* 如果value是None,session会依赖全局session失效策略。
# 删除当前会话的所有Session数据
request.session.delete()
# 删除当前的会话数据并删除会话的Cookie。
request.session.flush()
这用于确保前面的会话数据不可以再次被用户的浏览器访问
例如,django.contrib.auth.logout() 函数中就会调用它。
案例:
# session需要保存在服务器的数据库里,所以我们直接用Django自带的sqlit3就可以了,需要先执行数据库迁移命令
1.urls.py中
path('setSession/',views.set_session),
path('getSession/',views.get_session),
2.views.py中
def set_session(request):
request.session['name'] = 'jason'
return HttpResponse('设置session')
def get_session(request):
print(request.session.get('name'))
return HttpResponse('获取session')
3.启动Django,浏览器访问127.0.0.1:8000/setSession 和 127.0.0.1:8000/getSession
django中间件
Django中间件类似于Django的门户,所有的请求来和响应走都必须经过中间件
Django默认自带7个中间件,每个中间件都有各自负责的功能
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
Django中间件出了默认之外,还支持自定义中间件(不限制数量)
Django中间件使用场景
全局相关的功能:全局用户身份校验,全局用户黑名单校验,全局用户访问频率校验
Django自定义中间件中可以有5个方法
process_request
process_response
process_view
process_template_response
process_exception
1.process_request
1.请求来的时候会按照配置文件中注册了的中间件,从上往下一次执行每一个中间件里面的process_request方法,如果没有直接跳过
2.该方法如果返回了HttpResponse对象,那么请求不会再往后执行,原路返回
2.process_response
1.响应走的时候会按照配置文件中注册了的中间件,从下往上一次执行每一个中间件里面的process_response,如果没有直接跳过
2.该方法有2个形参,reqeust和response,默认情况下应该返回response
3.该方法也可以自己返回HttpResponse对象,相当于狸猫换太子
补充:如果请求的过程中,process_request方法直接返回了HttpResponse对象,那么会原地执行同级别的process_response方法返回
3.process_view
当路由匹配成功之后,执行视图函数之前,自动触发
该方法有四个参数
request是HttpRequest对象。
view_func是Django即将使用的视图函数。 (它是实际的函数对象,而不是函数的名称作为字符串。)
view_args是将传递给视图的位置参数的列表.
view_kwargs是将传递给视图的关键字参数的字典。 view_args和view_kwargs都不包含第一个视图参数(request)。
Django会在调用视图函数之前调用process_view方法。
4.process_excption
当视图函数报错之后,自动触发
该方法两个参数:
一个HttpRequest对象
一个exception是视图函数异常产生的Exception对象。
5.process_template_response
当视图返回的数据对象中含有rander属性对应的render方法才会触发
它的参数,一个HttpRequest对象,response是TemplateResponse对象(由视图函数或者中间件产生)。
案例:
1.app01下创建utils目录,并创建myadd.py
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
class MyMdd1(MiddlewareMixin):
def process_request(self, request):
print('MyMdd1 process_request')
# return HttpResponse('我怀疑你有问题')
def process_response(self, request, response):
print('MyMdd1 process_response')
return response
# return HttpResponse('狸猫换太子')
def process_view(self, request, view_func, view_args, view_kwargs):
print('MyMdd1 process_view')
def process_excption(self, request, exception):
print('MyMdd1 process_exception')
def process_template_response(self, request, response):
print('MyMdd1 process_template_response')
return response
class MyMdd2(MiddlewareMixin):
def process_request(self, request):
print('MyMdd2 process_request')
def process_response(self, request, response):
print('MyMdd2 process_response')
return response
def process_view(self, request, view_func, view_args, view_kwargs):
print('MyMdd2 process_view')
def process_excption(self, request, exception):
print('MyMdd2 process_exception')
def process_template_response(self, request, response):
print('MyMdd2 process_template_response')
return response
2.settings的MIDDLEWARE中添加
'app01.utils.mymdd.MyMdd1',
'app01.utils.mymdd.MyMdd2',
3.urls.py中添加
# Django中间件
path('getMd',views.get_md)
4.views.py中添加
def get_md(request):
print('from get_md')
def render():
return HttpResponse("hahaha")
obj = HttpResponse('嘿嘿嘿')
obj.render = render
# return HttpResponse('get md')
return obj
5.启动Django,浏览器访问127.0.0.1:8000/getMd,
pycharm上打印
MyMdd1 process_request
MyMdd2 process_request
MyMdd1 process_view
MyMdd2 process_view
from get_md
MyMdd2 process_template_response
MyMdd1 process_template_response
MyMdd2 process_response
MyMdd1 process_response
浏览器上打印
hahaha
登录和黑名单案例
1.models.py
from django.db import models
# Create your models here.
class UserInfolist(models.Model):
username = models.CharField(max_length=32)
password = models.CharField(max_length=32)
class UserBlocklist(models.Model):
username = models.CharField(max_length=32)
password = models.CharField(max_length=32, default='')
class UserWhitelist(models.Model):
username = models.CharField(max_length=32)
password = models.CharField(max_length=32, default='')
2.执行数据库迁移命令,同时数据库里自己插入几条数据
3.app01下创建utils/myadd.py
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
from app01 import models
class MyMdd1(MiddlewareMixin):
def process_request(self, request):
if request.method == 'POST':
username = request.POST.get('username')
user_obj = models.UserBlocklist.objects.filter(username=username).all().first()
if user_obj:
return HttpResponse('被我拉黑了,还敢来')
4.urls.py
path('home/', views.home, name='app01_home'),
path('index/', views.index, name='app01_index'),
path('login/', views.login, name='app01_login'),
path('logoff',views.logoff,name='app01_logoff'),
5.views.py
from django.shortcuts import render, HttpResponse, redirect, reverse
from app01 import models
# Create your views here.
def login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user_obj = models.UserInfolist.objects.filter(username=username).all().first()
if user_obj.username:
if user_obj.password == password:
target_path = request.GET.get('next')
if target_path:
obj = redirect(target_path)
else:
obj = redirect('app01_home')
obj.set_cookie('username', username) # 使用cookie
"""使用session需要先初始化数据库,django_session这张表"""
# request.session['username'] = username # 使用session
return obj
return render(request, 'login.html')
def logoff(request):
rep = redirect('app01_login')
rep.delete_cookie('username') # cookie删除
# request.session.delete() # session删除
return rep
def login_auth(func):
def inner(request, *args, **kwargs):
if request.COOKIES.get('username'): # 使用cookie
# if request.session.get('username'): # 使用session
print(request.session.get('username'))
res = func(request, *args, **kwargs)
return res
else:
target_path = request.path_info
# return redirect(f'/login/?next={target_path}')
return redirect('{}{}{}'.format(reverse('app01_login'), '?next=', target_path))
return inner
@login_auth
def home(request):
return HttpResponse('home页面,只有登录了才能看到哦')
@login_auth
def index(request):
return HttpResponse('index页面,只有登录了才能看到哦')
6.templates中创建login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
{% load static %}
<script src="{% static 'jquery.js' %}"></script>
<link rel="stylesheet" href="{% static 'bootstrap-3.4.1-dist/css/bootstrap.min.css' %}">
<script src="{% static 'bootstrap-3.4.1-dist/js/bootstrap.min.js' %}"></script>
</head>
<body>
<form action="" method="post">
<p>username:
<input type="text" name="username">
</p>
<p>password:
<input type="text" name="password">
</p>
<input type="submit" value="登录" class="btn btn-xs btn-success">
<a href="{% url 'app01_logoff' %}" class="btn btn-xs btn-success">注销</a>
</form>
</body>
</html>
7.启动Django,浏览器访问测试
本文作者:ycmyay
本文链接:https://www.cnblogs.com/ycmyay/p/17383812.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步