*** AttributeError:“类名”对象没有属性“ request”

时间:2020-01-06 19:25:19

标签: python django django-rest-framework pagination

我使用的是添加分页的端点,因此在DRF API视图中运行良好,但是当我从Web应用程序调用它时,它会返回*** *** AttributeError: 'SearchViewSet' object has no attribute 'request'

我在下面解释细节。这是我的api.py分页查询集的地方,例如以下answer解释:

class StandardResultsSetPagination(PageNumberPagination):
    page_size = 10

class SearchViewSet(viewsets.ModelViewSet):
    '''
    Class related with the Search Model, that is a tracking model where you
    could find recently search by user.
    ''' 
    queryset = Search.objects.filter(
        is_active=True,
        is_deleted=False
    ).order_by('id')
    permission_classes = [
        permissions.AllowAny
    ]
    pagination_class = StandardResultsSetPagination

    def __init__(self,*args, **kwargs):
        self.response_data = {'error': [], 'data': []}
        self.data = {}      
        self.code = 0       

    def get_serializer_class(self):
        if self.action in ['recent_search']:
            return RecentSearchAPISerializer
        return SearchSerializer

    @validate_type_of_request
    @action(methods=['post'], detail=False)
    def recent_search(self, request, *args, **kwargs):
        '''
        - POST method (recent_search): get user recent search
        - Mandatory: user, social_network_id
        '''
        try:
            serializer = SearchSerializer(
                data=kwargs['data'],
                fields=['social_network','user'])

            if serializer.is_valid():

                queryset = Search.objects.filter(
                    is_active=True,
                    is_deleted=False,
                    social_network=kwargs['data']['social_network'],
                    user_id=kwargs['data']['user']).order_by('id').reverse()
                page = self.paginate_queryset(queryset)

                if page is not None:

                    serializer = SearchSerializer(page, many=True, fields=(
                        'id','word','polarity','liked','shared','searched_date'))
                    self.data['recently_search'] = json.loads(json.dumps(serializer.data))
                    self.code = status.HTTP_200_OK
                    self.response_data['data'].append(self.data)
                    return self.get_paginated_response(serializer.data)                 

                serializer = SearchSerializer(queryset, many=True, fields=(
                    'id','word','polarity','liked','shared','searched_date'))
                self.data['recently_search'] = json.loads(json.dumps(serializer.data))
                self.code = status.HTTP_200_OK
                self.response_data['data'].append(self.data)

            else:
                return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)

        except Exception as e:
            logging.getLogger('error_logger').exception("[API - RecentSearchTwitterView] - Error: " + str(e))
            self.code = status.HTTP_500_INTERNAL_SERVER_ERROR
            self.response_data['error'].append("[API - RecentSearchTwitterView] - Error: " + str(e))
        return Response(self.response_data,status=self.code)

在我的views.py

class RecentSearchTwitterView(View):
    """docstring for RecentSearchTwitterView"""
    def __init__(self,*args, **kwargs):
        self.response_data = {'error': [], 'data': {}}
        self.code = 0

    def get(self, request, *args, **kwargs):
        try:
            _recent_search = SearchViewSet()
            _recent_search.recent_search(request,social_network=1,user=1)
            self.response_data['data'] = _recent_search.response_data['data'][0]
            self.code = _recent_search.code

        except Exception as e:
            logging.getLogger('error_logger').exception("[RecentSearchTwitterView] - Error: " + str(e))
            self.code = status.HTTP_500_INTERNAL_SERVER_ERROR
            self.response_data['error'].append("[RecentSearchTwitterView] - Error: " + str(e))
        return render(request,template_name='web/recent_search_twitter.html',status=self.code,context=self.response_data)

因此,在两种情况下,在api.py中,queryset返回数据,但在下一行:

page = self.paginate_queryset(queryset)

从Web App返回错误,而在DRF Api视图中或由邮递员返回分页的数据。即使我在这一行中通过了request

            _recent_search = SearchViewSet(request)

我收到了同样的错误。我试图调试错误,但找不到解决方案。我发现了这个similar question,但我认为情况有所不同,因为queryset总是正确地返回数据

从Web App请求调试:

(Pdb) queryset
<QuerySet [<Search: food>, <Search: ice cream>, <Search: pollution>, <Search: lapto>, <Search: pollution>, <Search: food>, <Search: dogs>, <Search: war>, <Search: Venezuela>, <Search: rock>, <Search: movies>, <Search: marvel>, <Search: food>]>
(Pdb) self
<api.api.SearchViewSet object at 0x000001A485E29278>
(Pdb) dir(self)             
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_allowed_methods', '_negotiator', 'action', 'action_map', 'allowed_methods', 'args', 'as_view', 'authentication_classes', 'basename', 'check_object_permissions', 'check_permissions', 'check_throttles', 'code', 'content_negotiation_class', 'create', 'data', 'default_response_headers', 'description', 'destroy', 'detail', 'determine_version', 'dispatch', 'filter_backends', 'filter_queryset', 'finalize_response', 'format_kwarg', 'get_authenticate_header', 'get_authenticators', 'get_content_negotiator', 'get_exception_handler', 'get_exception_handler_context', 'get_extra_action_url_map', 'get_extra_actions', 'get_format_suffix', 'get_object', 'get_paginated_response', 'get_parser_context', 'get_parsers', 'get_permissions', 'get_queryset', 'get_renderer_context', 'get_renderers', 'get_serializer', 'get_serializer_class', 'get_serializer_context', 'get_success_headers', 'get_throttles', 'get_view_description', 'get_view_name', 'handle_exception', 'headers', 'http_method_names', 'http_method_not_allowed', 'initial', 'initialize_request', 'kwargs', 'list', 'lookup_field', 'lookup_url_kwarg', 'metadata_class', 'name', 'options', 'paginate_queryset', 'pagination_class', 'paginator', 'parser_classes', 'partial_update', 'perform_authentication', 'perform_content_negotiation', 'perform_create', 'perform_destroy', 'perform_update', 'permission_classes', 'permission_denied', 'post', 'queryset', 'raise_uncaught_exception', 'recent_search', 'recent_search_kpi', 'renderer_classes', 'request', 'response_data', 'retrieve', 'reverse_action', 'schema', 'serializer_class', 'settings', 'setup', 'suffix', 'throttle_classes', 'throttled', 'update', 'versioning_class', 'word_details']
(Pdb) self.paginate_queryset
<bound method GenericAPIView.paginate_queryset of <api.api.SearchViewSet object at 0x000001A485E29278>>
(Pdb) dir(self.paginate_queryset)
['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__func__', '__ge__', '__get__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
(Pdb) self.paginate_queryset(queryset)
*** AttributeError: 'SearchViewSet' object has no attribute 'request'

从DRF Api View请求进行调试:

(Pdb) queryset
<QuerySet [<Search: food>, <Search: ice cream>, <Search: pollution>, <Search: lapto>, <Search: pollution>, <Search: food>, <Search: dogs>, <Search: war>, <Search: Venezuela>, <Search: rock>, <Search: movies>, <Search: marvel>, <Search: food>]>
(Pdb) self
<api.api.SearchViewSet object at 0x000001A485F902E8>
(Pdb) dir(self)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_allowed_methods', 'allowed_methods', 'as_view', 'authentication_classes', 'basename', 'check_object_permissions', 'check_permissions', 'check_throttles', 'code', 'content_negotiation_class', 'create', 'data', 'default_response_headers', 'description', 'destroy', 'detail', 'determine_version', 'dispatch', 'filter_backends', 'filter_queryset', 'finalize_response', 'get_authenticate_header', 'get_authenticators', 'get_content_negotiator', 'get_exception_handler', 'get_exception_handler_context', 'get_extra_action_url_map', 'get_extra_actions', 'get_format_suffix', 'get_object', 'get_paginated_response', 'get_parser_context', 'get_parsers', 'get_permissions', 'get_queryset', 'get_renderer_context', 'get_renderers', 'get_serializer', 'get_serializer_class', 'get_serializer_context', 'get_success_headers', 'get_throttles', 'get_view_description', 'get_view_name', 'handle_exception', 'http_method_names', 'http_method_not_allowed', 'initial', 'initialize_request', 'list', 'lookup_field', 'lookup_url_kwarg', 'metadata_class', 'name', 'options', 'paginate_queryset', 'pagination_class', 'paginator', 'parser_classes', 'partial_update', 'perform_authentication', 'perform_content_negotiation', 'perform_create', 'perform_destroy', 'perform_update', 'permission_classes', 'permission_denied', 'queryset', 'raise_uncaught_exception', 'recent_search', 'recent_search_kpi', 'renderer_classes', 'response_data', 'retrieve', 'reverse_action', 'schema', 'serializer_class', 'settings', 'setup', 'suffix', 'throttle_classes', 'throttled', 'update', 'versioning_class', 'word_details']
(Pdb) self.paginate_queryset
<bound method GenericAPIView.paginate_queryset of <api.api.SearchViewSet object at 0x000001A485F902E8>>
(Pdb) dir(self.paginate_queryset)
['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__func__', '__ge__', '__get__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
(Pdb) self.paginate_queryset(queryset)
[<Search: food>, <Search: ice cream>, <Search: pollution>, <Search: lapto>, <Search: pollution>, <Search: food>, <Search: dogs>, <Search: war>, <Search: Venezuela>, <Search: rock>]

我无法更好地解释问题,对发生的事情有任何想法吗?

在此先感谢您的帮助

0 个答案:

没有答案