Django 创建api的demo (不使用RESTFramework)

Django 创建api的demo (不使用RESTFramework),第1张

目录

1.新建项目和app:

2.创建模型 *** 作类

3.在settings.py中配置mysql数据库

4.数据库迁移

 5.在stpapi>view.py中编写如下代码:

6.在stuapi.py中新建子路由urls.py,并编写如下代码:

7.在总路由urls.py中编写如下代码:

8.在settings.py中关闭csrf

9.在postman中发送请求:

9.1post请求:

 9.2get请求:

9.3 编辑put和delete请求

9.4查看put和delete请求:


 本文可对比——Django创建api的demo(使用RESTFramework)

1.新建项目和app:

在settings.py中添加标注区域代码

2.创建模型 *** 作类

在stuapi/models.py中添加如下代码:

from django.db import models

# Create your models here.
class Student(models.Model):
    """学生信息"""
    name = models.CharField(max_length=255,verbose_name="姓名")
    sex = models.BooleanField(default=1, verbose_name="性别")
    age = models.IntegerField(verbose_name="年龄")
    classroom = models.CharField(max_length=5, verbose_name="班级编号")
    description = models.TextField(max_length=1000, verbose_name="个性签名")

    class Meta:
        db_table = "tb_student"
        verbose_name = "学生"
        verbose_name_plural = verbose_name
3.在settings.py中配置mysql数据库
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': '数据库名',
        'HOST':'ip地址',
        'POST':3306,
        'USER':'用户名',
        'PASSWORD':'密码',
    }
}

在主应用__init__.py中添加如下代码:

from pymysql import install_as_MySQLdb


install_as_MySQLdb()
4.数据库迁移

 在navcat中查看是否创建成功:

 5.在stpapi>view.py中编写如下代码:
from django.views import View
from django.http.response import JsonResponse
from .models import Student
import json


# Create your views here.
"""
POST /students/ 添加一个学生信息
GET  /students/ 获取所有学生信息

GET  /students// 获取一个学生信息
PUT  /students// 更新一个学生信息
DELETE  /students// 删除一个学生信息

一个路由对应一个视图类,所以我们可以把5个API分成2个类完成
"""
class StudentView(View):
    """学生视图"""
    def post(self,request):
        """添加一个学生信息"""
        # 1.接收客户单提交的数据
        data = json.loads(request.body)
        name = data.get("name")
        sex = data.get("sex")
        age = data.get("age")
        classroom = data.get("classroom")
        description = data.get("description")

        # 2. *** 作数据库,保存数据
        instance = Student.objects.create(
            name = name,
            sex = sex,
            age = age,
            classroom = classroom,
            description = description,
        )

        # 3.返回结果
        return JsonResponse(data={
            "id":instance.pk,
            "name":instance.name,
            "sex":instance.sex,
            "age":instance.age,
            "classroom":instance.classroom,
            "description":instance.description,
        },status=201)

    def get(self,request):
        """获取多个学生数据"""
        # 1.读取数据库
        student_list = list(Student.objects.values())
        # print(student_list)
        # 2.返回数据
        return JsonResponse(
            data=student_list,
            status=200,
            safe=False,
        )
6.在stuapi.py中新建子路由urls.py,并编写如下代码:

from django.urls import path
from . import views

urlpatterns = [
    path("students/", views.StudentView.as_view()),
]
7.在总路由urls.py中编写如下代码:

from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include("stuapi.urls")),
]
8.在settings.py中关闭csrf

别忘了启动服务,python manage.py runserver

9.在postman中发送请求: 9.1post请求:

 返回数据如下所示:

 在navcat中发现也新增一条数据:

 9.2get请求:

9.3 编辑put和delete请求

修改stuapi>views.py

from django.views import View
from django.http.response import JsonResponse
from .models import Student
import json

# Create your views here.
"""
POST /students/ 添加一个学生信息
GET  /students/ 获取所有学生信息

GET  /students// 获取一个学生信息
PUT  /students// 更新一个学生信息
DELETE  /students// 删除一个学生信息

一个路由对应一个视图类,所以我们可以把5个API分成2个类完成
"""
class StudentView(View):
    """学生视图"""
    def post(self,request):
        """添加一个学生信息"""
        # 1.接收客户单提交的数据
        data = json.loads(request.body)
        name = data.get("name")
        sex = data.get("sex")
        age = data.get("age")
        classroom = data.get("classroom")
        description = data.get("description")

        # 2. *** 作数据库,保存数据
        instance = Student.objects.create(
            name = name,
            sex = sex,
            age = age,
            classroom = classroom,
            description = description,
        )

        # 3.返回结果
        return JsonResponse(data={
            "id":instance.pk,
            "name":instance.name,
            "sex":instance.sex,
            "age":instance.age,
            "classroom":instance.classroom,
            "description":instance.description,
        },status=201)

    def get(self,request):
        """获取多个学生数据"""
        # 1.读取数据库
        student_list = list(Student.objects.values())
        # print(student_list)
        # 2.返回数据
        return JsonResponse(
            data=student_list,
            status=200,
            safe=False,
        )

class StudentInfoView(View):
    def get(self, request, pk):
        """获取一条学生信息"""
        try:
            instance = Student.objects.get(pk=pk)
            return JsonResponse(data={
                "id": instance.pk,
                "name": instance.name,
                "sex": instance.sex,
                "age": instance.age,
                "classroom": instance.classroom,
                "description": instance.description,
            },status=200)
        except Student.DoesNoExist:
            return JsonResponse(data={},status=404)

    def put(self,request,pk):
        """更新一个学生信息"""
        # 1.接收提交的数据
        data = json.loads(request.body)
        name = data.get("name")
        sex = data.get("sex")
        age = data.get("age")
        classroom = data.get("classroom")
        description = data.get("description")

        # 2. *** 作数据库,保存数据
        try:
            instance = Student.objects.get(pk=pk)
            # 修改数据
            instance.name = name
            instance.sex = sex
            instance.age = age
            instance.classroom = classroom
            instance.description = description
            instance.save()
        except Student.DoesNoExist:
            return JsonResponse(data=None, status=404)

        # 3.返回结果
        return JsonResponse(data={
            "id": instance.pk,
            "name": instance.name,
            "sex": instance.sex,
            "age": instance.age,
            "classroom": instance.classroom,
            "description": instance.description,
        }, status=201)

    def delete(self,request,pk):
        """删除一个学生信息"""
        try:
            Student.objects.filter(pk=pk).delete()
        except:
            pass
        return JsonResponse(data={}, status=204)

在stuapi>urls.py中修改代码如下:

from django.urls import path,re_path
from . import views

urlpatterns = [
    path("students/", views.StudentView.as_view()),
    re_path("^students/(?P\d+)/$", views.StudentInfoView.as_view()),
]
9.4查看put和delete请求:

查看put请求:

查看delete请求:

 在navcat中查看数据也被清空了:

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/742984.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-28
下一篇 2022-04-28

发表评论

登录后才能评论

评论列表(0条)

保存