2012-11-26 35 views
1

看看這段代碼奇怪的問題使用谷歌DFP API的Python客戶端時

order_service = client.GetService('OrderService', version='v201208') 
creative_service = client.GetService('CreativeService', version='v201208') 
with open('/tmp/urls.txt', 'w') as f: 
    for i in range(0, 3929, 100): 
     print 'ORDER BY ID LIMIT 100 OFFSET '+str(i) 
     creatives = creative_service.getCreativesByStatement({'query':'ORDER BY ID LIMIT 100 OFFSET '+str(i)}) 
     try: 
      for creative in creatives[0]['results']: 
       try: 
        for var in creative['creativeTemplateVariableValues']: 
         if var['uniqueName'] == 'DetailsPageURL':       
          print var['value'] 
          f.write(creative['advertiserId']+','+var['value']+"\n") 
       exception: 
        pass 
     except: 
      raise 
      pass 

時偏移第二次迭代是200,將在for creative in creatives[0]['results']抱怨結果KeyError異常,但如果我改變一個try/except語句到if creative.has_key('creativeTemplateVariableValues'):像下面修復了這個問題:

order_service = client.GetService('OrderService', version='v201208') 
creative_service = client.GetService('CreativeService', version='v201208') 
with open('/tmp/urls.txt', 'w') as f: 
    for i in range(0, 3929, 100): 
     print 'ORDER BY ID LIMIT 100 OFFSET '+str(i) 
     creatives = creative_service.getCreativesByStatement({'query':'ORDER BY ID LIMIT 100 OFFSET '+str(i)}) 
     try: 
      print creatives[0]['results'] 
     except: 
      print creatives 
     #creatives = creative_service.getCreativesByStatement({'query':'ORDER BY ID LIMIT 10 OFFSET 200'}) 
     try: 
      for creative in creatives[0]['results']: 
       if creative.has_key('creativeTemplateVariableValues'): 
        for var in creative['creativeTemplateVariableValues']: 
         if var['uniqueName'] == 'DetailsPageURL': 
          print var['value'] 
          f.write(creative['advertiserId']+','+var['value']+"\n") 
     except: 
      raise 
      pass 

爲什麼?

回答

1

字段'creativeTemplateVariableValues'類型爲'TemplateCreative'的廣告素材,因此如果您網絡上的其他廣告素材不是TemplateCreative,則不會出現該字段並按照您所看到的丟棄關鍵錯誤。你可以做的對象的has_key檢查你幹得或另一種是做一個類型檢查:

if creative['Creative_Type'] == 'ImageCreative': 
    for var in creative['creativeTemplateVariableValues']: 
    ... 

如果你只關心TemplateCreatives,我會建議使用爲特定類型廣告的聲明過濾器。請參閱get_creatives_by_statement示例(http://code.google.com/p/google-api-ads-python/source/browse/trunk/examples/adspygoogle/dfp/v201208/get_creatives_by_statement.py)

對於未來有關DFP API和相關客戶端庫的問題,請發佈到DFP API論壇:https://groups.google.com/forum/#!forum/google-doubleclick-for-publishers-api

相關問題