内容概要
- csrf相关装饰器
- 基于中间件思想编写项目
- auth认证模块
csrf相关装饰器
| from django.views.decorators.csrf import csrf_exempt,csrf_protect |
| """ |
| csrf_exempt |
| 忽略csrf校验 |
| csrf_protect |
| 开启csrf校验 |
| """ |
| |
| @csrf_protect\@csrf_exempt |
| def login(request): |
| return render(request,'login.html') |
| |
| csrf_protect 三种CBV添加装饰器的方式都可以 |
| csrf_exempt 只有一种方式可以生效(给重写的dispatch方法装) |

基于中间件思想编写项目
| |
| 可以通过字符串的形式导入模块 |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| from ccc.b import name |
| import importlib |
| module_path = 'ccc.b.name' |
| importlib.import_module(module_path) |
| |
| '''以发送提示信息为需求 编写功能''' |
| 方式1:封装成函数 |
| 方式2:封装成配置 |
| |
| NOTIFY_FUNC_LIST = [ |
| 'notify.email.Email', |
| 'notify.msg.Msg', |
| 'notify.qq.QQ', |
| 'notify.weixin.WeiXin' |
| ] |
| |
| |
| class Email(object): |
| def __init__(self): |
| pass |
| def send(self,msg): |
| print('邮箱提醒:%s'%msg) |
| |
| |
| import settings |
| import importlib |
| def send_all(msg): |
| |
| for str_path in settings.NOTIFY_FUNC_LIST: |
| |
| module_path, class_str_name = str_path.rsplit('.', maxsplit=1) |
| |
| module = importlib.import_module(module_path) |
| |
| class_name = getattr(module, class_str_name) |
| |
| obj = class_name() |
| |
| obj.send(msg) |
| |
auth认证模块
| |
| 用户相关功能:创建、认证、编辑... |
| |
| 执行数据库迁移命令之后默认产生的auth_user |
| |
| 创建admin后台管理员用户:run manage.py task>>:createsuperuser |
| 自动对用户密码进行加密处理并保存 |
auth模块方法大全
| from django.contrib import auth |
| |
| auth.authenticate() |
| |
| auth.login() |
| |
| request.user |
| |
| request.user.is_authenticated() |
| |
| from django.contrib.auth.decorators import login_required |
| @login_required(login_url='/lg/') |
| @login_required |
| LOGIN_URL = '/lg/' |
| |
| request.user.check_password() |
| |
| request.user.set_password() |
| request.user.save() |
| |
| auth.logout(request) |
| |
| from django.contrib.auth.models import User |
| User.objects.create_superuser() |
| User.objects.create_user() |
auth扩展表字段
| |
| |
| from django.contrib.auth.models import AbstractUser |
| class Users(AbstractUser): |
| |
| phone = models.BigIntegerField() |
| addr = models.CharField(max_length=32) |
| |
| AUTH_USER_MODEL = 'app01.Users' |
| """ |
| 1.类继承之后 需要重新执行数据库迁移命令 并且库里面是第一次操作才可以 |
| 2.auth模块所有的方法都可以直接在自定义模型类上面使用 |
| 自动切换参照表 |
| """ |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人