批量Service Manager
利用 批量服务 有效地管理帐户中所有市场活动的广告组和广告。 必应广告 .NET、Java 和 Python SDK 提供类,以提高下载和上传批量记录的工作效率。 例如, BulkServiceManager 会将下载请求提交到 批量服务,轮询服务直到完成,然后将文件下载到本地目录。 BulkServiceManager 还处理常见的请求标头字段,允许为每个服务在 AuthorizationData 对象中指定一次 Authentication、CustomerId、AccountId 和 DeveloperToken 属性。 有关详细信息,请参阅 使用 AuthorizationData 和 批量请求 代码示例。
注意
BulkServiceManager 仅适用于必应广告 .NET、Java 和 Python SDK。 无论是否使用 SDK,都可以直接使用 批量服务 。 有关详细信息,请参阅 批量下载和上传。
批量文件读取器和编写器
无需实现自己的文件分析程序来读取和写入批量文件。 可以使用 BulkFileReader 和 BulkFileWriter 对象读取和写入 BulkEntity 派生类。
注意
上传和下载实体而不是文件时, BulkServiceManager 在后台使用 BulkFileReader 和 BulkFileWriter 。 临时文件在后台使用。 有关详细信息,请参阅 Working Directory 和 BulkServiceManager。
例如,假设要将以下 扩展文本广告 记录写入批量文件。
Type,Status,Id,Parent Id,Campaign,Ad Group,Client Id,Modified Time,Title,Text,Text Part 2,Display Url,Destination Url,Promotion,Device Preference,Ad Format Preference,Name,App Platform,App Id,Final Url,Mobile Final Url,Tracking Template,Custom Parameter,Title Part 1,Title Part 2,Title Part 3,Path 1,Path 2
Format Version,,,,,,,,,,,,,,,6.0,,,,,,,,,,,
Expanded Text Ad,Active,,-1111,ParentCampaignNameGoesHere,AdGroupNameGoesHere,ClientIdGoesHere,,,Find New Customers & Increase Sales!,Start Advertising on Contoso Today.,,,,,False,,,,https://www.contoso.com/womenshoesale,https://mobile.contoso.com/womenshoesale,,{_promoCode}=PROMO1; {_season}=summer,Contoso,Quick & Easy Setup,Seemless Integration,seattle,shoe sale
首先,创建 BulkExpandedTextAd 对象,如 批量和市场活动管理实体映射中所示。 然后,可以将 BulkExpandedTextAd 写入使用 BulkFileWriter 的文件,如下所示。
var bulkFileWriter = new BulkFileWriter(
filePath: FileDirectory + UploadFileName
);
bulkFileWriter.WriteEntity(bulkExpandedTextAd);
bulkFileWriter.Dispose();
BulkFileWriter bulkFileWriter = new BulkFileWriter(
new File(FileDirectory + UploadFileName)
);
bulkFileWriter.writeEntity(bulkExpandedTextAd);
bulkFileWriter.close();
bulk_file_writer=BulkFileWriter(
file_path=FILE_DIRECTORY+UPLOAD_FILE_NAME
)
bulk_file_writer.write_entity(bulk_expanded_text_ad)
bulk_file_writer.close()
下面是使用 BulkFileReader 从本地目录读取批量上传结果文件的示例。 可以使用 BulkFileReader 读取批量文件,无论是完全下载、部分下载还是上传结果。
var bulkFileReader = new BulkFileReader(
filePath: bulkFilePath, // Path to the Bulk file
resultFileType: ResultFileType.Upload, // FullDownload, PartialDownload, or Upload
fileFormat: DownloadFileType.Csv // Csv or Tsv
);
var resultEntities = bulkFileReader.ReadEntities().ToList();
var expandedTextAdResults = resultEntities.OfType<BulkExpandedTextAd>().ToList();
OutputBulkExpandedTextAds(expandedTextAdResults);
bulkFileReader.Dispose();
BulkFileReader bulkFileReader = new BulkFileReader(
bulkFilePath, // Path to the Bulk file
ResultFileType.UPLOAD, // FULL_DOWNLOAD, PARTIAL_DOWNLOAD, or UPLOAD
DownloadFileType.CSV // Csv or Tsv
);
BulkEntityIterable resultEntities = bulkFileReader.getEntities();
for (BulkEntity entity : resultEntities) {
if (entity instanceof BulkExpandedTextAd) {
outputBulkBulkExpandedTextAds(Arrays.asList((BulkExpandedTextAd) entity));
}
}
resultEntities.close();
bulkFileReader.close();
def read_entities_from_bulk_file(file_path, result_file_type, file_type):
with BulkFileReader(file_path=file_path, result_file_type=result_file_type, file_type=file_type) as reader:
for entity in reader:
yield entity
def main():
result_entities=[]
entities_generator=read_entities_from_bulk_file(
file_path=bulk_file_path, # Path to the Bulk file
result_file_type=ResultFileType.upload, # full_download, partial_download, or upload
file_type='Csv' # Csv or Tsv
)
for entity in entities_generator:
result_entities.append(entity)
for entity in download_entities:
if isinstance(entity, BulkExpandedTextAd):
output_bulk_expanded_text_ads([entity])
批量和市场活动管理实体映射
通过 BulkServiceManager、BulkFileReader、BulkFileWriter 从批量文件读取和写入文件的所有对象都派生自 BulkEntity 基类,例如 BulkCampaign、BulkAdGroup 和 BulkExpandedTextAd。 如果可能,批量对象会利用市场活动管理对象和值集,例如,下面的 BulkExpandedTextAd 包含市场活动管理 API ExpandedTextAd 对象。
var uploadEntities = new List<BulkEntity>();
// Map properties in the Bulk file to the BulkExpandedTextAd
var bulkExpandedTextAd = new BulkExpandedTextAd
{
// 'Parent Id' column header in the Bulk file
AdGroupId = adGroupIdKey,
// 'Ad Group' column header in the Bulk file
AdGroupName = "AdGroupNameGoesHere",
// 'Campaign' column header in the Bulk file
CampaignName = "ParentCampaignNameGoesHere",
// 'Client Id' column header in the Bulk file
ClientId = "ClientIdGoesHere",
// Map properties in the Bulk file to the
// ExpandedTextAd object of the Campaign Management service.
ExpandedTextAd = new ExpandedTextAd
{
// 'Ad Format Preference' column header in the Bulk file
AdFormatPreference = "All",
// 'Mobile Final Url' column header in the Bulk file
FinalMobileUrls = new[] {
// Each Url is delimited by a semicolon (;) in the Bulk file
"https://mobile.contoso.com/womenshoesale"
},
// 'Final Url' column header in the Bulk file
FinalUrls = new[] {
// Each Url is delimited by a semicolon (;) in the Bulk file
"https://www.contoso.com/womenshoesale"
},
// 'Id' column header in the Bulk file
Id = null,
// 'Path 1' column header in the Bulk file
Path1 = "seattle",
// 'Path 2' column header in the Bulk file
Path2 = "shoe sale",
// 'Status' column header in the Bulk file
Status = AdStatus.Active,
// 'Text' column header in the Bulk file
Text = "Find New Customers & Increase Sales!",
// 'Text Part 2' column header in the Bulk file
TextPart2 = "Start Advertising on Contoso Today.",
// 'Title Part 1' column header in the Bulk file
TitlePart1 = "Contoso",
// 'Title Part 2' column header in the Bulk file
TitlePart2 = "Quick & Easy Setup",
// 'Title Part 3' column header in the Bulk file
TitlePart3 = "Seemless Integration",
// 'Tracking Template' column header in the Bulk file
TrackingUrlTemplate = null,
// 'Custom Parameter' column header in the Bulk file
UrlCustomParameters = new CustomParameters
{
// Each custom parameter is delimited by a semicolon (;) in the Bulk file
Parameters = new[] {
new CustomParameter(){
Key = "promoCode",
Value = "PROMO1"
},
new CustomParameter(){
Key = "season",
Value = "summer"
},
}
},
},
};
uploadEntities.Add(bulkExpandedTextAd);
var entityUploadParameters = new EntityUploadParameters
{
Entities = uploadEntities,
ResponseMode = ResponseMode.ErrorsAndResults,
ResultFileDirectory = FileDirectory,
ResultFileName = DownloadFileName,
OverwriteResultFile = true,
};
var uploadResultEntities = (await bulkServiceManager.UploadEntitiesAsync(entityUploadParameters)).ToList();
List<BulkEntity> uploadEntities = new ArrayList<BulkEntity>();
// Map properties in the Bulk file to the BulkExpandedTextAd
BulkExpandedTextAd bulkExpandedTextAd = new BulkExpandedTextAd();
// 'Parent Id' column header in the Bulk file
bulkExpandedTextAd.setAdGroupId(adGroupIdKey);
// 'Ad Group' column header in the Bulk file
bulkExpandedTextAd.setAdGroupName("AdGroupNameGoesHere");
// 'Campaign' column header in the Bulk file
bulkExpandedTextAd.setCampaignName("ParentCampaignNameGoesHere");
// 'Client Id' column header in the Bulk file
bulkExpandedTextAd.setClientId("ClientIdGoesHere");
// Map properties in the Bulk file to the
// ExpandedTextAd object of the Campaign Management service.
ExpandedTextAd expandedTextAd = new ExpandedTextAd();
// 'Ad Format Preference' column header in the Bulk file
expandedTextAd.setAdFormatPreference("All");
// 'Mobile Final Url' column header in the Bulk file
// Each Url is delimited by a semicolon (;) in the Bulk file
ArrayOfstring mobileFinalUrls = new ArrayOfstring();
mobileFinalUrls.getStrings().add("https://mobile.contoso.com/womenshoesale");
expandedTextAd.setFinalMobileUrls(mobileFinalUrls);
// 'Final Url' column header in the Bulk file
// Each Url is delimited by a semicolon (;) in the Bulk file
ArrayOfstring finalUrls = new ArrayOfstring();
finalUrls.getStrings().add("https://www.contoso.com/womenshoesale");
expandedTextAd.setFinalUrls(finalUrls);
// 'Id' column header in the Bulk file
expandedTextAd.setId(null);
// 'Path 1' column header in the Bulk file
expandedTextAd.setPath1("seattle");
// 'Path 2' column header in the Bulk file
expandedTextAd.setPath2("shoe sale");
// 'Status' column header in the Bulk file
expandedTextAd.setStatus(AdStatus.ACTIVE);
// 'Text' column header in the Bulk file
expandedTextAd.setText("Find New Customers & Increase Sales!");
// 'Text Part 2' column header in the Bulk file
expandedTextAd.setTextPart2("Start Advertising on Contoso Today.");
// 'Title Part 1' column header in the Bulk file
expandedTextAd.setTitlePart1("Contoso");
// 'Title Part 2' column header in the Bulk file
expandedTextAd.setTitlePart2("Quick & Easy Setup");
// 'Title Part 3' column header in the Bulk file
expandedTextAd.setTitlePart3("Seemless Integration");
// 'Tracking Template' column header in the Bulk file
expandedTextAd.setTrackingUrlTemplate(null);
// 'Custom Parameter' column header in the Bulk file
// Each custom parameter is delimited by a semicolon (;) in the Bulk file
CustomParameters customParameters = new CustomParameters();
ArrayOfCustomParameter arrayOfCustomParameter = new ArrayOfCustomParameter();
CustomParameter customParameterA = new CustomParameter();
customParameterA.setKey("promoCode");
customParameterA.setValue("PROMO1");
arrayOfCustomParameter.getCustomParameters().add(customParameterA);
CustomParameter customParameterB = new CustomParameter();
customParameterB.setKey("season");
customParameterB.setValue("summer");
arrayOfCustomParameter.getCustomParameters().add(customParameterB);
customParameters.setParameters(arrayOfCustomParameter);
expandedTextAd.setUrlCustomParameters(customParameters);
bulkExpandedTextAd.setExpandedTextAd(expandedTextAd);
uploadEntities.add(bulkExpandedTextAd);
EntityUploadParameters entityUploadParameters = new EntityUploadParameters();
entityUploadParameters.setEntities(uploadEntities);
entityUploadParameters.setOverwriteResultFile(true);
entityUploadParameters.setResultFileDirectory(new File(FileDirectory));
entityUploadParameters.setResultFileName(ResultFileName);
entityUploadParameters.setResponseMode(ResponseMode.ERRORS_AND_RESULTS);
BulkEntityIterable uploadResultEntities = bulkServiceManager.uploadEntitiesAsync(
entityUploadParameters,
null,
null
).get();
# Map properties in the Bulk file to the BulkExpandedTextAd
bulk_expanded_text_ad=BulkExpandedTextAd()
# 'Parent Id' column header in the Bulk file
bulk_expanded_text_ad.ad_group_id=AD_GROUP_ID_KEY
# 'Ad Group' column header in the Bulk file
bulk_expanded_text_ad.AdGroupName='AdGroupNameGoesHere'
# 'Campaign' column header in the Bulk file
bulk_expanded_text_ad.CampaignName='ParentCampaignNameGoesHere'
# 'Client Id' column header in the Bulk file
bulk_expanded_text_ad.ClientId='ClientIdGoesHere'
# Map properties in the Bulk file to the
# ExpandedTextAd object of the Campaign Management service.
expanded_text_ad=set_elements_to_none(campaign_service.factory.create('ExpandedTextAd'))
# 'Ad Format Preference' column header in the Bulk file
expanded_text_ad.AdFormatPreference='All'
# 'Mobile Final Url' column header in the Bulk file
# Each Url is delimited by a semicolon (;) in the Bulk file
mobile_final_urls=campaign_service.factory.create('ns3:ArrayOfstring')
mobile_final_urls.string.append('https://mobile.contoso.com/womenshoesale')
expanded_text_ad.FinalUrls=mobile_final_urls
# 'Final Url' column header in the Bulk file
# Each Url is delimited by a semicolon (;) in the Bulk file
final_urls=campaign_service.factory.create('ns3:ArrayOfstring')
final_urls.string.append('https://www.contoso.com/womenshoesale')
expanded_text_ad.FinalUrls=final_urls
# 'Id' column header in the Bulk file
expanded_text_ad.Id=None
# 'Path 1' column header in the Bulk file
expanded_text_ad.Path1='seattle'
# 'Path 2' column header in the Bulk file
expanded_text_ad.Path2='shoe sale'
# 'Status' column header in the Bulk file
expanded_text_ad.Status='Active'
# 'Text' column header in the Bulk file
expanded_text_ad.Text='Find New Customers & Increase Sales!'
# 'Text Part 2' column header in the Bulk file
expanded_text_ad.TextPart2='Start Advertising on Contoso Today.'
# 'Title Part 1' column header in the Bulk file
expanded_text_ad.TitlePart1='Contoso'
# 'Title Part 2' column header in the Bulk file
expanded_text_ad.TitlePart2='Quick & Easy Setup'
# 'Title Part 3' column header in the Bulk file
expanded_text_ad.TitlePart3='Seemless Integration'
# 'Tracking Template' column header in the Bulk file
expanded_text_ad.TrackingUrlTemplate=None
# 'Custom Parameter' column header in the Bulk file
# Each custom parameter is delimited by a semicolon (;) in the Bulk file
custom_parameters=set_elements_to_none(campaign_service.factory.create('CustomParameters'))
array_of_custom_parameter=campaign_service.factory.create('ArrayOfCustomParameter')
custom_parameter_a=set_elements_to_none(campaign_service.factory.create('CustomParameter'))
custom_parameter_a.Key='promoCode'
custom_parameter_a.Value='PROMO1'
array_of_custom_parameter.CustomParameter.append(custom_parameter_a)
custom_parameter_b=set_elements_to_none(campaign_service.factory.create('CustomParameter'))
custom_parameter_b.Key='season'
custom_parameter_b.Value='summer'
array_of_custom_parameter.CustomParameter.append(custom_parameter_b)
custom_parameters.Parameters=array_of_custom_parameter
expanded_text_ad.UrlCustomParameters=custom_parameters
bulk_expanded_text_ad.ad=expanded_text_ad
upload_entities.append(bulk_expanded_text_ad)
entity_upload_parameters=EntityUploadParameters(
entities=upload_entities,
overwrite_result_file=True,
result_file_directory=FILE_DIRECTORY,
result_file_name=RESULT_FILE_NAME,
response_mode='ErrorsAndResults'
)
upload_result_entities=bulk_service_manager.upload_entities(
entity_upload_parameters=entity_upload_parameters,
progress=None
)
使用 delete_value 进行更新
若要删除现有设置,不应将空字符串 (“”) 写入 Bulk 文件,因为批量服务会忽略此类字符串。 使用保留的“delete_value”字符串删除或重置可选字段的值。 如果在可选字段中使用保留的“delete_value”字符串,则会删除以前的设置。 例如,如果将“展开的文本广告”记录的“自定义参数”字段设置为“delete_value”,则会从展开的文本广告中删除所有以前的自定义参数。 同样,如果将“展开的文本广告”记录的“跟踪模板”字段设置为“delete_value”,则会从展开的文本广告中删除以前的跟踪模板。 有关“delete_value”的更多详细信息,请参阅 批量文件架构 - 使用delete_value更新。
BulkFileWriter 在适用的情况下自动写入“delete_value”。 由于 SDK 将市场活动管理 API 对象 映射到 批量文件的内容,因此不能显式设置具有其他数据类型的属性的“delete_value”字符串。 在这些情况下,可以使用通过市场活动管理 API 更新对象的相同语法。 在下面的示例中,通过将 UrlCustomParameters 设置为空 CustomParameters 对象,SDK 将在“扩展文本广告记录的自定义参数”字段中写入“delete_value”。 同样,通过将 TrackingUrlTemplate 设置为空字符串,SDK 将在扩展文本广告记录的跟踪模板字段中写入“delete_value”。 ExpandedTextAd 对象中的示例语法与通过市场活动管理 API 通过 UpdateAds 服务操作删除 previus 设置的方式相同。
重要
创建 Bulk 实体时,请勿使用空字符串 (“”) 或“delete_value”语法。 保留的“delete_value”字符串仅适用于更新批量记录。 不应设置 属性,或将其设置为 null 等效项。
var bulkExpandedTextAd = new BulkExpandedTextAd
{
AdGroupId = adGroupIdKey,
ExpandedTextAd = new ExpandedTextAd
{
Id = expandedTextAdIdKey,
TrackingUrlTemplate = "",
UrlCustomParameters = new CustomParameters { }
},
};
BulkExpandedTextAd bulkExpandedTextAd = new BulkExpandedTextAd();
bulkExpandedTextAd.setAdGroupId(expandedTextAdIdKey);
ExpandedTextAd expandedTextAd = new ExpandedTextAd();
expandedTextAd.setId(adIdKey);
expandedTextAd.setTrackingUrlTemplate("");
CustomParameters customParameters = new CustomParameters();
expandedTextAd.setUrlCustomParameters(customParameters);
bulkExpandedTextAd.setExpandedTextAd(expandedTextAd);
bulk_expanded_text_ad=BulkExpandedTextAd()
bulk_expanded_text_ad.ad_group_id=AD_GROUP_ID_KEY
expanded_text_ad=set_elements_to_none(campaign_service.factory.create('ExpandedTextAd'))
expanded_text_ad.Id=EXPANDED_TEXT_AD_ID_KEY
expanded_text_ad.TrackingUrlTemplate=''
custom_parameters=set_elements_to_none(campaign_service.factory.create('CustomParameters'))
expanded_text_ad.UrlCustomParameters=custom_parameters
bulk_expanded_text_ad.ad=expanded_text_ad
下载和上传
BulkServiceManager 支持灵活的批量下载和上传工作流。
可以创建下载或上传请求, BulkServiceManager 会将你的下载请求提交到批量服务,轮询服务直到完成,然后将文件下载到本地目录。 有关示例,请参阅 使用 BulkServiceManager 完成后台。
可以提交下载或上传请求,然后轮询,直到结果文件准备好下载。 有关示例,请参阅 使用 BulkServiceManager 提交和下载。
如果出于任何原因必须从以前的应用程序状态恢复,可以使用现有的下载或上传请求标识符,并使用它下载结果文件。 有关示例,请参阅 使用 BulkServiceManager 下载结果。
无论是在内存中下载和上传实体,还是自己在文件中读取和写入实体,BulkServiceManager 都对临时文件进行读取和写入。
使用 BulkServiceManager 完成后台
可以创建下载或上传请求, BulkServiceManager 会将你的下载请求提交到批量服务,轮询服务直到完成,然后将文件下载到本地目录。
public async Task RunAsync(AuthorizationData authorizationData)
{
var bulkServiceManager = new BulkServiceManager(authorizationData);
var progress = new Progress<BulkOperationProgressInfo>(x =>
Console.WriteLine(String.Format("{0} % Complete", x.PercentComplete.ToString(CultureInfo.InvariantCulture))));
var downloadParameters = new DownloadParameters
{
CampaignIds = null,
DataScope = DataScope.EntityData,
Entities = DownloadEntity.Keywords,
FileType = DownloadFileType.Csv,
LastSyncTimeInUTC = null,
ResultFileDirectory = FileDirectory,
ResultFileName = ResultFileName,
OverwriteResultFile = false // Set this value true if you want to overwrite the same file.
};
// Sets the time interval in milliseconds between two status polling attempts. The default value is 5000 (5 seconds).
bulkServiceManager.StatusPollIntervalInMilliseconds = 5000;
// Sets the timeout of the HttpClient download operation. The default value is 100000 (100s).
bulkServiceManager.DownloadHttpTimeout = new TimeSpan(0, 0, 100);
// You may optionally cancel the DownloadFileAsync operation after a specified time interval.
// Pass this object to the DownloadFileAsync operation or specify CancellationToken.None.
var tokenSource = new CancellationTokenSource();
tokenSource.CancelAfter(3600000);
// The BulkServiceManager will submit your download request to the Bulk service,
// poll the service until completed, and download the file to your local directory.
var resultFile = await bulkServiceManager.DownloadFileAsync(
parameters: downloadParameters,
progress: progress,
cancellationToken: tokenSource.Token
);
Console.WriteLine(string.Format("Download result file: {0}\n", resultFile));
}
BulkServiceManager bulkServiceManager = new BulkServiceManager(authorizationData);
Progress<BulkOperationProgressInfo> progress = new Progress<BulkOperationProgressInfo>() {
@Override
public void report(BulkOperationProgressInfo value) {
System.out.println(value.getPercentComplete() + "% Complete\n");
}
};
DownloadParameters downloadParameters = new DownloadParameters();
downloadParameters.setCampaignIds(null);
ArrayList<DataScope> dataScope = new ArrayList<DataScope>();
dataScope.add(DataScope.ENTITY_DATA);
downloadParameters.setDataScope(dataScope);
downloadParameters.setFileType(FileType);
downloadParameters.setLastSyncTimeInUTC(null);
ArrayList<DownloadEntity> bulkDownloadEntities = new ArrayList<DownloadEntity>();
bulkDownloadEntities.add(DownloadEntity.KEYWORDS);
downloadParameters.setEntities(bulkDownloadEntities);
downloadParameters.setResultFileDirectory(new File(FileDirectory));
downloadParameters.setResultFileName(ResultFileName);
downloadParameters.setOverwriteResultFile(true); // Set this value true if you want to overwrite the same file.
// Sets the time interval in milliseconds between two status polling attempts. The default value is 5000 (5 seconds).
bulkServiceManager.setStatusPollIntervalInMilliseconds(5000);
// Sets the timeout of the HttpClient download operation. The default value is 100000 (100s).
bulkServiceManager.setDownloadHttpTimeoutInMilliseconds(100000);
// The BulkServiceManager will submit your download request to the Bulk service,
// poll the service until completed, and download the file to your local directory.
// You may optionally cancel the downloadFileAsync operation after a specified time interval.
File resultFile = bulkServiceManager.downloadFileAsync(
downloadParameters,
progress,
null
).get(3600000, TimeUnit.MILLISECONDS);
System.out.printf("Download result file: %s\n", resultFile.getName());
bulk_service_manager = BulkServiceManager(
authorization_data=authorization_data,
# Sets the time interval in milliseconds between two status polling attempts.
# The default value is 5000 (5 seconds).
poll_interval_in_milliseconds = 5000,
environment = ENVIRONMENT,
)
download_parameters = DownloadParameters(
campaign_ids=None,
data_scope=['EntityData'],
entities=entities,
file_type=FILE_TYPE,
last_sync_time_in_utc=None,
result_file_directory = FILE_DIRECTORY,
result_file_name = DOWNLOAD_FILE_NAME,
# Set this value true if you want to overwrite the same file.
overwrite_result_file = True,
# You may optionally cancel the download after a specified time interval.
timeout_in_milliseconds=3600000
)
# The BulkServiceManager will submit your download request to the Bulk service,
# poll the service until completed, and download the file to your local directory.
result_file_path = bulk_service_manager.download_file(
download_parameters=download_parameters,
progress = None
)
print("Download result file: {0}\n".format(result_file_path))
使用 BulkServiceManager 提交和下载
提交下载请求,然后使用 BulkDownloadOperation 结果跟踪状态。
public async Task RunAsync(AuthorizationData authorizationData)
{
var bulkServiceManager = new BulkServiceManager(authorizationData);
var submitDownloadParameters = new SubmitDownloadParameters
{
CampaignIds = null,
DataScope = DataScope.EntityData,
Entities = DownloadEntity.Keywords,
FileType = DownloadFileType.Csv,
LastSyncTimeInUTC = null
};
var bulkDownloadOperation = await bulkServiceManager.SubmitDownloadAsync(submitDownloadParameters);
// You may optionally cancel the TrackAsync operation after a specified time interval.
var tokenSource = new CancellationTokenSource();
tokenSource.CancelAfter(3600000);
BulkOperationStatus<DownloadStatus> downloadStatus = await bulkDownloadOperation.TrackAsync(
null,
tokenSource.Token
);
var resultFilePath = await bulkDownloadOperation.DownloadResultFileAsync(
FileDirectory,
ResultFileName,
decompress: true,
overwrite: true // Set this value true if you want to overwrite the same file.
);
Console.WriteLine(String.Format("Download result file: {0}\n", resultFilePath));
}
BulkServiceManager bulkServiceManager = new BulkServiceManager(authorizationData);
SubmitDownloadParameters submitDownloadParameters = new SubmitDownloadParameters();
submitDownloadParameters.setCampaignIds(null);
ArrayList<DataScope> dataScope = new ArrayList<DataScope>();
dataScope.add(DataScope.ENTITY_DATA);
submitDownloadParameters.setDataScope(dataScope);
submitDownloadParameters.setFileType(FileType);
submitDownloadParameters.setLastSyncTimeInUTC(null);
ArrayList<DownloadEntity> bulkDownloadEntities = new ArrayList<DownloadEntity>();
bulkDownloadEntities.add(DownloadEntity.KEYWORDS);
submitDownloadParameters.setEntities(bulkDownloadEntities);
// Submit the download request. You can use the BulkDownloadOperation result to track status yourself using getStatusAsync,
// or use trackAsync to indicate that the application should wait until the download status is completed.
BulkDownloadOperation bulkDownloadOperation = bulkServiceManager.submitDownloadAsync(
submitDownloadParameters,
null
).get();
// You may optionally cancel the trackAsync operation after a specified time interval.
BulkOperationStatus<DownloadStatus> downloadStatus = bulkDownloadOperation.trackAsync(
null
).get(3600000, TimeUnit.MILLISECONDS);
File resultFile = bulkDownloadOperation.downloadResultFileAsync(
new File(FileDirectory),
ResultFileName,
true, // Set this value to true if you want to decompress the ZIP file.
true, // Set this value true if you want to overwrite the named file.
null
).get();
System.out.println(String.format("Download result file: %s\n", resultFile.getName()));
bulk_service_manager = BulkServiceManager(
authorization_data=authorization_data,
poll_interval_in_milliseconds = 5000,
environment = ENVIRONMENT,
)
submit_download_parameters = SubmitDownloadParameters(
data_scope = [ 'EntityData' ],
entities = [ 'Campaigns', 'AdGroups', 'Keywords', 'Ads' ],
file_type = 'Csv',
campaign_ids = None,
last_sync_time_in_utc = None,
performance_stats_date_range = None
)
bulk_download_operation = bulk_service_manager.submit_download(submit_download_parameters)
# You may optionally cancel the track() operation after a specified time interval.
download_status = bulk_download_operation.track(timeout_in_milliseconds=3600000)
result_file_path = bulk_download_operation.download_result_file(
result_file_directory = FILE_DIRECTORY,
result_file_name = DOWNLOAD_FILE_NAME,
decompress = True,
overwrite = True, # Set this value true if you want to overwrite the same file.
timeout_in_milliseconds=3600000 # You may optionally cancel the download after a specified time interval.
)
print("Download result file: {0}\n".format(result_file_path))
使用 BulkServiceManager 下载结果
如果出于任何原因必须从以前的应用程序状态恢复,可以使用现有的下载或上传请求标识符,并使用它下载结果文件。 跟踪结果以确保下载状态已完成。
public async Task RunAsync(AuthorizationData authorizationData)
{
var bulkServiceManager = new BulkServiceManager(authorizationData);
var progress = new Progress<BulkOperationProgressInfo>(x =>
Console.WriteLine(String.Format("{0} % Complete", x.PercentComplete.ToString(CultureInfo.InvariantCulture))));
// You may optionally cancel the TrackAsync operation after a specified time interval.
var tokenSource = new CancellationTokenSource();
tokenSource.CancelAfter(3600000);
var bulkDownloadOperation = new BulkDownloadOperation(requestId, authorizationData);
// Use TrackAsync to indicate that the application should wait to ensure that
// the download status is completed.
var bulkOperationStatus = await bulkDownloadOperation.TrackAsync(null, tokenSource.Token);
var resultFilePath = await bulkDownloadOperation.DownloadResultFileAsync(
FileDirectory,
ResultFileName,
decompress: true,
overwrite: true // Set this value true if you want to overwrite the same file.
);
Console.WriteLine(String.Format("Download result file: {0}", resultFilePath));
Console.WriteLine(String.Format("Status: {0}", bulkOperationStatus.Status));
Console.WriteLine(String.Format("TrackingId: {0}\n", bulkOperationStatus.TrackingId));
}
Progress<BulkOperationProgressInfo> progress = new Progress<BulkOperationProgressInfo>() {
@Override
public void report(BulkOperationProgressInfo value) {
System.out.println(value.getPercentComplete() + "% Complete\n");
}
};
java.lang.String requestId = RequestIdGoesHere;
BulkDownloadOperation bulkDownloadOperation = new BulkDownloadOperation(requestId, authorizationData);
// You may optionally cancel the trackAsync operation after a specified time interval.
BulkOperationStatus<DownloadStatus> downloadStatus = bulkDownloadOperation.trackAsync(
progress,
null
).get(3600000, TimeUnit.MILLISECONDS);
System.out.printf(
"Download Status:\nPercentComplete: %s\nResultFileUrl: %s\nStatus: %s\n",
downloadStatus.getPercentComplete(), downloadStatus.getResultFileUrl(), downloadStatus.getStatus()
);
File resultFile = bulkDownloadOperation.downloadResultFileAsync(
new File(FileDirectory),
ResultFileName,
true, // Set this value to true if you want to decompress the ZIP file
true, // Set this value true if you want to overwrite the same file.
null
).get();
System.out.println(String.format("Download result file: %s", resultFile.getName()));
System.out.println(String.format("Status: %s", downloadStatus.getStatus()));
System.out.println(String.format("TrackingId: %s\n", downloadStatus.getTrackingId()));
request_id = RequestIdGoesHere
bulk_download_operation = BulkDownloadOperation(
request_id = request_id,
authorization_data = authorization_data,
poll_interval_in_milliseconds = 5000,
environment = ENVIRONMENT
)
# Use track() to indicate that the application should wait to ensure that the download status is completed.
# You may optionally cancel the track() operation after a specified time interval.
bulk_operation_status = bulk_download_operation.track(timeout_in_milliseconds=3600000)
result_file_path = bulk_download_operation.download_result_file(
result_file_directory = FILE_DIRECTORY,
result_file_name = DOWNLOAD_FILE_NAME,
decompress = True,
overwrite = True, # Set this value true if you want to overwrite the same file.
timeout_in_milliseconds=3600000 # You may optionally cancel the download after a specified time interval.
)
print("Download result file: {0}\n".format(result_file))
print("Status: {0}\n".format(bulk_operation_status.status))
轮询和重试
按合理的间隔轮询下载和上传结果。 你比任何人都更了解你的数据。 例如,如果下载的关键字远远少于 100 万的帐户,请考虑以 5 到 20 秒的间隔进行轮询。 如果帐户包含大约 100 万个关键字,请考虑在等待五分钟后每隔一分钟轮询一次。 对于具有大约 400 万个关键字的帐户,请考虑在等待 10 分钟后每隔一分钟轮询一次。
BulkServiceManager 在前五次尝试的间隔 1000 毫秒内自动轮询结果文件,并且该行为不可配置。 StatusPollIntervalInMilliseconds 属性确定最初五次尝试之后每次轮询尝试之间的时间间隔。 有关示例,请参阅上面的 后台完成 。 默认值为 5000,因此如果未设置此值, BulkServiceManager 将按以下分钟顺序轮询:1、2、3、4、5、10、15、20 等。 如果将此值设置为 10000,BulkServiceManager 将按以下顺序轮询:1、2、3、4、5、15、25、35 等。 最小轮询间隔为 1000,如果指定的值小于 1000,则会引发异常。
BulkServiceManager 将自动重试上传、下载和轮询操作,最长不超过你设置的最大超时持续时间。 可以设置最大重试超时持续时间。 如果未指定超时, BulkServiceManager 将继续重试,直到服务器返回超时或内部错误。 另外,如果要上传或下载大型文件,应考虑设置 UploadHttpTimeout 或 DownloadHttpTimeout 属性。
工作目录和 BulkServiceManager
使用必应广告 .NET 和 Java SDK,可以设置 BulkServiceManager 应在其中存储临时批量文件的工作目录。 例如,使用必应广告 .NET SDK 下载实体时,虽然仅直接处理 BulkEntity 对象,但批量文件会下载到工作目录。 同样,在上传实体时,临时文件将写入工作目录,然后上传到批量服务。 如果未指定其他工作目录,将使用系统临时目录。
如果使用托管服务(如 Microsoft Azure),则需要确保不超过临时目录限制。 使用自定义工作目录可能还有其他原因。 可以通过设置 WorkingDirectory 属性为每个 BulkServiceManager 实例指定不同的工作目录。 你还负责创建和删除任何目录。 循环访问批量实体后,可以清理工作目录中的文件。
重要
CleanupTempFiles 方法 (删除工作目录中) 的所有文件,无论文件是否由当前 BulkServiceManager 实例创建。
public async Task RunAsync(AuthorizationData authorizationData)
{
var bulkServiceManager = new BulkServiceManager(authorizationData);
var progress = new Progress<BulkOperationProgressInfo>(x =>
Console.WriteLine(String.Format("{0} % Complete", x.PercentComplete.ToString(CultureInfo.InvariantCulture)))
);
var downloadParameters = new DownloadParameters
{
CampaignIds = null,
DataScope = DataScope.EntityData,
Entities = DownloadEntity.Keywords,
FileType = DownloadFileType.Csv,
LastSyncTimeInUTC = null,
ResultFileDirectory = FileDirectory,
ResultFileName = ResultFileName,
OverwriteResultFile = false // Set this value true if you want to overwrite the same file.
};
// The system temp directory will be used if another working directory is not specified. If you are
// using a hosted service such as Microsoft Azure you'll want to ensure you do not exceed the file or directory limits.
// You can specify a different working directory for each BulkServiceManager instance.
bulkServiceManager.WorkingDirectory = FileDirectory;
// The DownloadEntitiesAsync method returns IEnumerable<BulkEntity>, so the download file will not
// be accessible e.g. for CleanupTempFiles until you iterate over the result e.g. via ToList().
var resultEntities = (await bulkServiceManager.DownloadEntitiesAsync(
downloadParameters
)).ToList();
// The CleanupTempFiles method removes all files (but not sub-directories) within the working directory,
// whether or not the files were created by this BulkServiceManager instance.
bulkServiceManager.CleanupTempFiles();
}
BulkServiceManager bulkServiceManager = new BulkServiceManager(authorizationData);
Progress<BulkOperationProgressInfo> progress = new Progress<BulkOperationProgressInfo>() {
@Override
public void report(BulkOperationProgressInfo value) {
System.out.println(value.getPercentComplete() + "% Complete\n");
}
};
DownloadParameters downloadParameters = new DownloadParameters();
downloadParameters.setCampaignIds(null);
ArrayList<DataScope> dataScope = new ArrayList<DataScope>();
dataScope.add(DataScope.ENTITY_DATA);
downloadParameters.setDataScope(dataScope);
downloadParameters.setFileType(FileType);
downloadParameters.setLastSyncTimeInUTC(null);
ArrayList<DownloadEntity> bulkDownloadEntities = new ArrayList<DownloadEntity>();
bulkDownloadEntities.add(DownloadEntity.KEYWORDS);
downloadParameters.setEntities(bulkDownloadEntities);
downloadParameters.setResultFileDirectory(new File(FileDirectory));
downloadParameters.setResultFileName(ResultFileName);
downloadParameters.setOverwriteResultFile(true); // Set this value true if you want to overwrite the same file.
// The system temp directory will be used if another working directory is not specified. If you are
// using a cloud service such as Microsoft Azure you'll want to ensure you do not exceed the file or directory limits.
// You can specify a different working directory for each BulkServiceManager instance.
bulkServiceManager.setWorkingDirectory(new File(FileDirectory));
// The downloadEntitiesAsync method returns BulkEntityIterable, so the download file will not
// be accessible e.g. for cleanupTempFiles until you iterate over the result and close the BulkEntityIterable instance.
BulkEntityIterable tempEntities = bulkServiceManager.downloadEntitiesAsync(
downloadParameters,
null,
null
).get();
ArrayList<BulkEntity> resultEntities = new ArrayList<BulkEntity>();
for (BulkEntity entity : tempEntities) {
resultEntities.add(entity);
}
tempEntities.close();
// The cleanupTempFiles method removes all files (not sub-directories) within the working directory,
// whether or not the files were created by this BulkServiceManager instance.
bulkServiceManager.cleanupTempFiles();