2012-05-10 41 views
2

我瞭解TastyPie的基礎知識,但自定義ModelResource方法對我來說非常混亂。我正在嘗試進行PATCH API調用以更新用戶的密碼,並且數據未通過set_password()方法運行,因此正在使用原始值進行更新,而不是使用數據庫中的HASH進行更新。這裏是我的ModelResource:如何使用TastyPie PATCH更新密碼

class UserResource(ModelResource): 
    class Meta: 
     queryset = User.objects.all() 
     resource_name = 'user' 
     excludes = ['is_active', 'is_staff', 'is_superuser'] 
     authorization = Authorization() 
     detail_allowed_methods = ['get', 'post', 'put', 'delete', 'patch'] 
     filtering = { 
      'username': ALL, 
     } 
     authentication = ApiKeyAuthentication() 

我假設我需要在這裏使用obj_update方法,但我不知道實際的對象是在user表更新之前如何格式化這個運行通過set_password方法的密碼。

回答

4

您應該使用水合方法來處理這個raw_password以對所有情況(POST,PUT,PATCH)進行哈希轉換。我個人定義虛擬領域raw_password以免造成命名空間衝突,因爲Tastypie讓你POST/PUT/PATCH對象退回您從GET請求接收(是一個很好的做法旁):

def hydrate(self, bundle): 
    if bundle.data.has_key('raw_password'): 
     u = User(username='dummy') 
     u.set_password(bundle.data['raw_password']) 
     bundle.data['password'] = u.password 
    return bundle 
+0

@ digivampire謝謝爲了這。我覺得我在這裏朝着正確的方向前進。一些後續問題:請您詳細說明'定義一個虛擬領域',完成的地方以及如何配置?另外,'username ='dummy''有什麼意義?另外,有沒有一種方法來調試水合物方法來查看包中的內容? – bevinlorenzo

+0

此時,bundle僅包含原始序列化數據,Tastypie將創建一個完整的模型對象。通過虛擬字段,我的意思是從串行化輸入讀取的條目,但不是實際的TastyPie或Django的ORM字段。簡單地用於計算密碼散列,並將其置於恰當的位置,就好像客戶端確實知道散列並使用'password = hash_of(raw_password)'在請求中提交它。我不確定在實例化User對象時是否必須指定用戶名。轉出你不必,所以忽略:)。 – astevanovic

+0

這工作得很好!非常感謝! – bevinlorenzo