[英]Google Analytics API(Client library for Python) - Error handling
我在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.">
如果您需要更多信息,请告诉我。
假设您有一个要添加到配置文件中的users
列表,这些配置文件存储在list users
。 您可以使用以下回调函数删除不良电子邮件:
def call_back(request_id, response, exception):
if exception is not None:
if isinstance(exception, HttpError):
message = json.loads(exception.content)['error']['message']
bad = 'Value for field user.email = (\S*) is not valid.'
match = re.match(bad, message)
if match:
bad_user = match.group(1)
if bad_user in users:
users.remove(bad_user)
else:
print response
在所有失败的呼叫返回之后,您可以通过遍历用户并构造新的批处理请求来再次尝试再次执行批处理调用:
batch = BatchHttpRequest(callback=call_back)
for user in users:
request = analytics.management().profileUserLinks().insert(
accountId=ACCOUNT_ID,
webPropertyId=PROFILE_ID,
profileId=profile,
body={
'permissions': {'local': ['READ_AND_ANALYZE']},
'userRef': {'email': user}
}
)
batch.add(request, request_id=PROFILE_ID + user)
batch.execute()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.