什么是DRF?
简介
Django REST framework (DRF)是基于Django写出符合 RESTful 规范的借口
安装
pip3 install djangorestframework
RESTful规范
简介
REST是Representational State Transfer的简称,中文翻译为“表征状态转移”。REST与技术无关,它是一种软件架构风格,适用于前后端分离的应用模式中
10条规范
- HTTP 加密传输(HTTPS协议=HTTP协议+SSL/TLS )
- 接口特征表示(URL中带有API的关键字标识 eg:
https://api.changchen.cc
) - 多数据版本共存(URL中 ,带接口的版本 eg:
https://api.changchen.cc/v1/books/
) - 数据即资源,使用名词
- 请求方式决定决定操作
- 响应中带状态码
- 响应中带错误信息
- 返回结果中携带资源连接
- 请求路径中带过滤,在URL后带参数(eg:
https://api.changchen.cc/books/?name=金
) - 返回结果符合要求规范
DRF基本使用
setting.py
INSTALLED_APPS = [
...
'rest_framework'
]
models.py
from django.db import models
class Book(models.Model):
name = models.CharField(max_length=32)
price = models.DecimalField(max_digits=8, decimal_places=2)
serialized.py
(新建)
from rest_framework.serializers import ModelSerializer
from app01 import models
class BookSerializers(ModelSerializer):
class Meta:
model = models.Book
fields = "__all__"
views.py
from rest_framework.viewsets import ModelViewSet
from .serializer import BookSerializers
from .models import Book
class BookView(ModelViewSet):
serializer_class = BookSerializers
queryset = Book.objects.all()
url.py
from django.contrib import admin
from django.urls import path
from rest_framework.routers import SimpleRouter
from app01 import views
router = SimpleRouter()
router.register('books', views.BookView,)
urlpatterns = [
path('admin/', admin.site.urls),
]
urlpatterns += router.urls