Django Rest FrameWork中一些自带的功能的使用
使用token和session
https://blog.csdn.net/weixin_42142216/article/details/91345957
使用信号量
栗子1:加密保存密码
post_save 该信号在保存到数据库之前触发
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from django.contrib.auth import get_user_model
User = get_user_model()
# sender就是一个要操作的Model
@receiver(post_save, sender=User)
def create_user(sender, instance=None, created=False, **kwargs):
# 判断这个操作是不是新建
if created:
password = instance.password
instance.set_password(password)
instance.save()
这里的instance就是将要保存的User对象,由于User继承了abstractUser,所有可以使用set_password用来加密密码
栗子2:使用信号量完成增减收藏数量的操作
post_delete 在每次执行删除操作之前触发
from django.db.models.signals import post_delete, post_save
from django.dispatch import receiver
from user_operation.models import UserFav
@receiver(post_save, sender=UserFav)
def create_userfav(sender, instance=None, created=False, **kwargs):
if created:
goods = instance.goods
goods.fav_num += 1
goods.save()
@receiver(post_delete, sender=UserFav)
def delete_userfav(sender, instance=None, created=False, **kwargs):
goods = instance.goods
goods.fav_num -= 1
goods.save()
class UserOperationConfig(AppConfig):
name = 'user_operation'
def ready(self):
import user_operation.signals
- apps.py注册
from django.apps import AppConfig
class ConsumersConfig(AppConfig):
name = 'consumers'
def ready(self):
import users.signals
获取用户模块
from django.contrib.auth import get_user_model
User = get_user_model()
使用DRF提供的缓冲拓展
GoodsListViewSet中继承CacheResponseMixin
from rest_framework_extensions.cache.mixins import CacheResponseMixin
class GoodsListViewSet(CacheResponseMixin,mixins.ListModelMixin,mixins.RetrieveModelMixin,viewsets.GenericViewSet):
'''
注意,一定要放在第一个位置
配置缓存过期时间
#缓存配置
REST_FRAMEWORK_EXTENSIONS = {
'DEFAULT_CACHE_RESPONSE_TIMEOUT': 10 #5s过期,时间自己可以随便设定
}