-
Notifications
You must be signed in to change notification settings - Fork 162
Description
I am trying to write a python script to download the campaign performance report using the python sdk.
I keep getting the error "('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer'))".
I am using v13 of the bingads reporting.
May I know how I can resolve this error?
This is the python script,
`from campaignmanagement_example_helper import *
from auth_helper import *
from bingads.v13.reporting import *
from datetime import datetime, timedelta
You must provide credentials in auth_helper.py.
The report file extension type.
REPORT_FILE_FORMAT='Csv'
The directory for the report files.
FILE_DIRECTORY='/apps/edw/microsoft_ads/reports'
The name of the report download file.
RESULT_FILE_NAME='result.' + REPORT_FILE_FORMAT.lower()
The maximum amount of time (in milliseconds) that you want to wait for the report download.
TIMEOUT_IN_MILLISECONDS=3600000
def yesterday(frmt='%Y-%m-%d', string=True):
yesterday = datetime.now() - timedelta(1)
if string:
return yesterday.strftime(frmt)
return yesterday
#def main(authorization_data):
def get_campaign_report(authorization_data):
try:
# You can submit one of the example reports, or build your own.
"""
campaigns = campaign_service.GetCampaignsByAccountId(
AccountId=authorization_data.account_id,
CampaignType=['Search'])
output_status_message("Campaigns:")
for c in campaigns['Campaign']:
#entityIds.append(c.Id)
print(c.Name)
"""
AccountId=authorization_data.account_id,
startDate = yesterday()
endDate = yesterday()
aggregation = 'Daily'
exclude_column_headers=False
exclude_report_footer=False
exclude_report_header=False
time=reporting_service.factory.create('ReportTime')
time.PredefinedTime='Yesterday'
time.ReportTimeZone='BeijingChongqingHongKongUrumqi'
return_only_complete_data=True
time.CustomDateRangeStart = None
time.CustomDateRangeEnd = None
print(f'time = {time}')
print(f'account id = {AccountId}')
"""
start_date=reporting_service.factory.create('Date')
start_date.Day=startDate.day
start_date.Month=startDate.month
start_date.Year=startDate.year
time.CustomDateRangeStart=start_date
end_date=reporting_service.factory.create('Date')
end_date.Day=endDate.day
end_date.Month=endDate.month
end_date.Year=endDate.year
time.CustomDateRangeEnd=end_date
time.ReportTimeZone='BeijingChongqingHongKongUrumqi'
"""
report_request=reporting_service.factory.create('CampaignPerformanceReportRequest')
report_request.Aggregation=aggregation
report_request.ExcludeColumnHeaders=exclude_column_headers
report_request.ExcludeReportFooter=exclude_report_footer
report_request.ExcludeReportHeader=exclude_report_header
report_request.Format='Csv'
report_request.ReturnOnlyCompleteData=return_only_complete_data
report_request.Time=time
report_request.ReportName="Campaign Performance Report"
scope=reporting_service.factory.create('AccountThroughCampaignReportScope')
scope.AccountIds={'long': [AccountId] }
scope.Campaigns=None
report_request.Scope=scope
report_columns=reporting_service.factory.create('ArrayOfCampaignPerformanceReportColumn')
report_columns.CampaignPerformanceReportColumn.append(['TimePeriod','AccountName','AccountId','CampaignId',
'CampaignName','CampaignType','FinalUrlSuffix','Impressions','Clicks','Spend','Conversions'])
report_request.Columns=report_columns
#return campaign_performance_report_request
return report_request
except WebFault as ex:
output_webfault_errors(ex)
except Exception as ex:
output_status_message(ex)
#except:
#print("\nMS_ADS_CAMPAIGN_REPORT : report processing Failed : ", sys.exc_info())
"""
report_request=get_report_request(authorization_data.account_id)
reporting_download_parameters = ReportingDownloadParameters(
report_request=report_request,
result_file_directory = FILE_DIRECTORY,
result_file_name = RESULT_FILE_NAME,
overwrite_result_file = True, # Set this value true if you want to overwrite the same file.
timeout_in_milliseconds=TIMEOUT_IN_MILLISECONDS # You may optionally cancel the download after a specified time interval.
)
"""
def download_campaign_report(report_request, authorization_data):
try:
reporting_download_parameters = ReportingDownloadParameters(
report_request=report_request,
result_file_directory = FILE_DIRECTORY, # "./data/",
result_file_name = "campaign_report.csv",
overwrite_result_file = True, # value true if you want to overwrite the same file.
timeout_in_milliseconds=3600000 # cancel the download after a specified time interval.
)
reporting_service_manager = ReportingServiceManager(
authorization_data=authorization_data,
poll_interval_in_milliseconds=5000,
environment=ENVIRONMENT
)
report_container = reporting_service_manager.download_report(reporting_download_parameters)
if(report_container == None):
print("There is no report data for the submitted report request parameters.")
sys.exit(0)
"""
campaign_analytics_data = pd.DataFrame(columns=["account_id","campaign_name","campaign_id","start_date","end_date",
"cost","impressions","clicks"])
if "Impressions" in report_container.report_columns and \
"Clicks" in report_container.report_columns and \
"Spend" in report_container.report_columns and \
"CampaignId" in report_container.report_columns:
"""
#Be sure to close the report.
report_container.close()
except Exception as ex:
output_status_message(ex)
"""
except:
print("\nDOWNLOAD_CAMPAIGN_REPORT : processing Failed : ", sys.exc_info())
"""
Main execution
if name == 'main':
print("Loading the web service client proxies...")
authorization_data=AuthorizationData(
account_id=180639585,
customer_id=251854722,
developer_token='149J1R0KZB584239',
authentication=None,
)
campaign_service = ServiceClient(
service='CampaignManagementService',
version=13,
authorization_data=authorization_data,
environment=ENVIRONMENT,
)
reporting_service_manager=ReportingServiceManager(
authorization_data=authorization_data,
poll_interval_in_milliseconds=5000,
environment=ENVIRONMENT,
)
# In addition to ReportingServiceManager, you will need a reporting ServiceClient
# to build the ReportRequest.
reporting_service=ServiceClient(
service='ReportingService',
version=13,
authorization_data=authorization_data,
environment=ENVIRONMENT,
)
authenticate(authorization_data)
#main(authorization_data)
report_request = get_campaign_report(authorization_data)
download_campaign_report(report_request, authorization_data)
#campaign_analytics_data = download_campaign_report(report_request, authorization_data)
#print("\ncampaign_analytics_data :\n",campaign_analytics_data)
`