DRF笔记

一、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禁用方法是不一样的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值