安装
pip3 install djangorestframework
使用
-
注册app
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework' ]
-
写路由
from django.conf.urls import url from django.contrib import admin from api import views urlpatterns = [ url(r'^drf/info/', views.DrfInfoView.as_view()), ]
-
写视图
from rest_framework.views import APIView from rest_framework.response import Response class DrfInfoView(APIView): def get(self,request,*args,**kwargs): data = [ {'id': 1, 'title': '震惊了...王阳居然...', 'content': '...'}, {'id': 2, 'title': '震惊了...王阳居然...', 'content': '...'}, {'id': 3, 'title': '震惊了...王阳居然...', 'content': '...'}, {'id': 4, 'title': '震惊了...王阳居然...', 'content': '...'}, ] return Response(data)
DRF的应用场景
以后在公司参与前后端分离项目、参与为app写接口时,用drf会比较方便。
CBV到视图函数源码分析
1.首先注册,写好url,视图
首先下载并安装好djangorestframework
pip3 install djangorestframework
在settings中注册
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework'
]
写路由
from django.conf.urls import url
from django.contrib import admin
from api import views
urlpatterns = [
url(r'^drf/info/', views.DrfInfoView.as_view()),
]
写视图
from rest_framework.views import APIView
from rest_framework.response import Response
class DrfInfoView(APIView):
def get(self,request,*args,**kwargs):
data = [
{'id': 1, 'title': '震惊了...王阳居然...', 'content': '...'},
{'id': 2, 'title': '震惊了...王阳居然...', 'content': '...'},
{'id': 3, 'title': '震惊了...王阳居然...', 'content': '...'},
{'id': 4, 'title': '震惊了...王阳居然...', 'content': '...'},
]
return Response(data)
2.CBV到视图函数源码分析
- 第一步
urlpatterns = [
url(r'^drf/info/', views.DrfInfoView.as_view()),
]
请求进来首先执行as_view()
- 第二步
然后执行父类的as_view()方法,并赋值给view
- 第三步
执行self.dispatch方法,首先取本类DrfInfoView中找,如果没有就找父类APIView中找