cookie和session

  • 为什么要有cookie和session?

    • 原因是HTTP协议的是无状态的, 不保存用户状态
  • 作用:
    • 为了保存用户状态

cookie

  • 保存在客户端浏览器的键值对

  • cookie虽然是保存在客户端服务器上的, 但它是由服务端设置的

  • 浏览器有权禁止cookie写入

  • 查看浏览器cookie --> 右键检查-->application

  • 需要通过HttpResponse对象才能操作cookie

  • 设置cookie
    • max_age/expires 参数设置浏览器保存cookie的时间
obj = HttpResponse()
# max_age参数用来设置浏览器保存cookie时间, 单位是秒
obj.set_cookie('key', 'value', max_age=5)
  • 获取cookie
request.COOKIES.get('key')
  • request.path_info 获取当前用户访问的url

  • request.full_path 获取当前用户访问的url以及携带的参数

  • 删除cookie/(注销功能)

obj.delete_cookie('key')
def login(request):
next_path = request.GET.get('next')
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
if username == 'bigb' and password == '123':
# 从哪个页面过来, 登录后就跳转到那个页面
if next_path:
obj = redirect(next_path)
# 登录后默认跳转到home页面
else:
obj = redirect('/home/')
obj.set_cookie('whoami', 'bigb')
return obj return render(request, 'login.html') # 登录认证装饰器
def login_auth(func):
@wraps(func)
def inner(request, *args, **kwargs):
if request.COOKIES.get('whoami'):
res = func(request, *args, **kwargs)
return res
else:
# 获取当前页面url
current_url = request.path_info
# 携带当前页面url参数, 重定向到login页面
return redirect(f'/login/?next={current_url}')
return inner @login_auth
def home(request):
return HttpResponse('登录后才能访问') @login_auth
def index(request):
return HttpResponse('登录后才能访问') @login_auth
def logout(request):
# 删除cookie
request.delete_cookie('whoami')
return redirect('/home/')

session

  • 保存在服务器上面的键值对
  • session的工作机制是需要依赖cookie的
  • 设置session
    • session默认保存在数据库中的django_session表中, 因此要先执行数据库迁移命令
    • django默认的session有效时间是两周
request.session['key'] = 'value'
'''
1.django内部生成了一个随机字符串 2.在数据库session_data表中添加数据:
随机字符串 加密数据 到期时间 3.将产生的随机字符串返回给浏览器
sessionid: 随机字符串
'''
  • 获取session
'''
1.django会自动去请求头里面获取cookie
2.拿着sessionid所对应的随机字符串, 去数据库中session_data中比对
3.拿到随机字符串对应的数据, 添加到request.session中 '''
request.session.get('key')
  • 删除session
# 浏览器和服务端都删除
request.session.delete()
  • 设置到期时间
request.session.set_expiry(5)
def login(request):
next_url = request.GET.get('next')
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password') if username == 'bigb' and password == '123':
# 创建session
request.session['username'] = 'bigb'
# 设置到期时间, 默认是秒
request.session.set_expiry(10)
if next_url:
return redirect(next_url)
return redirect('/home/')
return render(request, 'login.html') def login_auth(func):
@wraps(func)
def inner(request, *args, **kwargs):
# 获取session
if request.session.get('username'):
res = func(request, *args, **kwargs)
return res
else:
current_url = request.path_info
return redirect(f'/login/?next={current_url}')
return inner @login_auth
def home(request):
return HttpResponse('登录后才能访问') @login_auth
def index(request):
return HttpResponse('登录后才能访问') @login_auth
def logout(request):
# 删除session
request.session.delete()
return redirect('/home/')

token

  • 服务端借助加密算法, 无须保存session数据
  • username--->通过加密算法--->生成字符串
  • 将username和随机字符串进行拼接, username+随机字符串, 并返回给客户端,
  • 客户端再次访问时, 对 username+字符串1 进行切割获取username
  • 对username进行加密算法处理, 得到字符串2, 如果字符串2==字符串1, 则是合法用户

Django中间件

  • django默认有七个中间件
  • 支持自定义中间件(类), django暴露给用户5个自定义的中间件下面的方法
  • 这5个方法在条件成立时自动触发

自定义中间件

  • 在APP目录下创建一个文件夹, 并在该文件夹下新建一个py文件
  • 查看settings.py中的中间件的代码, 对照着写
  • 在settings.py中注册我们创建好的中间件
import re

from django.conf import settings
from django.http import HttpResponsePermanentRedirect
from django.utils.deprecation import MiddlewareMixin class MyMid1(MiddlewareMixin):
def process_request(self, request):
print('MyMid1--process_request') def process_response(self, request, response):
print('Mymid1--process_response')
return response class MyMid2(MiddlewareMixin):
def process_request(self, request):
print('MyMid2--process_request') def process_response(self, request, response):
print('Mymid2--process_response')
return response # settings.py
# 这样就可以点进去查看代码了
from django.middleware.security import SecurityMiddleware
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',
# 注册自定义中间件
'app01.mymidware.mymid.MyMid1',
'app01.mymidware.mymid.MyMid2',
]

process_request

  • 请求来的时候, 会按照settings.py中从上到下执行各个中间件的process_request方法
  • 如果中间件没有process_request方法, 则跳过该中间件
  • process_request方法一旦返回了HttpResponse对象, 既响应了请求, 请求不会再往后走
'''
由于process_request方法可以响应请求, 使得中间件适合做网站的全局性功能
1.全局性的用户登陆校验
2.全局性的用户访问权限校验
3.全局性的用户访问频率校验 '''

process_response

  • 响应走的时候, 会按照settings.py中从下到上执行中间件中的process_response方法
  • 该方法必须有两个形参, request和response, 必须返回response, 否则直接报错
  • process_response方法返回什么, 前端就能获取什么 (可以逐级替换)
  • 当process_request方法返回HttpResponse对象, 那响应只从当前的process_response方法开始返回

其他方法

  • process_view

    • def process_view(self, request, view_name, *args, **kwargs):
    • 执行视图函数之前触发
    • 如何该方法返回HttpResponse对象, 则不会执行视图函数, 响应会经过所有的process_response方法
  • process_exception

    • def process_exception(self, request, exception):
    • 在视图函数出现错误时候, 自动触发, 顺序是从下往上
  • process_templates_response

    • 当视图函数返回的对象中含有render属性指向是一个render方法的时候才会触发, 顺序从下往上

Django 10的更多相关文章

  1. Django 10 GET和POST(HttpRequest对象,GET和POST请求,文件上传,HttpResponse对象的cookie)

    Django 10 GET和POST(HttpRequest对象,GET和POST请求,文件上传,HttpResponse对象的cookie) 一.HttpRequest对象 #HttpRequest ...

  2. python框架之Django(10)-Form组件

    介绍 我们之前在HTML页面中利用form表单向后端提交数据时,都会写一些获取用户输入的标签并且用form标签把它们包起来.与此同时我们在好多场景下都需要对用户的输入做校验,比如校验用户是否输入,输入 ...

  3. django 10.5 sqlite3迁移到mysql

    参考: http://www.voidcn.com/article/p-hesvaooz-ru.html 原文: python ./manage.py syncdb --database slave ...

  4. Python3+Apache+Django+CentOS

    使用django开发的项目上到正式环境的环境搭建,系统软件版本: CentOS6. setuptools-.tar.gz pip-.tar.gz Python-.tgz pcre-8.39.tar.b ...

  5. Python Django项目日志查询系统

    该项目适合中小型公司日志查询工作.大型公司可以使用elk等.该系统其实就是调用了absible命令去查日志,然后把输出的信息输到页面查看. 日志查询系统 维护手册 作者:陈土锋 日期:2020年6月1 ...

  6. 第一章 初识Mysql

    Mysql是一个开放源代码的数据库管理系统(DBMS),它是由MySQL AB 公司开发.发布并支持的. 登录 -- mysql #本地登录,默认用户root,空密码,用户为root@127.0.0. ...

  7. python——Pycharm的简单介绍

    一.什么是Pycharm? Pycharm是一种python IDE,带有一整套可以帮助用户在使用Python语言开发时提高其效率的工具,比如调试.语法高亮.Project管理.代码跳转.智能提示.自 ...

  8. 数据库学习之MySQL基础

    数据库基础 一.数据库简介 数据库:存放数据的仓库 sql及其规范 sql是Structured Query Language(结构化查询语言)的缩写.SQL是专为数据库而建立的操作命令集,是一种功能 ...

  9. 饮冰三年-人工智能-Python-21 Python数据库MySql

    一:下载与安装 1:下载地址:https://dev.mysql.com/downloads/mysql/ 2:安装MySql 打开下载文件解压到指定文件目录.(我这里解压目录为D:\MySql\my ...

随机推荐

  1. [LC]643题 Maximum Average Subarray I(子数组最大平均数 I)

    ①英文题目 Given an array consisting of n integers, find the contiguous subarray of given length k that h ...

  2. 在react中配置less

    在创建项目之后执行 $ yarn eject 抽离配置文件 会多出config和script文件夹 接下来安装less yarn add less less-loader 或者 npm install ...

  3. [spark程序]统计人口平均年龄(本地文件)(详细过程)

    一.题目描述 (1)编写Spark应用程序,该程序可以在本地文件系统中生成一个数据文件peopleage.txt,数据文件包含若干行(比如1000行,或者100万行等等)记录,每行记录只包含两列数据, ...

  4. 在linux (centos)上使用puppeteer实现网页截图

    1.安装nodejs和npm # 下载解压 wget -c https://nodejs.org/dist/v8.9.1/node-v8.9.1-linux-x64.tar.xz tar -xvf n ...

  5. bat脚本知识总结

    1常用基本命令 1.1 @ 它的作用是让执行窗口中不显示它后面这一行的命令本身 1.2 echo 它其实是一个开关命令,就是说它只有两种状态:打开和关闭.于是就有了echo on 和echo off两 ...

  6. Unix, Linux以及NT内核和它们各自衍生的系统关系图

  7. 源码分析RocketMQ消息轨迹

    目录 1.发送消息轨迹流程 1.1 DefaultMQProducer构造函数 1.2 SendMessageTraceHookImpl钩子函数 1.3 TraceDispatcher实现原理 2. ...

  8. 根据本地ip获取地理位置,再根据地理位置,获取天气

    import json,requestsfrom urllib.request import urlopenfrom pyquery import PyQuery as pqfrom lxml imp ...

  9. 2019-9-20:渗透测试,基础学习,笔记,metasploit的基础使用

    使用kali下metasploit生成木马,控制windows系统 kali基于debin的数字取证系统,上面集成了很多渗透测试工具,前身为bt r3(BrackTrack) Metasploit,是 ...

  10. HTML、CSS基础知识

    前端基础 1. CSS 8 1.1. CSS叫做层叠样式表,用来设置页面中元素的样式.背景颜色.字体颜色.字体大小... 8 1.2. CSS负责结构.表现.行为中的表现 8 1.3. 编写的位置 8 ...