INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
A simple convenience utility for adding months to a given start date. | def AddMonths(start_date, months):
"""A simple convenience utility for adding months to a given start date.
This increments the months by adding the number of days in the current month
to the current month, for each month.
Args:
start_date: date The date months are being added to.
months: int The numb... |
Displays mean average cpc position clicks and total cost for estimate. | def DisplayEstimate(message, min_estimate, max_estimate):
"""Displays mean average cpc, position, clicks, and total cost for estimate.
Args:
message: str message to display for the given estimate.
min_estimate: sudsobject containing a minimum estimate from the
TrafficEstimatorService response.
ma... |
Builds a client config dictionary used in the OAuth 2. 0 flow. | def Build(self):
"""Builds a client config dictionary used in the OAuth 2.0 flow."""
if all((self.client_type, self.client_id, self.client_secret,
self.auth_uri, self.token_uri)):
client_config = {
self.client_type: {
'client_id': self.client_id,
'client_s... |
Format a SOAP DateTime object for printing. | def FormatSOAPDateTime(value):
"""Format a SOAP DateTime object for printing.
Args:
value: The DateTime object to format.
Returns:
A string representing the value.
"""
value_date = value['date']
return '%s-%s-%s %s:%s:%s (%s)' % (
value_date['year'], value_date['month'], value_date['day'],
... |
Calculate forecast percentage stats. | def CalculateForecastStats(matched, available, possible=None):
"""Calculate forecast percentage stats.
Args:
matched: The number of matched impressions.
available: The number of available impressions.
possible: The optional number of possible impressions.
Returns:
The percentage of impressions t... |
Creates a shopping campaign with the given budget and merchant IDs. | def CreateShoppingCampaign(client, budget_id, merchant_id):
"""Creates a shopping campaign with the given budget and merchant IDs.
Args:
client: an AdWordsClient instance.
budget_id: the str ID of the budget to be associated with the shopping
campaign.
merchant_id: the str ID of the merchant acco... |
Creates an AdGroup for the given shopping campaign ID. | def CreateAdGroup(client, campaign_id):
"""Creates an AdGroup for the given shopping campaign ID.
Args:
client: an AdWordsClient instance.
campaign_id: the str ID of a shopping campaign.
Returns:
The created AdGroup as a sudsobject.
"""
ad_group_service = client.GetService('AdGroupService', 'v20... |
Creates a showcase add for the given AdGroup with the given images. | def CreateShowcaseAd(client, adgroup, expanded_image_filepath,
collapsed_image_filepath):
"""Creates a showcase add for the given AdGroup with the given images.
Args:
client: an AdWordsClient instance.
adgroup: a dict or suds object defining an AdGroup for a Shopping Campaign.
expa... |
Uploads a. jpg image with the given filepath via the AdWords MediaService. | def UploadImage(client, filepath):
"""Uploads a .jpg image with the given filepath via the AdWords MediaService.
Args:
client: an AdWordsClient instance.
filepath: a str filepath to the .jpg file to be uploaded.
Returns:
The created Image as a sudsobject.
"""
media_service = client.GetService('M... |
Creates a ProductPartition tree for the given AdGroup ID. | def CreateProductPartition(client, adgroup_id):
"""Creates a ProductPartition tree for the given AdGroup ID.
Args:
client: an AdWordsClient instance.
adgroup_id: a str AdGroup ID.
Returns:
The ProductPartition tree as a sudsobject.
"""
ad_group_criterion_service = client.GetService('AdGroupCrite... |
Creates a subdivision node. | def CreateSubdivision(self, parent=None, value=None):
"""Creates a subdivision node.
Args:
parent: The node that should be this node's parent.
value: The value being partitioned on.
Returns:
A new subdivision node.
"""
division = {
'xsi_type': 'ProductPartition',
'... |
Creates a unit node. | def CreateUnit(self, parent=None, value=None, bid_amount=None):
"""Creates a unit node.
Args:
parent: The node that should be this node's parent.
value: The value being partitioned on.
bid_amount: The amount to bid for matching products, in micros.
Returns:
A new unit node.
"""
... |
Retrieve and display the access and refresh token. | def main(client_id, client_secret, scopes):
"""Retrieve and display the access and refresh token."""
client_config = ClientConfigBuilder(
client_type=ClientConfigBuilder.CLIENT_TYPE_WEB, client_id=client_id,
client_secret=client_secret)
flow = InstalledAppFlow.from_client_config(
client_config.... |
Handle post request. | def post(self):
"""Handle post request."""
client_customer_id = self.request.get('clientCustomerId')
campaign_id = self.request.get('campaignId')
if not client_customer_id or not campaign_id:
self.redirect('/')
else:
self.redirect('/showAdGroups?clientCustomerId=%s&campaignId=%s'
... |
Handle get request. | def get(self):
"""Handle get request."""
template_values = {
'back_url': '/',
'back_msg': 'View Accounts',
'logout_url': users.create_logout_url('/'),
'user_nickname': users.get_current_user().nickname()
}
try:
try:
app_user = InitUser()
template_va... |
Creates the budget. | def _CreateBudget(client):
"""Creates the budget.
Args:
client: an AdWordsClient instance.
Returns:
a suds.sudsobject.Object representation of the created budget.
"""
budget_service = client.GetService('BudgetService', version='v201809')
# Create the campaign budget
operation = {
'operand... |
Creates the campaign. | def _CreateCampaign(client, budget):
"""Creates the campaign.
Args:
client: an AdWordsClient instance.
budget: a suds.sudsobject.Object representation of a created budget.
Returns:
An integer campaign ID.
"""
campaign_service = client.GetService('CampaignService')
operations = [{
'opera... |
Creates an ad group. | def _CreateAdGroup(client, campaign_id):
"""Creates an ad group.
Args:
client: an AdWordsClient instance.
campaign_id: an integer campaign ID.
Returns:
An integer ad group ID.
"""
ad_group_service = client.GetService('AdGroupService')
operations = [{
'operator': 'ADD',
'operand': ... |
Creates the expanded Dynamic Search Ad. | def _CreateExpandedDSA(client, ad_group_id):
"""Creates the expanded Dynamic Search Ad.
Args:
client: an AdwordsClient instance.
ad_group_id: an integer ID of the ad group in which the DSA is added.
"""
# Get the AdGroupAdService.
ad_group_ad_service = client.GetService('AdGroupAdService')
# Creat... |
Adds a web page criterion to target Dynamic Search Ads. | def _AddWebPageCriteria(client, ad_group_id):
"""Adds a web page criterion to target Dynamic Search Ads.
Args:
client: an AdWordsClient instance.
ad_group_id: an integer ID of the ad group the criteria is being added to.
"""
ad_group_criterion_service = client.GetService('AdGroupCriterionService',
... |
Uploads the image from the specified url. | def UploadImageAsset(client, url):
"""Uploads the image from the specified url.
Args:
client: An AdWordsClient instance.
url: The image URL.
Returns:
The ID of the uploaded image.
"""
# Initialize appropriate service.
asset_service = client.GetService('AssetService', version='v201809')
# Do... |
Generates a library signature suitable for a user agent field. | def GenerateLibSig(short_name):
"""Generates a library signature suitable for a user agent field.
Args:
short_name: The short, product-specific string name for the library.
Returns:
A library signature string to append to user-supplied user-agent value.
"""
with _UTILITY_LOCK:
utilities_used = ',... |
Loads the data necessary for instantiating a client from file storage. | def LoadFromString(yaml_doc, product_yaml_key, required_client_values,
optional_product_values):
"""Loads the data necessary for instantiating a client from file storage.
In addition to the required_client_values argument, the yaml file must supply
the keys used to create OAuth2 credentials. I... |
Loads the data necessary for instantiating a client from file storage. | def LoadFromStorage(path, product_yaml_key, required_client_values,
optional_product_values):
"""Loads the data necessary for instantiating a client from file storage.
In addition to the required_client_values argument, the yaml file must supply
the keys used to create OAuth2 credentials. It ... |
Generates an GoogleOAuth2Client subclass using the given product_data. | def _ExtractOAuth2Client(product_yaml_key, product_data, proxy_config):
"""Generates an GoogleOAuth2Client subclass using the given product_data.
Args:
product_yaml_key: a string key identifying the product being configured.
product_data: a dict containing the configurations for a given product.
proxy_... |
Returns an initialized ProxyConfig using the given proxy_config_data. | def _ExtractProxyConfig(product_yaml_key, proxy_config_data):
"""Returns an initialized ProxyConfig using the given proxy_config_data.
Args:
product_yaml_key: a string indicating the client being loaded.
proxy_config_data: a dict containing the contents of proxy_config from the
YAML file.
Returns:... |
Packs SOAP input into the format we want for suds. | def _PackForSuds(obj, factory, packer=None, version=None):
"""Packs SOAP input into the format we want for suds.
The main goal here is to pack dictionaries with an 'xsi_type' key into
objects. This allows dictionary syntax to be used even with complex types
extending other complex types. The contents of dictio... |
Recurses over a nested structure to look for changes in Suds objects. | def _RecurseOverObject(obj, factory, parent=None):
"""Recurses over a nested structure to look for changes in Suds objects.
Args:
obj: A parameter for a SOAP request field which is to be inspected and
will be packed for Suds if an xsi_type is specified, otherwise will be
left unaltered.
fac... |
Decorator that registers a class with the given utility name. | def RegisterUtility(utility_name, version_mapping=None):
"""Decorator that registers a class with the given utility name.
This will only register the utilities being used if the UtilityRegistry is
enabled. Note that only the utility class's public methods will cause the
utility name to be added to the registry... |
Extract logging fields from the request s suds. sax. element. Element. | def _ExtractRequestSummaryFields(document):
"""Extract logging fields from the request's suds.sax.element.Element.
Args:
document: A suds.sax.element.Element instance containing the API request.
Returns:
A dict mapping logging field names to their corresponding value.
"""
headers = document.childAtP... |
Extract logging fields from the response s suds. sax. document. Document. | def _ExtractResponseSummaryFields(document):
"""Extract logging fields from the response's suds.sax.document.Document.
Args:
document: A suds.sax.document.Document instance containing the parsed
API response for a given API request.
Returns:
A dict mapping logging field names to their correspondin... |
Creates a ssl. SSLContext with the given settings. | def _InitSSLContext(self, cafile=None,
disable_ssl_certificate_validation=False):
"""Creates a ssl.SSLContext with the given settings.
Args:
cafile: A str identifying the resolved path to the cafile. If not set,
this will use the system default cafile.
disable_ssl_cert... |
Retrieve the appropriate urllib2 handlers for the given configuration. | def GetHandlers(self):
"""Retrieve the appropriate urllib2 handlers for the given configuration.
Returns:
A list of urllib2.BaseHandler subclasses to be used when making calls
with proxy.
"""
handlers = []
if self.ssl_context:
handlers.append(urllib2.HTTPSHandler(context=self.ssl... |
Get a collection of urllib2 handlers to be installed in the opener. | def u2handlers(self):
"""Get a collection of urllib2 handlers to be installed in the opener.
Returns:
A list of handlers to be installed to the OpenerDirector used by suds.
"""
# Start with the default set of handlers.
return_handlers = suds.transport.http.HttpTransport.u2handlers(self)
r... |
Return an XML string representing a SOAP complex type. | def GetSoapXMLForComplexType(self, type_name, value):
"""Return an XML string representing a SOAP complex type.
Args:
type_name: The name of the type with namespace prefix if necessary.
value: A python dictionary to hydrate the type instance with.
Returns:
A string containing the SOAP XM... |
Return an XML string representing a SOAP complex type. | def GetSoapXMLForComplexType(self, type_name, value):
"""Return an XML string representing a SOAP complex type.
Args:
type_name: The name of the type with namespace prefix if necessary.
value: A python dictionary to hydrate the type instance with.
Returns:
A string containing the SOAP XM... |
Get the raw SOAP XML for a request. | def GetRequestXML(self, method, *args):
"""Get the raw SOAP XML for a request.
Args:
method: The method name.
*args: A list of arguments to be passed to the method.
Returns:
An element containing the raw XML that would be sent as the request.
"""
self.suds_client.set_options(nose... |
Set the headers for the underlying client. | def SetHeaders(self, soap_headers, http_headers):
"""Set the headers for the underlying client.
Args:
soap_headers: A SOAP element for the SOAP headers.
http_headers: A dictionary for the http headers.
"""
self.suds_client.set_options(soapheaders=soap_headers, headers=http_headers) |
Determine if the wsdl contains a method. | def _WsdlHasMethod(self, method_name):
"""Determine if the wsdl contains a method.
Args:
method_name: The name of the method to search.
Returns:
True if the method is in the WSDL, otherwise False.
"""
return method_name in self.suds_client.wsdl.services[0].ports[0].methods |
Create a method wrapping an invocation to the SOAP service. | def _CreateMethod(self, method_name):
"""Create a method wrapping an invocation to the SOAP service.
Args:
method_name: A string identifying the name of the SOAP method to call.
Returns:
A callable that can be used to make the desired SOAP request.
"""
soap_service_method = getattr(sel... |
Overriding the egress function to set our headers. | def egress(self, envelope, http_headers, operation, binding_options):
"""Overriding the egress function to set our headers.
Args:
envelope: An Element with the SOAP request data.
http_headers: A dict of the current http headers.
operation: The SoapOperation instance.
binding_options: An... |
Get the raw SOAP XML for a request. | def GetRequestXML(self, method, *args):
"""Get the raw SOAP XML for a request.
Args:
method: The method name.
*args: A list of arguments to be passed to the method.
Returns:
An element containing the raw XML that would be sent as the request.
"""
packed_args = self._PackArguments... |
Determine if a method is in the wsdl. | def _WsdlHasMethod(self, method_name):
"""Determine if a method is in the wsdl.
Args:
method_name: The name of the method.
Returns:
True if the method is in the wsdl, otherwise False.
"""
try:
self._method_bindings.get(method_name)
return True
except ValueError:
r... |
Return a string with the namespace of the service binding in the WSDL. | def _GetBindingNamespace(self):
"""Return a string with the namespace of the service binding in the WSDL."""
return (list(self.zeep_client.wsdl.bindings.itervalues())[0]
.port_name.namespace) |
Properly pack input dictionaries for zeep. | def _PackArguments(self, method_name, args, set_type_attrs=False):
"""Properly pack input dictionaries for zeep.
Pack a list of python dictionaries into XML objects. Dictionaries which
contain an 'xsi_type' entry are converted into that type instead of the
argument default. This allows creation of comp... |
An imperfect but decent method for determining if a string is base64. | def _IsBase64(cls, s):
"""An imperfect but decent method for determining if a string is base64.
Args:
s: A string with the data to test.
Returns:
True if s is base64, else False.
"""
try:
if base64.b64encode(base64.b64decode(s)).decode('utf-8') == s:
return True
excep... |
Recursive helper for PackArguments. | def _PackArgumentsHelper(self, elem, data, set_type_attrs):
"""Recursive helper for PackArguments.
Args:
elem: The element type we are creating.
data: The data to instantiate it with.
set_type_attrs: A boolean indicating whether or not attributes that end
in .Type should be set. This ... |
Searches all namespaces for a type by name. | def _DiscoverElementTypeFromLocalname(self, type_localname):
"""Searches all namespaces for a type by name.
Args:
type_localname: The name of the type.
Returns:
A fully qualified SOAP type with the specified name.
Raises:
A zeep.exceptions.LookupError if the type cannot be found in ... |
Initialize a SOAP element with specific data. | def _CreateComplexTypeFromData(
self, elem_type, type_is_override, data, set_type_attrs):
"""Initialize a SOAP element with specific data.
Args:
elem_type: The type of the element to create.
type_is_override: A boolean specifying if the type is being overridden.
data: The data to hydrat... |
Returns a dict with SOAP headers in the right format for zeep. | def _GetZeepFormattedSOAPHeaders(self):
"""Returns a dict with SOAP headers in the right format for zeep."""
headers = self._header_handler.GetSOAPHeaders(self.CreateSoapElementForType)
soap_headers = {'RequestHeader': headers}
return soap_headers |
Create a method wrapping an invocation to the SOAP service. | def _CreateMethod(self, method_name):
"""Create a method wrapping an invocation to the SOAP service.
Args:
method_name: A string identifying the name of the SOAP method to call.
Returns:
A callable that can be used to make the desired SOAP request.
"""
soap_service_method = self.zeep_c... |
Runs the example. | def main(client, adgroup_id):
"""Runs the example."""
adgroup_criterion_service = client.GetService(
'AdGroupCriterionService', version='v201809')
helper = ProductPartitionHelper(adgroup_id)
# The most trivial partition tree has only a unit node as the root, e.g.:
# helper.CreateUnit(bid_amount=100000... |
Recursively display a node and each of its children. | def DisplayTree(node, children, level=0):
"""Recursively display a node and each of its children.
Args:
node: The node we're displaying the children of.
children: Children of the parent node.
level: How deep in the tree we are.
"""
value = ''
node_type = ''
if 'caseValue' in node:
case_val... |
Download all ad units. | def get_all_ad_units(inventory_service):
"""Download all ad units.
Args:
inventory_service: An instance of the InventoryService.
Returns:
A list containing all ad units.
"""
# Create a statement to get all ad units.
statement = (ad_manager.StatementBuilder(version='v201811')
.OrderB... |
Display the ad units as a tree. | def display_hierarchy(root_ad_unit, all_ad_units):
"""Display the ad units as a tree.
Args:
root_ad_unit: The root ad unit to begin from.
all_ad_units: A list containing all ad units.
"""
# Create a dict mapping the ids of parents to lists of their children.
parent_id_to_children = collections.defaul... |
Recursive helper for displaying the hierarchy. | def display_hierarchy_helper(root, parent_id_to_children, depth):
"""Recursive helper for displaying the hierarchy.
Args:
root: The current root ad unit.
parent_id_to_children: The overall map of parent ids to children.
depth: The current depth.
"""
print '%s%s (%s)' % ('%s+--' % ('|'.join([' '] *... |
Create a campaign group. | def _CreateCampaignGroup(client):
"""Create a campaign group.
Args:
client: an AdWordsClient instance.
Returns:
The integer ID of the created campaign group.
"""
# Get the CampaignGroupService.
campaign_group_service = client.GetService('CampaignGroupService',
... |
Adds multiple campaigns to a campaign group. | def _AddCampaignsToGroup(client, campaign_group_id, campaign_ids):
"""Adds multiple campaigns to a campaign group.
Args:
client: an AdWordsClient instance.
campaign_group_id: an integer ID for the campaign group.
campaign_ids: a list of integer IDs for campaigns.
"""
# Get the CampaignService.
ca... |
Creates a performance target for the campaign group. | def _CreatePerformanceTarget(client, campaign_group_id):
"""Creates a performance target for the campaign group.
Args:
client: an AdWordsClient instance.
campaign_group_id: an integer ID for the campaign group.
"""
# Get the CampaignGroupPerformanceTargetService.
cgpt_service = client.GetService('Cam... |
Creates a service client for the given service. | def GetService(self, service_name, version=sorted(_SERVICE_MAP.keys())[-1],
server=None):
"""Creates a service client for the given service.
Args:
service_name: A string identifying which Ad Manager service to create a
service client for.
[optional]
version: A strin... |
Creates a downloader for Ad Manager reports and PQL result sets. | def GetDataDownloader(self, version=sorted(_SERVICE_MAP.keys())[-1],
server=None):
"""Creates a downloader for Ad Manager reports and PQL result sets.
This is a convenience method. It is functionally identical to calling
DataDownloader(ad_manager_client, version, server)
Args:
... |
Returns the SOAP headers required for request authorization. | def GetSOAPHeaders(self, create_method):
"""Returns the SOAP headers required for request authorization.
Args:
create_method: The SOAP library specific method used to instantiate SOAP
objects.
Returns:
A SOAP object containing the headers.
"""
header = create_method(self._SOAP_HE... |
Pack the given object using Ad Manager - specific logic. | def Pack(cls, obj, version):
"""Pack the given object using Ad Manager-specific logic.
Args:
obj: an object to be packed for SOAP using Ad Manager-specific logic, if
applicable.
version: the version of the current API, e.g. 'v201811'
Returns:
The given object packed with Ad Man... |
Returns dicts formatted for Ad Manager SOAP based on date/ datetime. | def AdManagerDateTimePacker(cls, value, version):
"""Returns dicts formatted for Ad Manager SOAP based on date/datetime.
Args:
value: A date or datetime object to be converted.
version: the version of the current API, e.g. 'v201811'
Returns:
The value object correctly represented for Ad ... |
Converts a dict of python types into a list of PQL types. | def GetQueryValuesFromDict(cls, d, version=sorted(_SERVICE_MAP.keys())[-1]):
"""Converts a dict of python types into a list of PQL types.
Args:
d: A dictionary of variable names to python types.
version: A string identifying the Ad Manager version the values object
is compatible with. Thi... |
Converts a single python value to its PQL representation. | def GetValueRepresentation(cls, value,
version=sorted(_SERVICE_MAP.keys())[-1]):
"""Converts a single python value to its PQL representation.
Args:
value: A python value.
version: A string identifying the Ad Manager version the value object
is compatible with.... |
Lazily initializes a report service client. | def _GetReportService(self):
"""Lazily initializes a report service client."""
if not self._report_service:
self._report_service = self._ad_manager_client.GetService(
'ReportService', self._version, self._server)
return self._report_service |
Lazily initializes a PQL service client. | def _GetPqlService(self):
"""Lazily initializes a PQL service client."""
if not self._pql_service:
self._pql_service = self._ad_manager_client.GetService(
'PublisherQueryLanguageService', self._version, self._server)
return self._pql_service |
Runs a report then waits ( blocks ) for the report to finish generating. | def WaitForReport(self, report_job):
"""Runs a report, then waits (blocks) for the report to finish generating.
Args:
report_job: The report job to wait for. This may be a dictionary or an
instance of the SOAP ReportJob class.
Returns:
The completed report job's ID as a string.
... |
Downloads report data and writes it to a file. | def DownloadReportToFile(self, report_job_id, export_format, outfile,
include_report_properties=False,
include_totals_row=None, use_gzip_compression=True):
"""Downloads report data and writes it to a file.
The report job must be completed before calling thi... |
Downloads the results of a PQL query to a list. | def DownloadPqlResultToList(self, pql_query, values=None):
"""Downloads the results of a PQL query to a list.
Args:
pql_query: str a statement filter to apply (the query should not include
the limit or the offset)
[optional]
values: A dict of python objects or a list of raw S... |
Downloads the results of a PQL query to CSV. | def DownloadPqlResultToCsv(self, pql_query, file_handle, values=None):
"""Downloads the results of a PQL query to CSV.
Args:
pql_query: str a statement filter to apply (the query should not include
the limit or the offset)
file_handle: file the file object to write to.
[optio... |
Sanitizes a field value from a Value object to a CSV suitable format. | def _ConvertValueForCsv(self, pql_value):
"""Sanitizes a field value from a Value object to a CSV suitable format.
Args:
pql_value: dict a dictionary containing the data for a single field of an
entity.
Returns:
str a CSV writer friendly value formatted by Value.Type.
"""
... |
Pages through a pql_query and performs an action ( output_function ). | def _PageThroughPqlSet(self, pql_query, output_function, values):
"""Pages through a pql_query and performs an action (output_function).
Args:
pql_query: str a statement filter to apply (the query should not include
the limit or the offset)
output_function: the function to call to ... |
Converts the PQL formatted response for a dateTime object. | def _ConvertDateTimeToOffset(self, date_time_value):
"""Converts the PQL formatted response for a dateTime object.
Output conforms to ISO 8061 format, e.g. 'YYYY-MM-DDTHH:MM:SSz.'
Args:
date_time_value: dict The date time value from the PQL response.
Returns:
str: A string representation ... |
Handle post request. | def post(self):
"""Handle post request."""
template_values = {
'back_url': '/showCredentials',
'back_msg': 'View Credentials',
'logout_url': users.create_logout_url('/'),
'user_nickname': users.get_current_user().nickname()
}
try:
UpdateUserCredentials(self.request.... |
Add a new BatchJob to upload operations to. | def AddBatchJob(client):
"""Add a new BatchJob to upload operations to.
Args:
client: an instantiated AdWordsClient used to retrieve the BatchJob.
Returns:
The new BatchJob created by the request.
"""
# Initialize appropriate service.
batch_job_service = client.GetService('BatchJobService', versio... |
Builds the operations adding a Keyword Criterion to each AdGroup. | def BuildAdGroupCriterionOperations(adgroup_id):
"""Builds the operations adding a Keyword Criterion to each AdGroup.
Args:
adgroup_id: an integer identifying an AdGroup to associate the keywords
with.
Returns:
a list containing the operations that will create a new Keyword Criterion
associate... |
Cancels the given BatchJob. | def CancelBatchJob(client, batch_job, max_poll_attempts=MAX_POLL_ATTEMPTS):
"""Cancels the given BatchJob.
Args:
client: an instantiated AdWordsClient used to cancel the BatchJob.
batch_job: a BatchJob to be canceled.
max_poll_attempts: an int defining the number of times the BatchJob will be
che... |
Retrieves the BatchJob with the given id. | def GetBatchJob(client, batch_job_id):
"""Retrieves the BatchJob with the given id.
Args:
client: an instantiated AdWordsClient used to retrieve the BatchJob.
batch_job_id: a long identifying the BatchJob to be retrieved.
Returns:
The BatchJob associated with the given id.
"""
batch_job_service =... |
Retrieves the downloadUrl when the BatchJob is complete. | def GetBatchJobDownloadUrlWhenReady(client, batch_job_id,
max_poll_attempts=MAX_POLL_ATTEMPTS):
"""Retrieves the downloadUrl when the BatchJob is complete.
Args:
client: an instantiated AdWordsClient used to poll the BatchJob.
batch_job_id: a long identifying the BatchJo... |
Prints the BatchJobService response. | def PrintResponse(batch_job_helper, response_xml):
"""Prints the BatchJobService response.
Args:
batch_job_helper: a BatchJobHelper instance.
response_xml: a string containing a response from the BatchJobService.
"""
response = batch_job_helper.ParseResponse(response_xml)
if 'rval' in response['muta... |
Create a new ad group. | def AddAdGroup(self, client_customer_id, campaign_id, name, status):
"""Create a new ad group.
Args:
client_customer_id: str Client Customer Id used to create the AdGroup.
campaign_id: str Id of the campaign to use.
name: str Name to assign to the AdGroup.
status: str Status to assign t... |
Create a new Budget with the given microAmount. | def AddBudget(self, client_customer_id, micro_amount):
"""Create a new Budget with the given microAmount.
Args:
client_customer_id: str Client Customer Id used to create Budget.
micro_amount: str The budget represented in micros.
Returns:
str BudgetId of the newly created Budget.
"""... |
Add a Campaign to the client account. | def AddCampaign(self, client_customer_id, campaign_name, ad_channel_type,
budget):
"""Add a Campaign to the client account.
Args:
client_customer_id: str Client Customer Id to use when creating Campaign.
campaign_name: str Name of the campaign to be added.
ad_channel_type: s... |
Return the client accounts associated with the user s manager account. | def GetAccounts(self):
"""Return the client accounts associated with the user's manager account.
Returns:
list List of ManagedCustomer data objects.
"""
selector = {
'fields': ['CustomerId', 'CanManageClients']
}
accounts = self.client.GetService('ManagedCustomerService').get(sel... |
Retrieves all AdGroups for the given campaign that haven t been removed. | def GetAdGroups(self, client_customer_id, campaign_id):
"""Retrieves all AdGroups for the given campaign that haven't been removed.
Args:
client_customer_id: str Client Customer Id being used in API request.
campaign_id: str id of the campaign for which to fetch ad groups.
Returns:
list ... |
Return a Budget with the associated budgetId. | def GetBudget(self, client_customer_id, budget_id):
"""Return a Budget with the associated budgetId.
Args:
client_customer_id: str Client Customer Id to which the budget belongs.
budget_id: str id of the budget we want to examine.
Returns:
Budget A Budget data object.
"""
self.cl... |
Returns a client account s Campaigns that haven t been removed. | def GetCampaigns(self, client_customer_id):
"""Returns a client account's Campaigns that haven't been removed.
Args:
client_customer_id: str Client Customer Id used to retrieve Campaigns.
Returns:
list List of Campaign data objects.
"""
self.client.SetClientCustomerId(client_customer_i... |
Update a Budget with the given budgetId. | def UpdateBudget(self, client_customer_id, budget_id, micro_amount,
delivery_method):
"""Update a Budget with the given budgetId.
Args:
client_customer_id: str Client Customer Id used to update Budget.
budget_id: str Id of the budget to be updated.
micro_amount: str New val... |
Creates the extension setting for a list of Feed Items. | def CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids,
platform_restrictions=None):
"""Creates the extension setting for a list of Feed Items.
Args:
client: an AdWordsClient instance.
feed_items: the list of all Feed Items.
campaign_feed: the original Ca... |
Creates a Sitelink Feed Item. | def CreateSitelinkFeedItem(feed_items, feed_item_id):
"""Creates a Sitelink Feed Item.
Args:
feed_items: a list of all Feed Items.
feed_item_id: the Id of a specific Feed Item for which a Sitelink Feed Item
should be created.
Returns:
The new Sitelink Feed Item.
"""
site_link_from_feed =... |
Deletes a campaign feed. | def DeleteCampaignFeed(client, campaign_feed):
"""Deletes a campaign feed.
Args:
client: an AdWordsClient instance.
campaign_feed: the campaign feed to delete.
"""
campaign_feed_service = client.GetService('CampaignFeedService', 'v201809')
operation = {
'operand': campaign_feed,
'operato... |
Deletes the old feed items for which extension settings have been created. | def DeleteOldFeedItems(client, feed_item_ids, feed):
"""Deletes the old feed items for which extension settings have been created.
Args:
client: an AdWordsClient instance.
feed_item_ids: a list of Feed Item Ids.
feed: the Feed containing the given Feed Item Ids.
"""
if not feed_item_ids:
return... |
Get a list of Feed Item Ids used by a campaign via a given Campaign Feed. | def GetCampaignFeeds(client, feed, placeholder_type):
"""Get a list of Feed Item Ids used by a campaign via a given Campaign Feed.
Args:
client: an AdWordsClient instance.
feed: a Campaign Feed.
placeholder_type: the Placeholder Type.
Returns:
A list of Feed Item Ids.
"""
campaign_feed_servi... |
Returns a list of all enabled Feeds. | def GetFeeds(client):
"""Returns a list of all enabled Feeds.
Args:
client: an AdWordsClient instance.
Returns:
A list containing all enabled Feeds.
"""
feed_service = client.GetService('FeedService', 'v201809')
feeds = []
more_pages = True
selector = {
'fields': ['Id', 'Name', 'Attrib... |
Returns the Feed Items for a given Feed. | def GetFeedItems(client, feed):
"""Returns the Feed Items for a given Feed.
Args:
client: an AdWordsClient instance.
feed: the Feed we are retrieving Feed Items from.
Returns:
The Feed Items associated with the given Feed.
"""
feed_item_service = client.GetService('FeedItemService', 'v201809')
... |
Gets the Feed Item Ids used by a campaign through a given Campaign Feed. | def GetFeedItemIdsForCampaign(campaign_feed):
"""Gets the Feed Item Ids used by a campaign through a given Campaign Feed.
Args:
campaign_feed: the Campaign Feed we are retrieving Feed Item Ids from.
Returns:
A list of Feed Item IDs.
"""
feed_item_ids = set()
try:
lhs_operand = campaign_feed['... |
Gets the Feed Mapping for a given Feed. | def GetFeedMapping(client, feed, placeholder_type):
"""Gets the Feed Mapping for a given Feed.
Args:
client: an AdWordsClient instance.
feed: the Feed we are retrieving the Feed Mapping for.
placeholder_type: the Placeholder Type we are looking for.
Returns:
A dictionary containing the Feed Mappi... |
Get the Platform Restrictions for a given Campaign Feed. | def GetPlatformRestrictions(campaign_feed):
"""Get the Platform Restrictions for a given Campaign Feed.
Args:
campaign_feed: the Campaign Feed we are retrieving Platform Restrictons for.
Returns:
The Platform Restrictions for the given feed.
"""
platform_restrictions = None
if campaign_feed['matc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.