FBV(function base views) 就是在视图里使用函数处理请求。
CBV(class base views) 就是在视图里使用类处理请求。
视图函数中代码
from django.http import JsonResponse, QueryDict
from django.shortcuts import render
# Create your views here.
from django.views import View
from .models import *
class BookAPI(View):
def get(self, req):
print(req.method)
return JsonResponse({'code': 200, 'msg': 'successful'})
def post(self, req):
params = req.POST
title = params.get('title')
content = params.get('content')
price = params.get('price')
poem = Poem.objects.create(
title=title,
content=content,
price=price,
)
return JsonResponse({'title': poem.title})
def put(self, req):
params = QueryDict(req.body)
id = int(params.get('id'))
title = params.get('title', )
book = Poem.objects.get(pk=id)
book.title = params.get('title', book.title)
book.content = params.get('content', book.content)
book.price = params.get('price', book.price)
book.save()
return JsonResponse({'code': 200, 'title': book.title})
def delete(self, req):
params = QueryDict(req.body)
id = int(params.get('id'))
book = Poem.objects.get(pk=id)
title = book.title
book.delete()
return JsonResponse({'code': 204, 'title': title})
models模型 Poem
class Poem(models.Model):
title = models.CharField(
max_length=20,
null=False,
)
content = models.CharField(
max_length=100,
null=True,
)
price = models.DecimalField(
max_digits=8,
decimal_places=2,
)
urls中代码
from django.conf.urls import url
from .views import *
urlpatterns = [
url(r'^book$',BookAPI.as_view()),
]
然后将urls添加进项目urls中即可
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^myapp/',include('myapp.urls')),
]
注:
class BookAPI(View): View类中as_view()方法会调用类中dispatch方法。dispatch方法会将 浏览器请求根据 method 分配 相应 get post put delete 方法
def dispatch(self, request, *args, **kwargs):
# Try to dispatch to the right method; if a method doesn’t exist,
# defer to the error handler. Also defer to the error handler if the
# request method isn’t on the approved list.
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed
return handler(request, *args, **kwargs)