Django休息嵌套APIView路线

时间:2017-05-26 07:43:50

标签: python django django-rest-framework

我对Django& amp; Django休息 - 以前只构建非常简单的应用程序。 目前使用嵌套路线时遇到问题。 以下是我的相关配置:

主要urls.py:

urlpatterns = [
    url(r'^'+root_url+'/swagger', swagger_schema_view),
    url(r'^' + root_url + '/', include('payments.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

app的网址:

urlpatterns = [
    url(r'payments', views.PaymentsView.as_view(), name='index'),
    url(r'payments/charge', views.PaymentsChargeView.as_view(), name='charge'),
]

应用的观点

import logging

from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from rest_framework.authentication import BasicAuthentication
from mysite.csrf_exempt import CsrfExemptSessionAuthentication

from rest_framework.views import APIView
from rest_framework.response import Response

import stripe
try:
    from django.conf import settings
except ImportError:
    pass



logger = logging.getLogger(__name__)


@method_decorator(csrf_exempt, name='dispatch')
class PaymentsView(APIView):
    authentication_classes = (CsrfExemptSessionAuthentication, BasicAuthentication)

    def get(self, request, *args, **kwargs):
        print('here GET PaymentsView')
        return Response('good')

    def post(self, request, *args, **kwargs):
        print('here POST PaymentsView')
        return Response('good')


@method_decorator(csrf_exempt, name='dispatch')
class PaymentsChargeView(APIView):
    authentication_classes = (CsrfExemptSessionAuthentication, BasicAuthentication)

    def get(self, request, *args, **kwargs):
        print('here GET PaymentsChargeView')
        return Response('good')

    def post(self, request, *args, **kwargs):
        print('here POST PaymentsChargeView')
        return Response('good post')

问题:

请求/payments/payments/charge GET / POST始终由PaymentsView处理(例如:POST/payments/payments/charge我在这里POST PaymentsView'在控制台中)

3 个答案:

答案 0 :(得分:1)

最佳做法是将$ (end-of-string match character)放入您的网址。因此定义的url将匹配并处理正确的视图函数。

url(r'payments$', views.PaymentsView.as_view(), name='index'),
url(r'payments/charge$', views.PaymentsChargeView.as_view(), name='charge'),

答案 1 :(得分:0)

更改您的网址顺序

urlpatterns = [
    url(r'payments/charge', views.PaymentsChargeView.as_view(), name='charge'),
    url(r'payments', views.PaymentsView.as_view(), name='index'),
]

答案 2 :(得分:0)

urlpatterns = [
    url(r'^payments', views.PaymentsView.as_view(), name='index'),
    url(r'^payments/charge', views.PaymentsChargeView.as_view(), name='charge'),
]