2015-03-25 63 views
1

我正在寫代碼從HTML表單中獲取數據並修改數據庫對象。我只想在數據庫對象上做一個put()如果有變化,所以我需要知道是否有任何改變。執行一些功能跟蹤,如果有任何返回true

到目前爲止,我已經嘗試了幾種方法,我將在代碼中進行說明。它們都使用下面的設置代碼:

def _addFormAttrToModel(self, obj, attr_name, new_attr): 
    if hasattr(obj, attr_name): 
     current_attr = getattr(obj, attr_name) 
     if current_attr == new_attr: 
      return False 
    setattr(obj, attr_name, new_attr) 
    return True 
def addFormStringToModel(self, obj, attr_name): 
    new_attr = self.request.get(attr_name, None) 
    return self._addFormAttrToModel(obj, attr_name, new_attr) 

第一個使用or,以決定是否有任何方法調用的返回True。

updated=False 
updated = self.addFormStringToModel(customer, "name") or updated 
updated = self.addFormStringToModel(customer, "addr") or updated 
updated = self.addFormStringToModel(customer, "phone") or updated 
if updated: 
    customer.put() 

,我已經實驗過另一種形式使用一組:

results= set() 
results.add(self.addFormStringToModel(customer, "name")) 
results.add(self.addFormStringToModel(customer, "addr")) 
results.add(self.addFormStringToModel(customer, "phone")) 
if True in results: 
    customer.put() 

我真正喜歡做的是這樣的:

updated = self.addFormStringToModel(customer, "name") and \ 
      self.addFormStringToModel(customer, "addr") and \ 
      self.addFormStringToModel(customer, "phone") 
if updated: 
    customer.put() 

然而,經過停止執行第一個已更新的屬性。有更多pythonic的方式?

回答

2

使用any一個列表:

updated = [self.addFormStringToModel(customer, "name"), 
      self.addFormStringToModel(customer, "addr"), 
      self.addFormStringToModel(customer, "phone")] 

if any(updated): 

你能做出這樣短的一個名單理解:

updated = [self.addFormStringToModel(customer, field) 
      for field in ('name', 'addr' 'phone')] 
if any(updated) 
1

爲了去除冗餘代碼,你應該首先定義字段列表檢查:

fields_to_check = ['name', 'addr', 'phone'] 

然後,您使用列表聚合將該方法應用於LL值:

updated = [self.addFormStringToModel(customer, field) for field in fields_to_check] 

如果在LIS結果的任何那朵真實的any()會告訴:

if any(updated): 
    customer.put()