Django框架 -- 使用restful设计风格

1)RESTful设计风格的API,每种请求方法,都对应后端一种数据库操作

2)views.py

from django.http import HttpResponse, JsonResponse
from django.views.generic.base import View
from .models import Plan


class PlansAPIView(View):
    def get(self, request):
        queryset = Plan.objects.all()
        plan_list = []
        for plan in queryset:
            plan_list.append({
                'id': plan.id,
                'title': plan.title,
            })
        return JsonResponse(plan_list, safe=False)


class PlanAPIView(View):
    def get(self, request, pk):
        try:
            plan = Plan.objects.get(id=pk)
        except Plan.DoesNotExist:
            return HttpResponse(status=404)

        return JsonResponse({
            'id': plan.id,
            'title': plan.title,
        })

3)urls.py

from django.conf.urls import url
from . import views
from .views import PlansAPIView, PlanAPIView

urlpatterns = [
    url('^index/$', views.PlansAPIView.as_view()),
    url(r'^index/(?P\d+)/$', views.PlanAPIView.as_view())
]

 

你可能感兴趣的:(django框架)