Go教程

基于django原生代码提供api接口

本文主要是介绍基于django原生代码提供api接口,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

创建了表单student:

  

from django.db import models

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

    def __str__(self):
        return self.name
    class Meta:
        # db_table = "tb_student"  # 数据库的表名字
        # verbose_name="学生"
        # verbose_name_plural=verbose_name
        verbose_name_plural="学生"

 

将表单注册到admin里面 ,否则后台不显示:

  

from django.contrib import admin
from . models import Student

admin.site.register(Student)

 

写视图views:(使用时用json格式提交)

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

from django.http import QueryDict


class StudentView(View):
    def post(self,request):
        #接收并验证客户端信息
        data=json.loads(request.body)
        name=data.get("name")
        sex=data.get("sex")
        age=data.get("age")
        classmate=data.get("classmate")
        description=data.get("description")
        #操作数据库,保存数据
        instance=Student.objects.create(
            name=name,
            sex=sex,
            age=age,
            classmate=classmate,
            description=description,
        )
        #返回数据
        return JsonResponse(data={
            "id":instance.pk,
            "name":instance.name,
            "sex":instance.sex,
            "age":instance.age,
            "classmate":instance.classmate,
            "description":instance.description,
        },status=201)

    def get(self,request):
        # 读取数据库
        students_list=list(Student.objects.values()) #value返回列表
        # 返回数据
        return JsonResponse(data=students_list,status=200,safe=False)

class StudentInfoView(View):
    def get(self,request,pk):
        # 获取一条数据
        try:
            instance=Student.objects.filter(pk=pk)
            return JsonResponse(data={
                "id":instance.pk,
                "name":instance.name,
                "sex":instance.sex,
                "age":instance.age,
                "classmate":instance.classmate,
                "description":instance.description,
            },status=200)
        except Student.DoesNotExist:
            return JsonResponse(data=None,status=404)#没有内容
        
    def put(self,request,pk):
        # 更新学生数据
        #接收并验证客户端信息
        data=json.loads(request.body)
        name=data.get("name")
        sex=data.get("sex")
        age=data.get("age")
        classmate=data.get("classmate")
        description=data.get("description")
        #操作数据库,保存数据
        try:
            instance=Student.objects.get(pk=pk)
            instance.name=name
            instance.sex=sex
            instance.age=age
            instance.classmate=classmate
            instance.description=description
            instance.save()

        except Student.DoesNotExist:
            return JsonResponse(data=None,status=404)

        #返回数据
        return JsonResponse(data={
            "id":instance.pk,
            "name":instance.name,
            "sex":instance.sex,
            "age":instance.age,
            "classmate":instance.classmate,
            "description":instance.description,
        },status=201)

    def delete(self,request,pk):
        try:
            Student.objects.filter(pk=pk).delete()
        except:
            pass
        return JsonResponse(data={},status=204)

 

 

 

填写路由urls:

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


# 路由列表
urlpatterns = [
    path("students/",views.StudentView.as_view()),
    re_path("^students/(?P<pk>\d+)/$",views.StudentInfoView.as_view())
    #使用re_path要在前面加上^后面加上$,防止格式和上面冲突

]

 

这篇关于基于django原生代码提供api接口的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!