用户信息
个人信息展示
新增邮箱是否激活字段
models中增加字段
class User(AbstractUser):
mobile = models.CharField(max_length=11, unique=True, verbose_name='手机号')
email_is_active = models.BooleanField(default=False, verbose_name='邮箱验证状态') # 增加
class Meta:
db_table = 'user_users'
verbose_name = '用户'
verbose_name_plural = verbose_name
数据库迁移
python manage.py makemigrations
python manage.py migrate
修改邮箱
view.py
class UserEmailView(UpdateAPIView):
"""用户邮箱"""
serializer_class = UserEmailSerializer
permission_classes = [IsAuthenticated]
def get_object(self):
"""重写方法返回 要展示的用户模型对象"""
return self.request.user
serializer.py
# 导包
from celery_tasks.email.tasks import send_verify_email
class UserEmailSerializer(serializers.ModelSerializer):
"""邮箱序列化器"""
class Meta:
model = User
fields = ('id', 'email')
extra_kwargs = {
'email': {
'required': True,
}
}
def update(self, instance, validated_data):
"""重写此方法不是为了更新邮箱,而是为了发送邮箱验证链接"""
# 此处的instance代表的是用户模型
instance.email = validated_data.get('email')
instance.save()
# verify_url = '/success_verify_email.html?token='
verify_url = instance.generate_email_verify_url()
# 发送激活邮箱邮件
send_verify_email.delay(instance.email, verify_url)
return instance
model.py 生成邮箱验证链接方法
使用itsdangerous库做加密和解密,官网链接:https://itsdangerous.palletsprojects.com/en/2.2.x/
# 导包
from itsdangerous import URLSafeTimedSerializer as TimedSerializer, SignatureExpired, BadSignature
class User(AbstractUser):
...
def generate_email_verify_url(self):
"""生成邮箱验证链接"""
# 1.创建加密序列化器
serializer = TimedSerializer(settings.SECRET_KEY)
# 2.调用dumps方法进行加密, bytes
data = {'user_id': self.id, 'email': self.email}
token = serializer.dumps(data)
# 3.拼接验证链接
return settings.FRONT_END_URL + '/success_verify_email.html?token=' + token
urls.py
urlpatterns = [
...
# 修改用户邮箱
path('email/', views.UserEmailView.as_view()),
...
]
celery 发送邮箱任务
在celery_tasks路径下创建email python包,email路径下再创建tasks.py
from celery_tasks.main import celery_app
from django.core.mail import send_mail
from django.conf import settings
"""
bind=True: 允许函数访问self参数,即任务实例本身,这对调用重试方法很有用。
autoretry_for=(Exception,):当任务因为指定的异常(这里是任何Exception)失败时,自动重试。
retry_backoff=60:重试间隔的时间,这里设置为60秒。这意味着第一次重试等待60秒,如果还设置了retry_backoff参数并且大于1,则下一次重试将等待更长。
max_retries=3:最大重试次数,这里设置为3次。
"""
@celery_app.task(bind=True, name='send_verify_email', autoretry_for=(Exception,), retry_backoff=60, max_retries=3,
retry_kwargs={'max_retries': 3})
def send_verify_email(self, user_email, verify_url):
try:
subject = '美多商城邮箱验证'
email_from = settings.EMAIL_FROM
recipient = [user_email, ]
html_message = '<p>尊敬的用户您好!</p>' \
'<p>感谢您使用美多商城。</p>' \
'<p>您的邮箱为:%s 。请点击此链接激活您的邮箱:</p>' \
'<p><a href="%s">%s<a></p>' % (user_email, verify_url, verify_url)
# 调用send_mail函数发送邮件
send_mail(subject, '', email_from, recipient, html_message=html_message)
except Exception as exc:
# 显式抛出异常,告诉Celery任务失败了
raise self.retry(exc=exc)
celery main.py 文件中 自动注册异步任务增加 celery_tasks.email,导入django的settings
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'meiduo_mall.settings.dev')
# 3.自动注册异步任务
celery_app.autodiscover_tasks(['celery_tasks.sms', 'celery_tasks.email',])
注意:启动celery服务时使用gevent执行池,否则默认项不支持windows系统,会导致任务无法执行。
激活邮箱
model.py
class User(AbstractUser):
...
# 不使用self,用@staticmethod修饰为静态方法,通过User.check_email_verify_token(token)的方式调用
@staticmethod
def check_email_verify_token(token):
"""对token进行解密并查询对应user"""
# 1.创建加密序列化器
serializer = TimedSerializer(settings.SECRET_KEY)
# 2.调用loads方法进行解密
try:
# 尝试解析token,有最大有效期限制
data = serializer.loads(token, max_age=3600)
except SignatureExpired:
# 验证链接已过期
return {'data': None, 'message': '验证链接已过期'}
except BadSignature:
# 验证链接无效
return {'data': None, 'message': '验证链接无效'}
else:
# 验证链接有效, 获取user_id和email
user_id = data.get('user_id')
email = data.get('email')
try:
# 查询user
user = User.objects.get(id=user_id, email=email)
except User.DoesNotExist:
return {'data': None, 'message': '用户不存在'}
return {'data': user, 'message': 'ok'}
view.py
class UserEmailVerifyView(APIView):
"""邮箱验证"""
def get(self, request):
# 获取参数
token = request.query_params.get('token')
# 把token解密,并查询对应user
result = User.check_email_verify_token(token)
user = result['data']
if user is None:
# 验证失败
return Response(result, status=status.HTTP_400_BAD_REQUEST)
user.email_is_active = True
user.save()
return Response({'data': True, 'message': 'OK'})
urls.py
urlpatterns = [
...
# 激活邮箱
path('success_verify_email/', views.UserEmailVerifyView.as_view()),
]
收货地址
省市区数据
思路:
- 创建收货地址app
# 进入apps目录
python ../../manage.py startapp areas
创建模型,迁移,导入数据
编写类视图,请求参数parent有值查其下所有子级,无值查一级所有。
编写序列化器,id和name
添加路由
redis缓存数据,减少mysql操作 drf-extensions
创建模型和准备数据
models.py
from django.db import models
# Create your models here.
class Area(models.Model):
name = models.CharField(max_length=20, verbose_name='名称')
parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.SET_NULL, verbose_name='上级行政区划')
class Meta:
db_table = 'areas'
verbose_name = '行政区划'
verbose_name_plural = verbose_name
def __str__(self):
return self.name
注册应用
settings INSTALLED_APPS 添加
INSTALLED_APPS = [
...
'areas.apps.AreasConfig', # 省市区
]
迁移
python manage.py makemigrations
python manage.py migrate
导入数据
本次使用pycharm运行sql导入的,记得去研究下通过sql文件导入。
类视图
views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Area
from .serializer import AreaSerializer
class AreaListView(APIView):
def get(self, request):
# 获取GET请求中的`parent_id`参数
parent_id = request.query_params.get('parent')
# 如果`parent_id`被传递, 则筛选所有parent_id对应的Location
# 否则,筛选所有顶级Location(即parent为None)
if parent_id in ['', 'null', 'undefined', 'None']:
locations = Area.objects.filter(parent_id=None)
else:
locations = Area.objects.filter(parent_id=parent_id)
# 序列化数据
serializer = AreaSerializer(locations, many=True)
# 返回响应
return Response({'message': '查询成功', 'data': serializer.data})
# 继承ListAPIView写法,跟上面的选一种即可
class AreaListView(ListAPIView):
def get_queryset(self):
parent_id = self.request.query_params.get('parent')
if parent_id in ['', 'null', 'undefined', 'None']:
return Area.objects.filter(parent_id=None)
else:
return Area.objects.filter(parent_id=parent_id)
serializer_class = AreaListSerializer
# 再次简化
class AreaListView(ListAPIView):
def get_queryset(self):
parent_id = self.request.query_params.get('parent') or None
return Area.objects.filter(parent_id=parent_id)
serializer_class = AreaListSerializer
序列化器
serializer.py
from rest_framework import serializers
from .models import Area
class AreaSerializer(serializers.ModelSerializer):
class Meta:
model = Area
fields = ('id', 'name')
路由
urls.py
from django.urls import path
from .views import AreasDetail
urlpatterns = [
path('areas/', AreaListView.as_view(), name='areas'),
]
缓存
安装 drf-extensions
在视图类中修饰get方法
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework_extensions.cache.decorators import cache_response # 导包
from .models import Area
from .serializer import AreaSerializer
class AreasDetail(APIView):
@cache_response(timeout=3600, cache='default') # 修饰get方法,若不写time和cache,则需要在settings中进行默认配置
def get(self, request):
parent_id = request.query_params.get('parent')
if parent_id in ['', 'null', 'undefined', 'None']:
locations = Area.objects.filter(parent_id=None)
else:
locations = Area.objects.filter(parent_id=parent_id)
serializer = AreaSerializer(locations, many=True)
return Response({'message': '查询成功', 'data': serializer.data})
settings中配置
# DRF 扩展配置省市区数据缓存
REST_FRAMEWORK_EXTENSIONS = {
'DEFAULT_CACHE_RESPONSE_TIMEOUT': 60 * 60, # 缓存时间
'DEFAULT_USE_CACHE': 'default', # 指定缓存存储使用的名称
}
以上为简单实现需求,下面是课程中给的代码。
课程中代码方式
利用两个序列化器,返回{'id':130000, 'name':'河北省', 'children':[{'id':130100, 'name':'石家庄市'}, ...]}这种格式的数据。
第一种方法:
list序列化器查询集合,details序列化器查询pk的详情。
省视图类get一级集合,详情视图类get 单一市或区详情及其子级集合。
添加两个路由,获取省和获取市或区。
serializer.py
from rest_framework import serializers
from .models import Area
class AreaListSerializer(serializers.ModelSerializer):
class Meta:
model = Area
fields = ('id', 'name')
class AreaDetailSerializer(serializers.ModelSerializer):
class Meta:
model = Area
fields = ('id', 'name', 'children')
children = AreaListSerializer(many=True)
views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Area
from .serializer import AreaListSerializer, AreaDetailSerializer
class AreasList(APIView):
def get(self, request):
qs = Area.objects.filter(parent_id=None)
# 序列化数据
serializer = AreaListSerializer(qs, many=True)
# 返回响应
return Response({'message': '查询成功', 'data': serializer.data})
class AreasDetail(APIView):
def get(self, request, pk):
try:
area = Area.objects.get(id=pk)
except Area.DoesNotExist:
return Response({'message': '无效的PK'}, status=status.HTTP_400_BAD_REQUEST)
# 序列化数据
serializer = AreaDetailSerializer(area)
# 返回响应
return Response({'message': '查询成功', **serializer.data)
urls.py
from django.urls import path
from .views import AreasList, AreasDetail
urlpatterns = [
path('areas/', AreasList.as_view()),
path('areas/<int:pk>/', AreasDetail.as_view()),
]
第二种方法:
views.py
from rest_framework.generics import ListAPIView, RetrieveAPIView
from .models import Area
from .serializer import AreaListSerializer, AreaDetailSerializer
class AreasList(ListAPIView):
queryset = Area.objects.filter(parent_id=None)
serializer_class = AreaListSerializer
class AreasDetail(RetrieveAPIView):
queryset = Area.objects.all()
serializer_class = AreaDetailSerializer
第三种方法:
views.py
from rest_framework.viewsets import ReadOnlyModelViewSet
from .models import Area
from .serializer import AreaListSerializer, AreaDetailSerializer
class AreaViewSet(ReadOnlyModelViewSet):
def get_queryset(self):
if self.action == 'list':
return Area.objects.filter(parent_id=None)
else:
return Area.objects.all()
def get_serializer_class(self):
if self.action == 'list':
return AreaListSerializer
else:
return AreaDetailSerializer
urls.py
from rest_framework.routers import DefaultRouter
from . import views
urlpatterns = []
router = DefaultRouter()
router.register('areas', views.AreaViewSet, basename='areas') # 注册视图集。如果不指定basename,DRF会尝试使用默认命名规则。默认情况下,如果ViewSet有 queryset 属性,它会使用该属性的model名来构造basename。如果没有queryset属性,那么必须手动设置basename参数,因为DRF没有足够的信息来生成URL name。
urlpatterns += router.urls # 列表合并
缓存数据
利用继承的方式
from rest_framework.viewsets import ReadOnlyModelViewSet
# 导包
from rest_framework_extensions.cache.mixins import CacheResponseMixin
from .models import Area
from .serializer import AreaListSerializer, AreaDetailSerializer
class AreaViewSet(CacheResponseMixin, ReadOnlyModelViewSet):
def get_queryset(self):
if self.action == 'list':
return Area.objects.filter(parent_id=None)
else:
return Area.objects.all()
def get_serializer_class(self):
if self.action == 'list':
return AreaListSerializer
else:
return AreaDetailSerializer
用户收货地址
如果增删改查(包括单一和全部),使用视图集代码简单方便。
通过视图集的方式:
实现查询用户所有收货地址,并将默认地址排在第一位。
添加和修改用户收货地址,若当前操作地址设置为默认地址,则取消原来的默认地址。
删除收货地址,软删除的方式实现。
查询单一收货地址详情。(视图集自带,课程中为了不用这个接口重写了视图集)。
模型
users/models.py 因为是用户的收货地址,所以放到了用户应用下。
#增加导包,BaseModel默认加上创建时间和更新时间
from meiduo_mall.utils.models import BaseModel
class Address(BaseModel):
"""收货地址模型"""
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='addresses', verbose_name='用户')
receiver = models.CharField(max_length=20, verbose_name='收件人')
province = models.ForeignKey('areas.Area', on_delete=models.PROTECT, related_name='province_address', verbose_name='省')
city = models.ForeignKey('areas.Area', on_delete=models.PROTECT, related_name='city_address', verbose_name='市')
district = models.ForeignKey('areas.Area', on_delete=models.PROTECT, related_name='district_address', verbose_name='区')
detail_address = models.CharField(max_length=200, verbose_name='详细地址')
mobile = models.CharField(max_length=11, verbose_name='手机')
tel = models.CharField(max_length=20, null=True, blank=True, default='', verbose_name='固定电话')
email = models.CharField(max_length=30, null=True, blank=True, verbose_name='电子邮箱')
is_deleted = models.BooleanField(default=False, verbose_name='逻辑删除')
is_default = models.BooleanField(default=False, verbose_name='是否默认')
class Meta:
db_table = 'user_address'
verbose_name = '收货地址'
verbose_name_plural = verbose_name
ordering = ['-update_time'] # 默认排序
def save(self, *args, **kwargs):
"""重写save方法,保存时若设置是默认地址,则将原默认地址取消"""
if self.is_default:
self.user.addresses.filter(is_default=True).update(is_default=False)
super(Address, self).save(*args, **kwargs)
视图
users/views.py 使用 ModelViewSet简化代码,ModelViewSet同时继承了mixins.CreateModelMixin
、mixins.RetrieveModelMixin
、mixins.UpdateModelMixin
、mixins.DestroyModelMixin
、mixins.ListModelMixin
、GenericViewSet
#增加导包
from rest_framework.viewsets import ModelViewSet
...
class UserAddressView(ModelViewSet):
"""用户收货地址增删改查"""
serializer_class = UserAddressSerializer
permission_classes = [IsAuthenticated]
def get_queryset(self):
return self.request.user.addresses.filter(is_deleted=False).order_by('-is_default', '-update_time') # 排序默认地址在
def create(self, request, *args, **kwargs):
"""重写创建方法,验证用户收货地址不能超过20"""
count = self.get_queryset().count()
if count >= 20:
return Response({'message': '收货地址数量不能超过20'}, status=status.HTTP_400_BAD_REQUEST)
# 获取参数
request.data['user'] = self.request.user.id
# 创建数据
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
def destroy(self, request, *args, **kwargs):
"""重写删除方法,实现软删除"""
instance = self.get_object()
instance.is_deleted = True
instance.save()
return Response(status=status.HTTP_204_NO_CONTENT)
序列化器
users/serializer.py exclude排除不进行序列化的字段,不与fields同用,同用则以fields为准。
class UserAddressSerializer(serializers.ModelSerializer):
"""用户地址序列化器"""
province = serializers.StringRelatedField(read_only=True)
city = serializers.StringRelatedField(read_only=True)
district = serializers.StringRelatedField(read_only=True)
province_id = serializers.IntegerField(label='省ID', required=True)
city_id = serializers.IntegerField(label='市ID', required=True)
district_id = serializers.IntegerField(label='区ID', required=True)
# user_id = serializers.IntegerField(label='用户ID', required=True)
class Meta:
model = Address
exclude = ('is_deleted',)
read_only_fields = ('id', 'create_time', 'update_time')
路由
users/urls.py
# 增加导包
from rest_framework.routers import DefaultRouter
...
router = DefaultRouter()
router.register('address', views.UserAddressView, basename='address')
urlpatterns += router.urls
课程中代码方式
只写需要的接口,类视图继承GenericViewSet
自己写增删改查的方法,其实修改继承的UpdateModelMixin
还是会生成两个接口,修改和部分更新,总的来说还是直接继承ModelViewSet
类更方便。
models.py
class Address(BaseModel):
"""收货地址模型"""
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='addresses', verbose_name='用户')
receiver = models.CharField(max_length=20, verbose_name='收件人')
province = models.ForeignKey('areas.Area', on_delete=models.PROTECT, related_name='province_address', verbose_name='省')
city = models.ForeignKey('areas.Area', on_delete=models.PROTECT, related_name='city_address', verbose_name='市')
district = models.ForeignKey('areas.Area', on_delete=models.PROTECT, related_name='district_address', verbose_name='区')
detail_address = models.CharField(max_length=200, verbose_name='详细地址')
mobile = models.CharField(max_length=11, verbose_name='手机')
tel = models.CharField(max_length=20, null=True, blank=True, default='', verbose_name='固定电话')
email = models.CharField(max_length=30, null=True, blank=True, verbose_name='电子邮箱')
is_deleted = models.BooleanField(default=False, verbose_name='逻辑删除')
is_default = models.BooleanField(default=False, verbose_name='是否默认')
title = models.CharField(max_length=20, verbose_name='地址名称')
class Meta:
db_table = 'user_address'
verbose_name = '收货地址'
verbose_name_plural = verbose_name
ordering = ['-update_time']</pre>
serializer.py
<pre class="md-fences md-end-block ty-contain-cm modeLoaded" spellcheck="false" lang="python" cid="n619" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">class UserAddressSerializer(serializers.ModelSerializer):
"""用户地址序列化器"""
province = serializers.StringRelatedField(label='省名称', read_only=True)
city = serializers.StringRelatedField(label='市名称', read_only=True)
district = serializers.StringRelatedField(label='区名称', read_only=True)
province_id = serializers.IntegerField(label='省ID', required=True)
city_id = serializers.IntegerField(label='市ID', required=True)
district_id = serializers.IntegerField(label='区ID', required=True)
class Meta:
model = Address
exclude = ('is_deleted', 'user',)
read_only_fields = ('id', 'create_time', 'update_time')
def validate_mobile(self, value):
"""验证手机号格式"""
if not re.match(r'^1[3-9]\d{9}', value):
raise serializers.ValidationError('手机号格式错误')
return value
class AddressTitleSerializer(serializers.ModelSerializer):
"""用户地址标题"""
class Meta:
model = Address
fields = ('title',)
view.py
@extend_schema(tags=['用户收货地址'])
class UserAddressView(GenericViewSet, UpdateModelMixin):
"""用户收货地址增删改查"""
serializer_class = UserAddressSerializer
permission_classes = [IsAuthenticated]
def get_queryset(self):
return self.request.user.addresses.filter(is_deleted=False).order_by('-is_default', '-update_time')
def create(self, request, *args, **kwargs):
"""重写创建方法,验证用户收货地址不能超过20"""
count = self.get_queryset().count()
if count >= 20:
return Response({'message': '收货地址数量不能超过20'}, status=status.HTTP_400_BAD_REQUEST)
# 获取参数
request.data['user'] = self.request.user.id
# 创建数据
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
def list(self, request, *args, **kwargs):
"""展示用户收货地址"""
# 获取参数
queryset = self.get_queryset()
# 序列化
serializer = self.get_serializer(queryset, many=True)
return Response({
'user_id': self.request.user.id,
'default_address_id': self.request.user.default_address_id,
'limit': 20,
'addresses': serializer.data
})
def destroy(self, request, *args, **kwargs):
"""重写删除方法,实现软删除"""
address = self.get_object()
address.is_deleted = True
address.save()
return Response(status=status.HTTP_204_NO_CONTENT)
@extend_schema(summary='设置默认地址')
@action(methods=['put'], detail=True)
def default_address(self, request, *args, **kwargs):
"""设置默认地址"""
# 获取参数
address = self.get_object()
# 查询对应地址
request.user.default_address = address
request.user.save()
return Response(status=status.HTTP_200_OK)
@extend_schema(summary='修改地址标题')
@action(methods=['put'], detail=True)
def title(self, request, *args, **kwargs):
"""修改地址标题"""
# 获取参数
address = self.get_object()
# 设置标题
serializer = AddressTitleSerializer(instance=address, data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK)