【发布时间】:2016-06-07 03:41:45
【问题描述】:
我在 Google Analytics API(Python) 中使用批处理请求。批处理链接:https://developers.google.com/api-client-library/python/guide/batch 当通过 .add() 的所有记录都正确(有效)时,批处理工作正常。当一个或多个值无效时,所有记录的批处理都会失败。
我添加了一个回调函数来处理错误,我看到批处理中所有记录的 BAtching 请求都失败了(而不是只有无效记录)。 有没有办法处理错误并跳过无效的行/记录并继续批处理中的其余记录?
下面是我使用的示例代码和错误信息:
def add_user_callback(request_id, response, exception):
if exception:
print "error :",exception
else:
print "successful"
def main():
## code to set the account, property and other variables
batch.add(service.management().webpropertyUserLinks().insert(
accountId=account_id,
webPropertyId=property_at,
body={
'permissions': {
'local': [
'READ_AND_ANALYZE'
]
},
'userRef': {
'email': 'valid_address@domain.com'
}
}))
batch.add(service.management().webpropertyUserLinks().insert(
accountId=account_id,
webPropertyId=property_at,
body={
'permissions': {
'local': [
'READ_AND_ANALYZE'
]
},
'userRef': {
'email': 'invalid_address@ddomain.com' ## i used a dummy id : pppp@domain.com
}
}))
batch.execute()
#Error :
#error : <HttpError 400 when requesting https://www.googleapis.com/analytics/v3/management/accounts/62974313/webproperties/UA-62974313-35/entityUserLinks?alt=json returned "Value for field user.email = ppppp@domain.com is not valid.">
#error : <HttpError 400 when requesting https://www.googleapis.com/analytics/v3/management/accounts/62974313/webproperties/UA-62974313-11/entityUserLinks?alt=json returned "Value for field user.email = ppppp@domain.com is not valid.">
如果您需要更多信息,请告诉我。
【问题讨论】:
-
在 add 方法中使用
request_id来跟踪失败的请求,并仅对格式良好的请求重新尝试。整个批处理请求需要是原子的,因为它可能需要多个请求来更改单个用户的 ACL——想象一下将用户从帐户级别移动到视图级别所需的请求。 -
Matt,您能否指出一些示例代码来处理 request_id。当出现异常时,我试图在回调函数中处理它。这是我正在使用的代码:
bad_email = re.search(r'[a-zA-Z0-9]*@[a-z]*[.][a-z]*\S',str(exception)) bad_emails.append(bad_email) print "emails in the bad_emails list:",bad_emails[0] create_batch(email_list, bad_emails)create_batch() 这里调用函数来创建批处理(没有 bad_emails) -
我在下面添加了一个更完整的解决方案,以帮助您从回复中提取违规电子邮件。
标签: python error-handling google-analytics google-analytics-api google-api-python-client