Django Rest Framework:无法克服奇怪的错误

时间:2019-07-02 17:21:24

标签: django django-rest-framework

尝试一个简单的请求:

urls.py

from django.conf.urls import url
from django.urls import include, path
from rest_framework import routers
from django.http import HttpResponse
from rest_framework.urlpatterns import format_suffix_patterns
from .public_views import NavigationBar


router = routers.DefaultRouter()
router.register(r'navbar', NavigationBar, basename="NavigationBar")


urlpatterns = [
    path('', include(router.urls))

]

urlpatterns = format_suffix_patterns(urlpatterns)

public_views.py

from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.permissions import AllowAny
from rest_framework.throttling import UserRateThrottle
from rest_framework.decorators import api_view, throttle_classes
from . view_utils import *


class OncePerDayUserThrottle(UserRateThrottle):
    rate = '1/day'


class NavigationBar(APIView):
    """
    obtain up to date navigation bar (or side menu navigation) hierarchy.
    """
    permission_classes = ([AllowAny])

    def get(self, request, format=None):
        """
        get user addresses
        """
        return Response("this is a good response")

    def get_extra_actions(cls):
        return []

当我API调用/v1/navbar/v1/navbar/端点时(我的主要urls.py引导所有/v1/流量流向另一个专用urls.py),我出现以下错误:

AttributeError at /v1/navbar
type object 'NavigationBar' has no attribute 'get_extra_actions'
Request Method: GET
Request URL:    http://web/v1/navbar
Django Version: 2.1
Exception Type: AttributeError
Exception Value:    
type object 'NavigationBar' has no attribute 'get_extra_actions'
Exception Location: /usr/local/lib/python3.6/site-packages/rest_framework/routers.py in get_routes, line 200
Python Executable:  /usr/local/bin/uwsgi
Python Version: 3.6.8
Python Path:    
['.',
 '',
 '/usr/local/lib/python36.zip',
 '/usr/local/lib/python3.6',
 '/usr/local/lib/python3.6/lib-dynload',
 '/usr/local/lib/python3.6/site-packages']
Server time:    Tue, 2 Jul 2019 17:12:27 +0000

任何指针,我将不胜感激。另外,当Request URL: http://web/v1/navbar不是我正在使用的URL的一部分时,我无法理解为什么错误消息中包含web指示。 web来自哪里???我只是用/v1/navbar/击中终点。

1 个答案:

答案 0 :(得分:2)

这里有两个错误。首先,路由器用于视图集,而不是简单视图。其次,对于基于类的视图,您需要通过urlconf中的as_view()方法来调用它。因此,摆脱掉路由器的东西,然后做:

urlpatterns = [
    path(r'navbar', NavigationBar.as_view(), name="NavigationBar")
]

注意,现在您不使用路由器,根本不需要该get_extra_actions方法。