2015-10-20 91 views
0

将tastypie用于我们在此处的API。python/tastypie:非资源授权?

所以主要的API类:

from tastypie.api import Api 

class TheAPI(Api): 
    def prepend_urls(self): 
    return [ 
    url(r"^(?P<api_name>%s)/reset/(?P<pk>\w+)%s$" % (self.api_name, trailing_slash()), self.wrap_view('reset'), name="api_reset"), 
    ] 
    def reset(self, request, **kwargs): 
     #do the work 

到目前为止好。 我的问题在于我想在这个调用中使用ApiAuthentication。我不希望任何人能够使用重置功能(以及在URL中有一个唯一的代码,但仍然)。

但是,因为这不是一个资源,我不知道该怎么做。我尝试添加一个Meta类到这个类,但它似乎被忽略。

我能想到的唯一的其他黑客就是发明了一些封装了这个功能的FakeResource,但是这种感觉很奇怪,因为它不是资源。 任何想法?

+1

嘿嘿,不知道这代码是alrigth。 prepend_urls应该返回一个列表,并且在你的代码中你没有返回任何东西。 – Itxaka

回答

0

在这里扩展常规资源并将authorizationauthentication添加到Meta类没有任何坏处。

class BaseNonORMResource(Resource): 

    class Meta: 
     max_limit = None 

     """ 
     (Using Tastypie's DjangoAuthorization which checks the permission a user has granted to them) 
     and Tastypie's token based authentication approach 
     """ 
     authorization = DjangoAuthorization() 
     authentication = ApiKeyAuthentication() 

     ''' 
     Specify allowed_methods, list_allowed_methods or detail_allowed_methods in each SubResource 
     e.g. allowed_methods = ['get'] 
     ''' 
     allowed_methods = ['get', 'post', 'delete', 'patch', 'put'] 

,然后用它来定义端点

class TheAPI(BaseNonORMResource): 
    def prepend_urls(self): 
    return [ 
     url(r"^(?P<api_name>%s)/reset/(?P<pk>\w+)%s$" % (self.api_name, trailing_slash()), self.wrap_view('reset'), name="api_reset"), 
    ] 

    def reset(self, request, **kwargs): 
     #do the work