django、中间件、cookie、session、csrf

今日内容详细

  • django中间件三个了解的方法
  • 基于django中间件实现功能的插拔式设计
  • cookie与session简介
  • django操作cookie
  • django操作session
  • csrf跨站请求伪造

今日内容详细

django中间件三个了解的方法

1.process_view
	路由匹配成功之后执行视图函数/类之前自动触发(顺序同process_request)
2.process_exception
	视图函数/类执行报错自动触发(顺序同process_response)
3.process_template_response
	视图函数/类返回的HttpResponse对象含有render并且对应一个方法的时候自动触发(顺序同process_response)

基于django中间件的功能设计

将各个功能制作成配置文件的字符串形式
	如果想拥有该功能就编写对应的字符串
	如果不想有该功能则注释掉对应的字符串
 
补充知识	
	如果利用字符串导入模块
import importlib
s1 = 'bbb.b'  # aaa.bbb.ccc.b
res = importlib.import_module(s1)  # from aaa.bbb.ccc import b
print(res)  # <module 'bbb.b' from 'D:\\pythonProject03\\djangomiddle\\bbb\\b.py'>
'''注意字符串的结尾最小单位只能是py文件 不能是py文件里面的变量名'''
思考django中间件是如何处理的(最小单位是类名)


需求分析
	模拟编写一个消息通知功能(微信、qq、邮箱)
 
方式1:基于函数封装的版本
	没有眼前一亮的感觉 很一般
方式2:基于django中间件的功能设计
 	眼前一亮 回味无穷

class MyLogin1(object):
    def __init__(self):
        pass

    def send_msg(self, content):
        print('MyLogin1 send_msg %s' % content)

class MyLogin2(object):
    def __init__(self):
        pass

    def send_msg(self, content):
        print('MyLogin2 send_msg %s' % content)

class MyLogin3(object):
    def __init__(self):
        pass

    def send_msg(self, content):
        print('MyLogin3 send_msg %s' % content)

APP_LIST = [
    'bbb.a.MyLogin1',
    'bbb.b.MyLogin2',
    'bbb.c.MyLogin3',
]

import importlib
from myapps.settings import APP_LIST

for full_app_path in APP_LIST:
    str_class_path, str_class_name = full_app_path.rsplit('.', maxsplit=1)
    class_path = importlib.import_module(str_class_path)
    class_name = getattr(class_path, str_class_name)
    obj = class_name()
    obj.send_msg('元旦节快乐')

cookie与session简介

"""
回忆:HTTP协议四大特性
	1.基于请求响应	
	2.基于TCP、IP作用于应用层之上的协议
	3.无状态
		不保存客户端的状态
	4.无连接
"""
最开始的网站都不需要用户注册 所有人来访问获取到的数据都是一样的
随着互联网的发展很多网站需要指定当前用户的状态

cookie
	保存在客户端与用户状态相关的信息
session
	保存在服务端与用户状态相关的信息
ps:session的工作需要依赖于cookie
    
补充:浏览器有资格拒绝保存服务端发送过来的cookie数据

django操作cookie

编写一个真正的用户登录功能
def login_func(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        if username == 'jason' and password == '123':
            obj = redirect('/home/')
            obj.set_cookie('name', username)
            return obj
    return render(request, 'loginPage.html')

def login_auth(func_name):
    def inner(request, *args, **kwargs):
        if request.COOKIES.get('name'):
            res = func_name(request, *args, **kwargs)
            return res
        return redirect('/login/')

    return inner


@login_auth
def home_func(request):
    return HttpResponse('home页面 只有登录的用户才可以查看')



进阶操作:用户没有登录之前想访问某个网站输入用户名密码之后就应该调回该网站
def login_func(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', username)
            return obj
    return render(request, 'loginPage.html')


def login_auth(func_name):
    def inner(request, *args, **kwargs):
        # print(request.path)  # 只获取用户输入的路由信息
        # print(request.path_info)  # 只获取用户输入的路由信息
        target_path = request.path_info
        # print(request.get_full_path())  # 获取用户输入的路由信息+问号后面携带的数据
        if request.COOKIES.get('name'):
            res = func_name(request, *args, **kwargs)
            return res
        return redirect('/login/?next=%s' % target_path)

    return inner

django操作session

由于session是保存在服务端上面的数据 就应该有个地方能够存储
我们只需要执行数据库迁移命令即可 django会自动创建很多需要的表


django默认的session失效时间是14天


设置session	
	request.session['key'] = value
        1.生成一个随机字符串
        2.对value数据做加密处理 并在django_session表中存储
            随机字符串>>>加密数据
        3.将随机字符串也发送一份给客户端保存(cookie)
            sessionid:随机字符串
获取session	
	request.session.get('key')
        1.自动获取随机字符串
        2.去django_session表中根据随机字符串获取加密的数据
        3.自动解密数据并处理到request.sesion.get()中
    
补充说明
	1.可以设置过期时间		
 	2.存储session数据的位置也可以修改
posted @ 2022-12-22 22:41  虾仁猪心排骨汤  阅读(21)  评论(0编辑  收藏  举报