如何反转命名空间:视图:端点格式的 URL?

问题描述 投票:0回答:1

我有一个 Django 项目,在项目级别定义了以下 urlpattern:

urlpatterns = [
    path('', include(('ws_shopify.urls', 'ws_shopify'), namespace='shopify')),
]

文件

ws_shopify.urls
定义了以下urlpatterns:

urlpatterns = [
    path('api/shopify/', ShopifyWebhookAPIView.as_view(), name='webhook'),
]

ShopifyWebhookAPIView
定义了以下端点:

from rest_framework.views import APIView

class ShopifyWebhookAPIView(APIView):
    @action(detail=False, methods=['post'], url_path='(?P<webshop_name>.+)/order_created', name='order-created')
    def order_created(self, request: Request, webshop_name=None):
        return Response({'message': f'Order created for {webshop_name}'})

我的问题是:

在使用

reverse()
的测试用例中使用的此端点的正确名称是什么?

我现在正在尝试:

class WebhookTestCase(TestCase):
    def test_that_url_resolves(self):
        url = reverse('shopify:webhook:order-created', kwargs={'webshop_name': 'my-shop'})
        self.assertEqual(url, '/api/shopify/my-shop/order_created')

但是失败并出现以下错误消息:

django.urls.exceptions.NoReverseMatch: 'webhook' is not a registered namespace inside 'shopify'

不确定它是否相关,这就是

ws_shopify.apps
的样子:

from django.apps import AppConfig

class ShopifyConfig(AppConfig):
    name = 'ws_shopify'
python django django-rest-framework url-pattern
1个回答
0
投票

我让它可以通过以下更改工作:

ws_shopify.urls

from django.urls import path, include
from rest_framework.routers import DefaultRouter

from ws_shopify.views import ShopifyWebhookViewSet

router = DefaultRouter()
router.register(r'', ShopifyWebhookViewSet, basename='webhook')

urlpatterns = [
    path('api/shopify/', include(router.urls)),
]

ws_shopify.views

from rest_framework.viewsets import ViewSet

class ShopifyWebhookViewSet(ViewSet):
    @action(detail=False, methods=['post'], url_path='(?P<webshop_name>.+)/order_created', name='order-created')
    def order_created(self, request: Request, webshop_name=None):
        return Response({'message': f'Order created for {webshop_name}'})

ws_shopify.tests_views

class WebhookTestCase(TestCase):
    def test_that_url_resolves(self):
        url = reverse('shopify:webhook-order-created', kwargs={'webshop_name': 'my-shop'})
        self.assertEqual(url, '/api/shopify/my-shop/order_created/')
© www.soinside.com 2019 - 2024. All rights reserved.