参考资料
http://www.yuan316.com/post/DRF/
全站最牛逼的DRF(Django-restframework),没有之一!
零、创建django项目
项目每次处相当于执行命令:django-admin startproject xxx
应用名称处:python manage.py startap
此外创建了虚拟环境、自动安装了django等
安装相应得包
pip install djangorestframework -i https://pypi.douban.com/simple
pip install pymysql -i https://pypi.douban.com/simple
一、CBV与FBV
- FBV(Function-Based Views)基于函数的视图
# views.py
from django.shortcuts import HttpResponse
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def book_views(request):
if request.method == "GET":
return HttpResponse("这是get")
if request.method == "POST":
return HttpResponse("这是post")
if request.method == "DELETE":
return HttpResponse("这是delete")
if request.method == "PUT":
return HttpResponse("这是put")
# urls.py
from django.urls import path
from app001 import views
urlpatterns = [
# fbv
path('book/',views.book_views),
]
- CBV(Class-Based Views)基于类的视图
# views.py
from django.shortcuts import HttpResponse
from django.views import View
from django.utils.decorators import method_decorator
@method_decorator(csrf_exempt, name='dispatch') # 类视图禁止crsf
class BookView(View):
def get(self, request):
return HttpResponse("这是get")
def post(self, request):
return HttpResponse("这是post")
def delete(self, request):
return HttpResponse("这是delete")
def put(self, request):
return HttpResponse("这是put")
# urls.py
from django.urls import path
from app001 import views
urlpatterns = [
# cbv
path('book/',views.BookView.as_view())
]
-
注意
1 urls.py 中使用
book/
访问时需要加上/
,否则会转为get
请求
2 访问get
外的其它请求,需要禁用csrf,cbv与fbv禁用方法是不一样的
二、APIView
在settings.py的INSTALLED_APPS中添加’rest_framework’
#settings.py
INSTALLED_APPS = [
...
'rest_framework',
]
需要将CBV中的class BookView(View)
变为class BookView(APIView)
导入from rest_framework.views import APIView
即可
# views.py
from rest_framework.views import APIView
from django.shortcuts import HttpResponse
class BookView(APIView):
def get(self, request):
return HttpResponse("这是get")
def post(self, request):
return HttpResponse("这是post")
def delete(self, request):
return HttpResponse("这是delete")
def put(self, request):
return HttpResponse("这是put")
urls.py
都不用改变
# urls.py
from django.urls import path
from app001 import views
urlpatterns = [
# cbv
path('book/',views.BookView.as_view())
]