使用rest框架在django中切换相同URL但不同方法的视图?

时间:2017-09-11 12:56:16

标签: python django django-rest-framework django-views

最多" pythonic"基于方法处理同一网址上的视图路由的方法?我不喜欢这个解决方案

if(request.method == 'GET'):
    .......

有更好的方法吗?

1 个答案:

答案 0 :(得分:2)

Django View是最pythonic的代码。

from django.http import HttpResponse
from rest_framework.views import APIView

class MyView(APIView):
    def get(self, request):
        # <view logic>
        return HttpResponse('result')
    def post(self, request):
        # <view logic x2>
        return HttpResponse('message_post_template')

urls.py

from django.conf.urls import url
from myapp.views import MyView

urlpatterns = [
    url(r'^about/$', MyView.as_view(), name='view'),
]