Django api web_api rest_framework 简单实例

Django rest_framework 简单实例

官方介绍:

Django REST框架是用于构建Web API的功能强大且灵活的工具包。

您可能要使用REST框架的一些原因:

开始使用

环境需要:djangorestframework,Django
pip install djangorestframework
pip install Django

新建Django项目-本次案例项目名:Students_api

新建App-本次App名:student1

Students_api\settings.py 配置
INSTALLED_APPS = [
    ‘django.contrib.admin‘,
    ‘django.contrib.auth‘,
    ‘django.contrib.contenttypes‘,
    ‘django.contrib.sessions‘,
    ‘django.contrib.messages‘,
    ‘django.contrib.staticfiles‘,
    ‘rest_framework‘,
    ‘student1‘
]
#数据库使用MySQL 请修改成自己的配置使用
DATABASES = {
    ‘default‘: {
        ‘ENGINE‘: ‘django.db.backends.mysql‘,
        ‘ROOT‘:‘127.0.0.1‘,
        ‘PORT‘:3306,
        ‘USER‘:‘root‘,
        ‘PASSWORD‘:‘123‘,
        ‘NAME‘:‘student_api‘,
    }
}
student1\models.py 配置
from django.db import models

# Create your models here.

class Student(models.Model):
    sname = models.CharField(max_length=10)
    sbirth = models.DateField()
    smajor = models.CharField(max_length=20)
    sclass = models.CharField(max_length=20)
    sid = models.CharField(max_length=20)
    score = models.FloatField()
数据库字段:

Django api web_api rest_framework 简单实例

student1\serializer.py
from rest_framework import serializers
from .models import Student

class StudentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = ("sname","sbirth","smajor","sclass","sid","score")
student1\views.py
from django.shortcuts import render
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import generics

from .models import Student
from .serializer import StudentSerializer
# Create your views here.


class StudentView(APIView):
    def get(self,request,format=None):
        sid = request.GET.get(‘sid‘)
        if sid is not None:
            student = Student.objects.filter(pk=sid)
        else:
            student = Student.objects.all()
        serializer = StudentSerializer(student,many=True)
        return Response(serializer.data)
Students_api\urls.py
from django.urls import path,include
from student1 import views
urlpatterns = [
    path(‘‘, views.StudentView.as_view(), name=‘allstudent‘),
]

运行项目截图:

http://127.0.0.1:8000
Django api web_api rest_framework 简单实例

按ID查询

http://127.0.0.1:8000/?sid=1
Django api web_api rest_framework 简单实例

Format=Json

http://127.0.0.1:8000/?format=json&sid=1
Django api web_api rest_framework 简单实例

Django api web_api rest_framework 简单实例

上一篇:使用Windows API 编写按行分配的计算矩阵向量相乘的并行程序


下一篇:C# 创建对象时需要考虑是否实现比较器