django rest_framework

1、创建django项目及app

django-admin.py startproject drf_project

cd drf_project

python manage.py startapp drf_app

2、安装rest_framework

pip install djangorestframework

3、将新建的drf_app和rest_framework添加到stting.py中的INSTALLED_APPS

# setting.py

INSTALLED_APPS =(
    ...
    'rest_framework',
    'drf_app',
)

4、创建model

# drf_app/models.py

from django.db import models
from django.utils.translation import gettext_lazy as _
from django.contrib.auth import get_user_model
# from django.contrib.auth.models import User

User = get_user_model()

STATUS_CHOICES = {
    ('1', _('上架')),
    ('2', _('下架')),
}


class TestTable(models.Model):
    id = models.BigIntegerField(verbose_name=_('Id'), db_index=True, primary_key=True)
    name = models.CharField(verbose_name=_('Name'), max_length=100)
    author = models.ForeignKey(User, verbose_name=_('Author'), on_delete=models.CASCADE, related_name='Articles')
    content = models.TextField(verbose_name=_('Content'), blank=True)
    status = models.IntegerField(verbose_name=_('Status'), max_length=10, choices=STATUS_CHOICES)
    create_date = models.DateTimeField(verbose_name=_('Create Date'), auto_now_add=True)

    def __str__(self):
        return self.name

5、迁移创建数据库

python manage.py makemigrations
python manage.py migrate

6、启动django,查看是否正常

python manage.py runserver 127.0.0.1:8000

7、自定义序列化器(serializers)

# 新建一个文件 drf_app/serializers.py
from rest_framework import serializers


class TestApiDeserialization(serializers.Serializer):
    id = serializers.IntegerField(label='id', required=True)
    name = serializers.CharField(label='name', max_length=20, required=True)


class TestApiSerializer(serializers.Serializer):
    id = serializers.IntegerField(label='id', read_only=True, allow_null=False)
    name = serializers.CharField(label='name', max_length=100, allow_null=False)
    author = serializers.CharField(label='name', max_length=20, allow_null=False)
    create_date = serializers.DateTimeField()

8、编写API视图(views.py)

# drf_app/views.py
from rest_framework.views import APIView
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from drf_appimport serializers
from drf_appimport models


class TestAPIView(APIView):
    @api_view(['POST'])
    def get_test_tb(request):
        try:
            serializer = serializers.TestApiDeserialization(data=request.data)

            if not serializer.is_valid():
                print("xxxx")
                return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
            # 处理验证后的数据
            validated_data = serializer.validated_data
            _id = validated_data['id']
            query_data = models.TestTable.objects.filter(id=_id).first()

            data_dict = {"id": query_data.id,
                         "name": query_data.name,
                         "author": query_data.author,
                         "create_date": query_data.create_date,
                         }
            print(data_dict)
            return Response(serializers.TestApiSerializer(data_dict).data, status=status.HTTP_200_OK)
        except Exception as e:
            raise e

9、创建url

# 与setting.py 同目录下的 url.py
from django.contrib import admin
from django.urls import path
from drf_api.views import TestAPIView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('test_api/get_test_tb', TestAPIView.get_test_tb)
]

10、重新迁移数据库并启动服务

python manage.py makemigrations
python manage.py migrate
# 可以手动去数据库表中插入一些数据,再去开启服务
python manage.py runserver 127.0.0.1:8000

11、访问url:http://127.0.0.1:8000/

django
django

12、使用postman请求url: http://127.0.0.1:8000/test_api/get_test_tb
postman

success!!!

posted @ 2024-08-15 15:38  二月雪  阅读(6)  评论(0编辑  收藏  举报