1. 程式人生 > WINDOWS開發 >Django api web_api rest_framework 簡單例項

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()
資料庫欄位:

技術分享圖片

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
技術分享圖片

按ID查詢

http://127.0.0.1:8000/?sid=1
技術分享圖片

Format=Json

http://127.0.0.1:8000/?format=json&sid=1
技術分享圖片