简体   繁体   English

在django-tastypie中获得认证的用户

[英]Get authenticated user in django-tastypie

I'm just starting with Python and Django, and using tastypie to create a RESTful API. 我只是从Python和Django开始,然后使用tastypie创建RESTful API。

I need to calculate a field of a resource based on the authenticated user, I plan to override the dehydrate_field method in my resource, but I don't know how to get the authenticated user within the dehydrate_field method. 我需要基于经过身份验证的用户来计算资源的字段,我计划在资源中覆盖dehydrate_field方法,但是我不知道如何在dehydrate_field方法中获取经过身份验证的用户。

I'm using tastypie's ApiKeyAuthentication, and I'm currently passing the authentication parameters in the query string of the URL but I'd like to be able to pass the authentication parameters in the Authentication header too. 我正在使用asteapie的ApiKeyAuthentication,目前正在URL的查询字符串中传递身份验证参数,但我也希望能够在Authentication标头中传递身份验证参数。

I think I should be able to get username from the query string or the Authorization header myself, and find the user with that, but I have a feeling like it has to be implemented in tastypie somewhere already, but I couldn't find it in the docs. 我想我应该可以自己从查询字符串或Authorization标头中获取用户名,并以此找到用户,但是我感觉它必须已经在某个地方实现了,但是我找不到它。文档。

Here's some sample code: 这是一些示例代码:

class MyModelResource(ModelResource):

    calculated_field = fields.BooleanField(readonly=True)

    class Meta:
        queryset = MyModel.objects.all()
        resource_name = 'mymodel'
        authentication = ApiKeyAuthentication()     

    def dehydrate_calculated_field(self, bundle):
        user = <get authenticated user somehow>
        return <some boolean that's calculated depending on authenticated user>

I'd like to know if tastypie has some built-in functionality for getting the authenticated user or a proper way to roll my own, based on query string parameters or header fields. 我想知道estaplie是否具有一些内置功能来获取经过身份验证的用户,或者是根据查询字符串参数或标头字段使用正确的方式来滚动自己的用户。

I found the answer to the question, to get the current user I'm doing 我找到了问题的答案,以获取当前正在使用的用户

user = bundle.request.user

Thanks to Aidan Ewen for pointing me in the right direction. 感谢Aidan Ewen为我指出正确的方向。

I'm not really familiar with Tastypie, but I think a Tastypie Resource is a django class based view . 我对Tastypie并不是很熟悉,但是我认为Tastypie资源是基于django类的视图 In which case you should be able to get the user with 在这种情况下,您应该能够吸引用户

user = self.request.user

I use Per-Request Alterations To The Queryset 我对查询集使用按请求的更改

class CurrentUserResource(ModelResource):
    class Meta:
        queryset = User.objects.all()
        resource_name = 'current-user'

    def get_object_list(self, request):
        users = super(CurrentUserResource, self).get_object_list(request)
        return users.filter(id=request.user.id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM