2015-10-20 88 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