0

我正在覆盖一个流行包的一些方法,django-activity-stream(我认为这个包与这个问题几乎无关)。

app/urls.py我打电话TeamJSONActivityFeed

urlpatterns = [
    ...
    url(_(r'^feeds/organization/(?P<organization_id>.+)$'), TeamJSONActivityFeed.as_view(name='organization_stream')),
    ...
]

TeamJSONactivityFeed 然后调用我不太熟悉的“pass”,并继承自其他两个类OrganizationStreamMixinJSONActivityFeed.

from rest_framework.authentication import TokenAuthentication

class TeamJSONActivityFeed(OrganizationStreamMixin, JSONActivityFeed):
    """
    JSON feed of Activity for a custom stream. self.name should be the name of the custom stream as defined in the Manager
    and arguments may be passed either in the url or when calling as_view(...)
    """
    authentication_classes = (TokenAuthentication,)
    pass

我的问题是我似乎无法访问/传递请求对象到这些继承的类中。我将如何传递这个?现在,self.request.userrequest.userAnonymousUser对象。

class OrganizationStreamMixin(object):
    name = None

    def get_object(self,request):
        # this is printing Anonymous User
        pprint(str(self.request.user))
        pprint(str(request.user))
        return

    def get_stream(self):
        return getattr(Action.objects, self.name)

    def items(self, request, *args, **kwargs):
        return self.get_stream()(*args[1:], **kwargs)


class JSONActivityFeed(AbstractActivityStream, View):
    """
    Feed that generates feeds compatible with the v1.0 JSON Activity Stream spec
    """
    def dispatch(self, request, *args, **kwargs):

        for i, v in kwargs.items():
            print ("    ", i, ": ", v)

        return HttpResponse(self.serialize(request, *args, **kwargs),
                            content_type='application/json')

    def serialize(self, request, *args, **kwargs):
        pprint(str(self.request.user))

        items = self.items(request, *args, **kwargs)
        return json.dumps({
            'totalItems': len(items),
            'items': [self.format(action) for action in items]
        })

注意:我是一个 django/python 菜鸟,但我确信我从前端正确地调用了它。类似的请求可以访问请求用户。

4

1 回答 1

1

我觉得有点混乱。.user您确实有权访问 request 对象,否则它会在尝试访问时引发错误None。如果您担心它是 AnonymousUser 实例,请在访问该视图之前进行身份验证。如果您需要阻止 AnonymousUser 实例访问该视图,请使用login_required装饰器包装该视图。

编辑

您正在覆盖该dispatch方法而不调用super. 这可能是问题所在。

于 2020-01-08T19:52:52.497 回答