我刚刚开始使用 Python 和 Django,并使用 tastypie 创建 RESTful API。
我需要根据经过身份验证的用户计算资源的字段,我计划重写资源中的 deHydrate_field 方法,但我不知道如何在 deHydrate_field 方法中获取经过身份验证的用户。
我正在使用 tastypie 的 ApiKeyAuthentication,目前正在 URL 的查询字符串中传递身份验证参数,但我希望也能够在 Authentication header 中传递身份验证参数。
我认为我应该能够自己从查询字符串或授权 header 中获取用户名,并找到用户,但我有一种感觉,它必须已经在 tastypie 的某个地方实现了,但我不能在文档中找到它。
这是一些示例代码:
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>
我想知道 tastypie 是否有一些内置功能来获取经过身份验证的用户,或者根据查询字符串参数或 header 字段来推出自己的正确方法。
最佳答案
关于python - 在 django-tastypie 中获取经过身份验证的用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14425894/