Django 注册及创建订单商品

注册功能的实现

user/views

python 复制代码
from rest_framework.generics import GenericAPIView
from rest_framework.views import APIView

from apps.user.models import User
from apps.user.serializers import UserSerializer
from utils import ResponseMessage
from utils.jwt_auth import create_token
from utils.password_encode import get_md5


# Create your views here.
class UserApiView(APIView):
    # 注册功能的实现
    # def post(self,request):
    #     request.data["password"] = get_md5(request.data.get("password"))
    #     # 反序列化呀,把json变成一个对象  [这是关键的一句话]
    #     user_data_serializer = UserSerializer(data=request.data)
    #     user_data_serializer.is_valid(raise_exception=True)
    #     user_data = User.objects.create(**user_data_serializer.data)
    #
    #     # 序列化一下,把json返回给前端对象
    #     user_ser = UserSerializer(instance=user_data)
    #     return JsonResponse(user_ser.data)
    def post(self,request):
        # 反序列化呀,把json变成一个对象  [这是关键的一句话]
        user_data_serializer = UserSerializer(data=request.data)
        user_data_serializer.is_valid(raise_exception=True)
        user_data = user_data_serializer.save()

        # 序列化一下,把json返回给前端对象
        user_ser = UserSerializer(instance=user_data)
        # return JsonResponse(user_ser.data)
        return ResponseMessage.UserResponse.success(user_ser.data)

user/urls

python 复制代码
from django.urls import path
from .views import UserApiView

urlpatterns = [
    path("",UserApiView.as_view()),
]

user/serializers.py

python 复制代码
import datetime

from rest_framework import serializers
from rest_framework.validators import UniqueValidator

from apps.user.models import User
from utils.password_encode import get_md5


class UserSerializer(serializers.ModelSerializer):
    # email作为用户名进行登录,这里我们需要做一个唯一性的验证
    email = serializers.EmailField(
        required=True,
        allow_blank=False,
        validators=[UniqueValidator(queryset=User.objects, message="用户已经存在了")]
    )
    password = serializers.CharField(write_only=True)
    # password = serializers.CharField()
    birthday = serializers.DateTimeField("%Y-%m-%d %H:%M:%S")
    create_time = serializers.DateTimeField("%Y-%m-%d %H:%M:%S",required=False)
    # create方法会被自动调用,这里可以做一些数据的验证或者是存储之前数据的加工
    def create(self, validated_data):
        print("create方法被调用了")
        print(validated_data)
        validated_data["password"] = get_md5(validated_data["password"])
        validated_data["create_time"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        result = User.objects.create(**validated_data)
        return result

    class Meta:
        model = User
        fields = "__all__"

utils/password_encode.py

python 复制代码
import hashlib
def get_md5(param):
    md5 = hashlib.md5()
    md5.update(param.encode())
    return md5.hexdigest()

urls

python 复制代码
path("user/", include("user.urls")),

用户个人中心获取 用户信息接口开发

python 复制代码
class UserApiView(APIView):
    

    def get(self, request):
        email = request.GET.get("email")
        try:
            user_data = User.objects.get(email=email)
            user_ser = UserSerializer(user_data)
            return ResponseMessage.UserResponse.success(user_ser.data)
        except Exception as e:
            print(e)
            return ResponseMessage.UserResponse.failed("用户信息获取失败")

订单逻辑梳理与表的创建




订单商品表(点击去结算)

订单表(提交订单)

将数据库创建的表映射到本地模型类

python 复制代码
python manage.py inspectdb --database default goods > apps/order/models.py

基于GenericAPIView视图的调用逻辑实现创建订单商品的接口开发

order/views

python 复制代码
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from rest_framework.generics import GenericAPIView
from apps.order.models import OrderGoods
from apps.order.serializers import OrderGoodsSerializer


class OrderGoodsGenericAPIView(GenericAPIView):
    queryset = OrderGoods.objects
    serializer_class = OrderGoodsSerializer

    def post(self, request):
        # trade_no = request.data.get("trade_no")
        # print(self.get_queryset())
        # print(self.get_serializer())
        print(request.data)
        # request.data 类型是 dict   转成object传data
        ser = self.get_serializer(data=request.data)
        ser.is_valid()
        ser.save()
        return JsonResponse("ok",safe=False)

order/urls

python 复制代码
from django.contrib import admin
from django.urls import path
from .views import OrderGoodsGenericAPIView


urlpatterns = [
    path("goods/",OrderGoodsGenericAPIView.as_view()),


]

order/serializers.py

python 复制代码
from rest_framework import serializers
from apps.order.models import OrderGoods


class OrderGoodsSerializer(serializers.ModelSerializer):
    class Meta:
        model = OrderGoods
        fields = "__all__"
python 复制代码
from django.db import models


class Order(models.Model):
    email = models.CharField(max_length=255, blank=True, null=True)
    order_amount = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
    address_id = models.IntegerField(blank=True, null=True)
    pay_status = models.CharField(max_length=155, blank=True, null=True)
    pay_time = models.DateTimeField(blank=True, null=True)
    ali_trade_no = models.CharField(max_length=255, blank=True, null=True)
    is_delete = models.PositiveIntegerField(blank=True, null=True)
    create_time = models.DateTimeField(blank=True, null=True)
    update_time = models.DateTimeField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'order'


class OrderGoods(models.Model):
    trade_no = models.CharField(max_length=255, blank=True, null=True)
    sku_id = models.CharField(max_length=255, blank=True, null=True)
    goods_num = models.IntegerField(blank=True, null=True)
    # create_time = models.DateTimeField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'order_goods'

urls

python 复制代码
path("order/", include("order.urls")),

基于GenericAPIView视图调用逻辑实现获取订单商品接口开发

order/view.py

python 复制代码
class OrderGoodsGenericAPIView(GenericAPIView):
    queryset = OrderGoods.objects
    serializer_class = OrderGoodsSerializer

    def post(self, request):
        print(request.data)
        # request.data 类型是 dict   转成object传data
        ser = self.get_serializer(data=request.data)
        ser.is_valid()
        ser.save()
        return JsonResponse("ok",safe=False)

    lookup_field = "trade_no"
    def get(self, request, trade_no):
        # 这一行代码就实现了数据库里所有数据的查询   self.get_queryset()拿到配置模型表中的所有数据  返回所有数据
        # 调用self.get_serializer 其实就是调用 serializer_class = OrderGoodsSerializer
        # return JsonResponse(self.get_serializer(instance=self.get_queryset(),many=True).data,safe=False)
        print(trade_no)
        # self.get_object() 调用该方法拿到lookup_field作为请求的参数直接传进去 其实就是加了某一个条件 返回一条数据
        ser = self.get_serializer(instance=self.get_object(), many=False)
        # 传many会报错
        # ser = self.get_serializer(instance=self.get_object(),many=True)
        return JsonResponse(ser.data, safe=False)
相关推荐
Python大数据分析@8 分钟前
python操作CSV和excel,如何来做?
开发语言·python·excel
黑叶白树10 分钟前
简单的签到程序 python笔记
笔记·python
Shy96041823 分钟前
Bert完形填空
python·深度学习·bert
上海_彭彭34 分钟前
【提效工具开发】Python功能模块执行和 SQL 执行 需求整理
开发语言·python·sql·测试工具·element
zhongcx011 小时前
使用Python查找大文件的实用脚本
python
Yaml41 小时前
智能化健身房管理:Spring Boot与Vue的创新解决方案
前端·spring boot·后端·mysql·vue·健身房管理
yyfhq2 小时前
sdnet
python
测试19982 小时前
2024软件测试面试热点问题
自动化测试·软件测试·python·测试工具·面试·职场和发展·压力测试