1.一个项目对应一个虚拟环境
mkvirtualenv -p /usr/bin/python3 promote
2.下载安装django(使用django项目做框架)
pip install django -i https://pypi.douban.com/simple
3.下载安装drf
pip install djangorestframework -i https://pypi.douban.com/simple
4.下载安装pymysql(使用mysql数据库)
pip install pymysql -i https://pypi.douban.com/simple
1.
mysql -uroot -p
create database `promote` charset='utf8';
grant all privileges on `promote`.* to 'promoteu'@'%' identified by 'qwe123';
mysql -upromoteu -p
show databases;
1.创建项目
django-admin startproject promote
2.给pycharm创建新的项目和项目的配置
https://editor.csdn.net/md/?articleId=121496997
https://editor.csdn.net/md/?articleId=121498949
1.新建文件用于存放各类APP,并设置为资源目录(APP目录)
sys.path.insert(0, BASE_DIR)
sys.path.insert(1, os.path.join(BASE_DIR, 'apps'))
1.创建映射文件提交到数据库
2.创建超级管理员
3.访问后台管理系统
4.创建两个组
5.创建用户,选择用户组
1.保存私钥,防止泄露
2.设置保密(屏蔽config)
3.下载drf认证模块
pip install djangorestframework-jwt -i https://pypi.douban.com/simple
4.配置令牌过期时间
# 过期时间配置
JWT_AUTH = {
'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1),
}
5.jwt 自带登录接口,配置路由(放在总路由不合适,先创建APP)
6.APP
7.登录
1.连接数据库
1.再创建一个APP
2. 创建模型
from django.db import models
from django.contrib.auth.models import User # Django认证里面的User模型
# Create your models here.
class Classes(models.Model):
name = models.CharField(max_length=30, verbose_name='班级名')
slogan = models.TextField(verbose_name='口号', null=True, blank=True)
create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
is_delete = models.BooleanField(default=False, verbose_name='逻辑删除')
number = models.ManyToManyField(User)
class Meta:
db_table = 'classes'
verbose_name = '班级' # 后台显示的名字
verbose_name_plural = verbose_name
def delete(self, using=None, keep_parents=False):
self.is_delete = True
self.save()
3.写序列化器
from rest_framework.serializers import ModelSerializer
from .models import Classes
class ClassesSerializer(ModelSerializer):
class Meta:
model = Classes # 指定model映射的模型类
exclude = ['id', 'is_delete']
4.写视图
from rest_framework.viewsets import ModelViewSet
from .models import Classes
from .serializers import ClassesSerializer
class ClassesViewSet(ModelViewSet):
queryset = Classes.objects.filter(is_delete=False) # 查询集
serializer_class = ClassesSerializer
5.配置路由
from rest_framework.routers import DefaultRouter
from .views import ClassesViewSet
urlpatterns = [
]
router = DefaultRouter() # 创建路由器
router.register('classes', ClassesViewSet) # 注册路由
urlpatterns += router.urls # 拼接路由
6.访问
7.添加数据
优化1
from rest_framework.serializers import ModelSerializer
from django.contrib.auth.models import User
class UserSerializer(ModelSerializer):
class Meta:
model = User
exclude = ['id', 'password']
优化2
from rest_framework.serializers import ModelSerializer
from .models import Classes
from users.serializers import UserSerializer
from rest_framework.fields import SerializerMethodField
class ClassesSerializer(ModelSerializer):
# number = UserSerializer(many=True) # 序列化的嵌套
# 我们的班级在做序列化的时候,它会执行get_number的方法,同时将要序列化的实例对象(Classes),作为参数传递进去
number = SerializerMethodField()
class Meta:
model = Classes # 指定model映射的模型类
exclude = ['id', 'is_delete']
def get_number(self, classes): # 得到班级查询出来的实例化模型对象,将返回的数据赋予number
serializer = UserSerializer(classes.number.all(), many=True) # 拿到班级的所有数据
data = {
'teacher': [i for i in serializer.data if i['is_staff'] or 1 in i['groups']],
'student': [i for i in serializer.data if 2 in i['groups']]
}
return data # 返回的数据会赋值给number
优化3
优化4
1. 配置
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication', # 全局认证方式为JWT认证方式
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
),
}
from rest_framework.viewsets import ModelViewSet
from .models import Classes
from .serializers import ClassesSerializer
from rest_framework.permissions import IsAuthenticated
class ClassesViewSet(ModelViewSet):
# 局部权限设置
permission_classes = [IsAuthenticated] # 登录才有权限
queryset = Classes.objects.filter(is_delete=False) # 查询集
serializer_class = ClassesSerializer
2.测试(postman工具)
说明:这里拿另一个账户登录的令牌也是可以访问的,因此存在安全隐患,需要自制令牌权限
3.自定义权限
from django.contrib.auth.models import Group
from rest_framework.permissions import BasePermission
class MyPermission(BasePermission): # 自定义权限认证类
def has_permission(self, request, view): # 重写权限认证方法
user = request.user
# 获取有权限的分组,老师
group = Group.objects.filter(name='老师').first()
# 获取令牌用户所属的分组
groups = user.groups.all()
return user.is_superuser or group in groups
配置权限
4.优化(返回token同时返回用户名)
1.配置
def jwt_token(token, user=None, request=None):
"""自定义登录成功返回数据处理"""
data = {
'token': token,
'username': user.username,
}
return data
'JWT_RESPONSE_PAYLOAD_HANDLER': 'users.utils.jwt_token',