Django rest_framework 简单实例
官方介绍:
Django REST框架是用于构建Web API的功能强大且灵活的工具包。
您可能要使用REST框架的一些原因:
- 该网站可浏览API是你的开发人员一个巨大的可用性胜利。
- 身份验证策略,包括OAuth1a和OAuth2的软件包。
- 支持ORM和非ORM数据源的序列化。
- 完全可自定义- 如果您不需要更强大的功能,请仅使用基于函数的常规视图。
- 广泛的文档资料以及强大的社区支持。
- 由Mozilla,Red Hat,Heroku和Eventbrite等国际知名公司使用和信任。
开始使用
环境需要: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()
数据库字段:
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‘),
]