【007】- Django Rest API简介

本篇接上篇内容,我们学习Django视图。学习之前,我们首先声明,我们主要以目前比较流行的前后端分离思想为主。本篇只是进行一个演示,后续我们将会介绍专门的Rest API方式—Rest Framework。

在前面我们在models.py中定义了两个模型类,分别为User和Role

class User(models.Model):
    """ 用户模型类 """
    SEX_CHOICE = [
        (True, "male"),
        (False, "female"),
    ]

    # 用户ID
    id = models.CharField(max_length=30, primary_key=True, db_column="id")
    # 用户名
    name = models.CharField(max_length=30, unique=True)
    # 密码
    password = models.CharField(max_length=200)
    # 年龄
    age = models.IntegerField()
    # 性别
    sex = models.BooleanField(default=True, choices=SEX_CHOICE)
    # 创建时间
    create_time = models.DateTimeField(auto_now_add=True)
    # 更新时间
    update_time = models.DateTimeField(auto_now=True)
    # 备注
    remark = models.CharField(max_length=200, null=True)
    # 在此我们假设一个用户只能有一个角色,但一个角色可以对应多个用户
    user_role = models.ForeignKey("Role", on_delete=models.CASCADE)

    def __str__(self):
        return "id=" + self.id + ",name=" + self.name + ",age=" + str(self.age) + ",remark=" + self.remark

我们基于User在beardata_sys/views.py中定义如下方法

from beardata_sys.models import User, Role
from django.views.decorators.http import require_http_methods
from django.http import JsonResponse
from django.core import serializers
import json


@require_http_methods(["POST"])
def add_user(request):
    """添加用户"""
    response = {}
    try:
        user_dict = json.loads(str(request.body, encoding="utf8"))
        user = User(id=user_dict["id"],
                    name=user_dict["name"],
                    password=user_dict["password"],
                    age=user_dict["age"],
                    remark=user_dict["remark"],
                    user_role=Role.objects.get(id=user_dict["role_id"]))
        user.save()
        response["msg"] = "success"
        response['error_num'] = 0
    except Exception as e:
        response["msg"] = str(e)
        response['error_num'] = 1
    return JsonResponse(response)


@require_http_methods(["GET"])
def get_user_list(request):
    """获取用列表"""
    response = {}
    try:
        user_list = User.objects.filter()
        response['list'] = json.loads(serializers.serialize("json", user_list))
        response['msg'] = 'success'
        response['error_num'] = 0
    except  Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1
    return JsonResponse(response)

在postman中访问
127.0.0.1:8000/beardata_sys/user/add 添加用户
【007】- Django Rest API简介_第1张图片
访问127.0.0.1:8000/beardata_sys/user/list 获取用户列表
【007】- Django Rest API简介_第2张图片

你可能感兴趣的:(Python,python,django,restful,rest)