Loading

csrf相关装饰器、基于中间件思想编写项目、auth认证模块、auth模块方法大全、auth扩展表字段

csrf相关装饰器

"""
csrf_exempt 
    忽略csrf校验
csrf_protect
    开启csrf校验
"""
使用方法:先导入两个模块
from django.views.decorators.csrf import csrf_exempt,csrf_protect

针对FBV

from django.views.decorators.csrf import csrf_exempt,csrf_protect
@csrf_protect\@csrf_exempt
def login(request):
    return render(request,'login.html')

针对CBV

# @method_decorator(csrf_protect, name='post')  # 第二种
class MyClogin(views.View):
    # @csrf_protect  # 第一种
    def post(self, request):
        return HttpResponse('提示提示提示')

    @csrf_protect  # 第三种  @csrf_exempt只能使用这一种
    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(request, *args, **kwargs)

基于中间件思想编写项目

# importlib模块
# 常规导入方式
from www import b
print(b)  # <module 'ccc.b' from 'E:\\Pythonexercise\\day61_2插拔式程序\\ccc\\b.py'>
print(b.name)

# 字符串导入方式
import importlib
module_path = 'ccc.b'
res = importlib.import_module(module_path)
print(res.name)

"""
常规方式可以直接导入变量数据
eg:from ccc.b import name 
而importlib只能最小导入单位是模块文件级别
import importlib
module_path = 'ccc.b.name'
importlib.import_module(module_path)  # 不可以 最小导入单位是模块文件级别
"""

以发送提示信息为需求 编写功能

方式1:封装成函数

notify.py文件
def send_email(msg):
    print('邮箱信息提示%s' % msg)


def send_msg(msg):
    print('短信信息提示%s' % msg)


def send_qq(msg):
    print('qq信息提示%s' % msg)
def send_all(msg):
    send_email(msg)
    send_msg(msg)
    send_qq(msg)
    
start.py文件
from notify import send_all

send_all('端午节要来了')
"""
这种方式是常规的方式,但是每次改动都需要进入核心文件里去修改
"""

方式2:封装成配置

# 将功能分开放入到一个文件夹下,方便以后新增或者更改功能
# notify文件夹下的email.py
class Email(object):
    def __init__(self):
        pass  # 模拟发送邮件需要提前准备好的操作

    def send(self, msg):
        print('邮箱提醒%s' % msg)
        
# notify文件夹下的email.py的__init__.py
import settings
import importlib


def send_all(msg):
    # 1.循环获取配置文件中字符串信息
    for str_path in settings.NOTIFY_FUNC_LIST:  # 'notify.email.Email'
        # 2.切割路径信息
        module_path, class_str_name = str_path.rsplit('.', maxsplit=1)
        # 3.根据module_path导入模块文件
        module = importlib.import_module(module_path)
        # 4.利用反射获取模块文件中对应的类名
        class_name = getattr(module, class_str_name)
        # 5.实例化
        obj = class_name()
        # 6.调用发送消息的功能
        obj.send(msg)
        
        
# settings.py
NOTIFY_FUNC_LIST = [
    'notify.email.Email',
    'notify.msg.Msg',
    'notify.qq.QQ'
]


# start.py
import  notify

if __name__ == '__main__':
    notify.send_all('端午节怎么过111')

'''
这样每次只需要去settings文件下注释不想用的功能就可以了
如果新增功能也可以直接再notify文件夹下新增文件,把路径写在settings里面就可以了
'''

auth认证模块

# django提供给你快速完成用户相关功能的模块
	用户相关功能:创建、认证、编辑...
# django也配套提供了一张'用户表'
	执行数据库迁移命令之后默认产生的auth_user
# django自带的admin后台管理用户登录参考的就是auth_user表
	创建admin后台管理员用户:run manage.py task>>:createsuperuser
  自动对用户密码进行加密处理并保存

auth模块方法大全

1.验证用户名和密码是否正确

2.保存用户登录状态

from django.contrib import auth
# 1.验证用户名和密码是否正确
	auth.authenticate()
# 2.保存用户登录状态
	auth.login()
点击查看代码
def lg(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        """下面这种方式行不通了,因为密码是被自动加密过的,所以肯定比对不上"""
        # AbstractUser.objects.filter(username=username,password=password)
        """既然选择使用auth模块,那么就用它的全套功能"""
        is_user_obj = auth.authenticate(request, username=username, password=password)
        print(is_user_obj)  # 校验正确返回的是用户对象,错误时是None
        next_path = request.GET.get('next')
        print(next_path)
        if next_path:
            if is_user_obj:
                # 记录用户登录状态
                auth.login(request, is_user_obj)  # 自动操作session相关
                return redirect(next_path)
        else:
            return redirect('/home/')
    return render(request, 'lg.html')

3.获取当前用户对象

4.判断当前用户是否登录

# 3.获取当前用户对象
	request.user
# 4.判断当前用户是否登录
	request.user.is_authenticated()
点击查看代码
def get_user(request):
    print(request.user)  # 获取的是当前登录的用户对象,没有登录过则是AnonymousUser(匿名用户
    print(request.user.is_authenticated())  # 判断用户是否登录,返回布尔值True/False
    if request.user.is_authenticated():
        print(request.user.username)  # tuzi
        print(request.user.password)  # pbkdf2_sha256$36000$Qng4SkHkA3sO$OwMBiRpmgzQcU2/hinYonQTE1lQYCqLxCjDuzjwdBSk=
        print(request.user.last_login)  # 2022-05-25 13:37:38.368516+00:00
    return HttpResponse('查看当前用户是否已经登陆')

5.校验登录装饰器

from django.contrib.auth.decorators import login_required
@login_required(login_url='/lg/')  # 局部配置


@login_required  # 全局配置,需要在配置文件中添加配置
'''settings.py'''
LOGIN_URL = '/lg/'  # 需要在配置文件中添加的配置
点击查看代码
from django.contrib.auth.decorators import login_required
# @login_required  # 用户没有登录,默认跳转到/account/login/  也可以自定义
# @login_required(login_url='/lg/')  # 自定义跳转位置,局部配置
@login_required  # 全局配置
def index(request):
    return HttpResponse('index页面,只有登录的用户才能查看')

6.修改密码

request.user.check_password()  # 自动加密再比对,用来判断输入的密码与数据库里的密码是否一致
request.user.set_password()  # 临时修改密码 
request.user.save()  # 将修改操作同步到数据库中
点击查看代码
@login_required
def set_pwd(request):
    if request.method == 'POST':
        old_password = request.POST.get('old_password')
        new_password = request.POST.get('new_password')
        # 1.先比对原密码是否正确
        is_right = request.user.check_password(old_password)  # 自动加密再比对
        if is_right:
            # 2.修改密码
            request.user.set_password(new_password)  # 临时修改密码
            # 3.保存数据
            request.user.save()  # 将修改操作同步到数据库中

    return render(request, 'set_pwd.html', locals())

7.注销登录

auth.logout(request)
点击查看代码
@login_required
def logout(request):
    auth.logout(request)
    return HttpResponse('注销成功')

8.注册用户

from django.contrib.auth.models import User  # 没有更改auth表的话用这个,更改的则直接导入更改后的表
from app01 import models  # 继承了AbstractUser这个类后,直接使用models文件里的类(表名)就行了

  User.objects.create_superuser()  # 创建管理员用户
  User.objects.create_user()  # 从创建普通用户
点击查看代码
def register(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        # models.Users.objects.create(username=username, password=password)  # 不能直接create这么写,因为密码不会加密了
        # models.Users.objects.create_user(username=username, password=password)
        # create_user创建的是普通用户,is_superuser这个字段不会打勾
        models.Users.objects.create_superuser(username=username, password=password,email='123@qq.com')
        # create_superuser创建一个管理员用户,传入相应的字段
    return render(request, 'register.html')

auth扩展表字段

# 方式1:编写一对一表关系(了解)
# 方式2:类继承(推荐)
from django.contrib.auth.models import AbstractUser
class Users(AbstractUser):
    # 编写AbstractUser类中没有的字段 不能冲突!!!
    phone = models.BigIntegerField()
    addr = models.CharField(max_length=32)
    
    
'''需要再settings文件中修改配置'''
# 告诉auth模块,不再使用auth_user而是使用自定义的表
AUTH_USER_MODEL = 'app01.Users'
"""
1.类继承之后 需要重新执行数据库迁移命令 并且库里面是第一次操作才可以
2.auth模块所有的方法都可以直接在自定义模型类上面使用
	自动切换参照表
"""

项目开发流程

1.需求分析
2.技术选型
3.分组开发
4.提交测试
5.交付上线
"""
我们以后写项目 一般都是从数据库设计开始!!!
	一个好的数据库设计 会让我们写代码变得非常的轻松
"""

bbs数据表分析

"""
1.先确定表
2.再确定字段
3.最后确定关系
"""
1.用户表
	继承AbstractUser
2.个人站点表
	站点名称、标题、样式
3.文章表
	标题、简介、内容、发布时间
4.文章分类表
	分类名称
5.文章标签表
	标签名称
6.文章点赞点踩表
	文章、用户、赞/踩
7.文章评论表
	文章、用户、评论内容、评论时间
posted @ 2022-05-25 22:15  香菜根  阅读(33)  评论(0编辑  收藏  举报