Django-rest framework的安装与使用
01-03 Django-rest framework的安装与使用
1.安装与配置
1)安装drf:pip install dajngorestframework
2)项目settings.py注册app:INSTALLED_APPS = [ ......, 'rest_framework']
3)基于CBV完成满足Restful规范的接口
2.如何使用
视图层:
# 视图层 views.py
from rest_framework.views import APIView
from rest_framework.response import Response
# 书籍
class BookAPIView(APIView):
"""书籍"""
# 查看书籍
def get(self, request, *args, **kwargs):
return Response({
'status': 0,
'msg': 'ok',
'results': {
'name': '百年孤独',
'price': 33.60
}
})
# 添加书籍
def post(self, request, *args, **kwargs): pass
# 全局修改书籍
def put(self, request, *args, **kwargs): pass
# 局部修改书籍
def patch(self, requset, *args, **kwargs): pass
# 删除书籍
def delete(self, request, *args, **kwargs): pass
路由层:
# 根路由:drf_vue.urls.py
from django.conf.urls import url, include
urlpatterns = [
# 导入api下的路由
url(r'^api/', include('api.urls', namespace='api'))
]
# app下的路由:api.urls.py
from django.conf.urls import url
from api import views
urlpatterns = [
# 通过以下两个路径,完成所有增删改查操作
url(r'^books/$', views.CarApi.as_view()),
url(r'^books/(?P<pk>\d+)/', views.CarApi.as_view()),
]