Python 如何在oauth 2.0中使用tastypie显示基于客户端id的模型内容?
我有一个问题,我想根据一个字段过滤模型资源,并向请求的客户机id显示特定的查询集 我使用带有django 1.6.5和swagger UI的tastypie v0.10.0作为文档 在示例模型中,我存储了与所有客户机相关的信息,并希望根据客户机id显示属于特定客户机的数据。在示例模型中,我有过滤器字段,可以根据这些字段为特定客户机创建querysetPython 如何在oauth 2.0中使用tastypie显示基于客户端id的模型内容?,python,django,rest,tastypie,Python,Django,Rest,Tastypie,我有一个问题,我想根据一个字段过滤模型资源,并向请求的客户机id显示特定的查询集 我使用带有django 1.6.5和swagger UI的tastypie v0.10.0作为文档 在示例模型中,我存储了与所有客户机相关的信息,并希望根据客户机id显示属于特定客户机的数据。在示例模型中,我有过滤器字段,可以根据这些字段为特定客户机创建queryset class Resource(ModelResource): class Meta: queryset = Example
class Resource(ModelResource):
class Meta:
queryset = Example.objects.all()
resource_name = 'example'
authorization = DjangoAuthorization()
detail_allowed_methods = ['get',]
authentication = OAuth20Authentication()
请建议我实现上述场景的最佳方法。提前感谢。我想到了两种可能性,如何根据客户id筛选资源。我想客户id是您模型的一个字段: 或者您可以使用Tastype筛选:
class Resource(ModelResource):
class Meta:
queryset = Example.objects.all()
resource_name = 'example'
authorization = DjangoAuthorization()
detail_allowed_methods = ['get',]
authentication = OAuth20Authentication()
filtering = {
'client_id': 'exact',
}
这一次,您应该通过GET方法传递过滤参数,类似于:
http://website.com/api/?client_id=5
或者您可以编写自己的obj_get_list方法:
class Resource(ModelResource):
class Meta:
queryset = Example.objects.all()
resource_name = 'example'
authorization = DjangoAuthorization()
detail_allowed_methods = ['get',]
authentication = OAuth20Authentication()
def obj_get_list(self, bundle, **kwargs):
queryset = Message.objects.filter(client_id = bundle.request.GET['client_id'])
return queryset
这是我提出的解决方案
import provider.oauth2
from provider.oauth2.models import AccessToken
class Resource(ModelResource):
#
class Meta:
queryset = Example.objects.all()
resource_name = 'example'
authorization = DjangoAuthorization()
detail_allowed_methods = ['get',]
always_return_data = True
authentication = OAuth20Authentication()
key = bundle.request.GET.get('oauth_consumer_key')
if not key:
key = bundle.request.POST.get('oauth_consumer_key')
if not key:
auth_header_value = bundle.request.META.get('HTTP_AUTHORIZATION')
if auth_header_value:
key = auth_header_value.split(' ')[1]
token = verify_access_token(key)
>>>>> token.user this contains username
>>>> come out with the proper conditions through which you can create queryset
queryset = Example.objects.filter(field=condition)
return queryset
感谢您的回复,但我的模型中没有客户id。provider.oauth2正在处理这个问题。我只是通过获取客户端ID在HTTP请求的头中获取AccessToken。您能告诉我从哪里获取头信息吗?我想您可以通过bundle.request.META['AccesToken']访问HTTP头,下面是我通过bundle.request.META.getHTTP_授权获取头的示例,但obj_get_列表不起作用。它给了我存储在模型中的全部数据,但这并不是我所问问题的正确答案。使用oauth2。