INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
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. | 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.
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. | 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.
Args:
client: an AdWordsClient instance.
Returns:
a suds.sudsobject.Object representation of the created 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.
Args:
client: an AdWordsClient instance.
budget: a suds.sudsobject.Object representation of a created budget.
Returns:
An integer campaign ID. | 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.
Args:
client: an AdWordsClient instance.
campaign_id: an integer campaign ID.
Returns:
An integer ad group ID. | 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.
Args:
client: an AdwordsClient instance.
ad_group_id: an integer ID of the ad group in which the DSA is added. | 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.
Args:
client: an AdWordsClient instance.
ad_group_id: an integer ID of the ad group the criteria is being added to. | 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.
Args:
client: An AdWordsClient instance.
url: The image URL.
Returns:
The ID of the uploaded image. | 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.
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. | 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.
In addition to the required_client_values argument, the yaml file must supply
the keys used to create OAuth2 credentials. It may also optionally set proxy
configurations.
Args:
yaml_doc: the yaml document whose keys should be used.
... | 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.
In addition to the required_client_values argument, the yaml file must supply
the keys used to create OAuth2 credentials. It may also optionally set proxy
configurations.
Args:
path: A path string to the yaml document whose keys should... | 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.
Args:
product_yaml_key: a string key identifying the product being configured.
product_data: a dict containing the configurations for a given product.
proxy_config: a ProxyConfig instance.
Returns:
An instantiated GoogleOAuth2C... | 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.
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:
If there is a proxy to configure in proxy_config, this will re... | 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.
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 dictionaries and lists/tuples
are recursively packed. Mutable types ... | 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.
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.
factory: The suds.client.Factory object which can create in... | 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.
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.
Args:
utility_name: A str specifying the 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.
Args:
document: A suds.sax.element.Element instance containing the API request.
Returns:
A dict mapping logging field names to their corresponding value. | 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.
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 corresponding value. | 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.
Args:
cafile: A str identifying the resolved path to the cafile. If not set,
this will use the system default cafile.
disable_ssl_certificate_validation: A boolean indicating whether
certificate verification is disabled. For security pur... | 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.
Returns:
A list of urllib2.BaseHandler subclasses to be used when making calls
with proxy. | 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.
Returns:
A list of handlers to be installed to the OpenerDirector used by suds. | 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.
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 XML for the 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.
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 XML for the 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.
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. | 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.
Args:
soap_headers: A SOAP element for the SOAP headers.
http_headers: A dictionary for the http headers. | 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.
Args:
method_name: The name of the method to search.
Returns:
True if the method is in the WSDL, otherwise False. | 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.
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. | 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.
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 options dict for the SOAP binding.
Returns:
A tuple of the envelo... | 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.
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. | 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.
Args:
method_name: The name of the method.
Returns:
True if the method is in the wsdl, otherwise False. | 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.
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 complex objects which include
inherited types.
Args:
method_nam... | 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.
Args:
s: A string with the data to test.
Returns:
True if s is base64, else False. | 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.
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 is only necessary for batch job service.
Returns:
An ins... | 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.
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 any
namespace. | 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.
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 hydrate the type with.
set_type_attrs: A boolean indicating whether or not attributes that end
... | 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.
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. | 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.
Args:
node: The node we're displaying the children of.
children: Children of the parent node.
level: How deep in the tree we are. | 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.
Args:
inventory_service: An instance of the InventoryService.
Returns:
A list containing 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.
Args:
root_ad_unit: The root ad unit to begin from.
all_ad_units: A list containing all ad units. | 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... |
Create a campaign group.
Args:
client: an AdWordsClient instance.
Returns:
The integer ID of the created 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.
Args:
client: an AdWordsClient instance.
campaign_group_id: an integer ID for the campaign group.
campaign_ids: a list of integer IDs for campaigns. | 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.
Args:
client: an AdWordsClient instance.
campaign_group_id: an integer ID 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.
Args:
service_name: A string identifying which Ad Manager service to create a
service client for.
[optional]
version: A string identifying the Ad Manager version to connect to. This
defaults to what is currently the latest versio... | 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.
This is a convenience method. It is functionally identical to calling
DataDownloader(ad_manager_client, version, server)
Args:
[optional]
version: A string identifying the Ad Manager version to connect to.
This defaults... | 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.
Args:
create_method: The SOAP library specific method used to instantiate SOAP
objects.
Returns:
A SOAP object containing the headers. | 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.
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 Manager-specific logic for SOAP,
... | 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.
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 Manager SOAP. | 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.
Args:
d: A dictionary of variable names to python types.
version: A string identifying the Ad Manager version the values object
is compatible with. This defaults to what is currently the latest
version. This will be updated i... | 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.
Args:
value: A python value.
version: A string identifying the Ad Manager version the value object
is compatible with. This defaults to what is currently the latest
version. This will be updated in future releases to point to... | 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.
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.
Raises:
An AdManagerReportError if the... | 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.
The report job must be completed before calling this function.
Args:
report_job_id: The ID of the report job to wait for, as a string.
export_format: The export format for the report file, as a string.
outfile: A writeable, file-like object to w... | 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.
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 SOAP values to bind
to the pql_query.
Returns:
... | 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.
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.
[optional]
values: A dict of python objects or a list of raw SOAP values to bi... | 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.
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. | 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).
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 output the results (csv or in
memory)
values... | 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.
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 of the date time value uniform to
ReportService. | 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.
Args:
client: an instantiated AdWordsClient used to retrieve the BatchJob.
Returns:
The new BatchJob created by the request. | 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.
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
associated with each provided 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.
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
checked to determine whether it has been canceled. | 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.
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. | 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.
Args:
client: an instantiated AdWordsClient used to poll the BatchJob.
batch_job_id: a long identifying the BatchJob to be polled.
max_poll_attempts: an int defining the number of times the BatchJob will be
checked to determine whether it has... | 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.
Args:
batch_job_helper: a BatchJobHelper instance.
response_xml: a string containing a response from the BatchJobService. | 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.
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 to the AdGroup when it is created. | 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.
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. | 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.
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: str Primary serving target the campaign's ads.
budget: str a budget amount (in micros) to use. | 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.
Returns:
list List of ManagedCustomer data objects. | 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.
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 List of AdGroup data objects. | 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.
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. | 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.
Args:
client_customer_id: str Client Customer Id used to retrieve Campaigns.
Returns:
list List of Campaign data objects. | 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.
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 value for the microAmount field.
delivery_method: str New value for the deliveryMethod field. | 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.
Args:
client: an AdWordsClient instance.
feed_items: the list of all Feed Items.
campaign_feed: the original Campaign Feed.
feed_item_ids: the Ids of the feed items for which extension settings should
be created.
platform_restriction... | 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.
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. | 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.
Args:
client: an AdWordsClient instance.
campaign_feed: the campaign feed to delete. | 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.
Args:
client: an AdWordsClient instance.
feed_item_ids: a list of Feed Item Ids.
feed: the Feed containing the given Feed Item Ids. | 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.
Args:
client: an AdWordsClient instance.
feed: a Campaign Feed.
placeholder_type: the Placeholder Type.
Returns:
A list of Feed Item Ids. | 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.
Args:
client: an AdWordsClient instance.
Returns:
A list containing 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.
Args:
client: an AdWordsClient instance.
feed: the Feed we are retrieving Feed Items from.
Returns:
The Feed Items associated with the 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.
Args:
campaign_feed: the Campaign Feed we are retrieving Feed Item Ids from.
Returns:
A list of Feed Item IDs. | 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.
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 Mapping. | 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.
Args:
campaign_feed: the Campaign Feed we are retrieving Platform Restrictons for.
Returns:
The Platform Restrictions for the given 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... |
Gets the sitelinks from a feed.
Args:
client: an AdWordsClient instance.
feed: the feed used to retrieve sitelinks.
Returns:
A dictionary mapping the feed item ID to SiteLinkFromFeed. | def GetSitelinksFromFeed(client, feed):
"""Gets the sitelinks from a feed.
Args:
client: an AdWordsClient instance.
feed: the feed used to retrieve sitelinks.
Returns:
A dictionary mapping the feed item ID to SiteLinkFromFeed.
"""
# Retrieve the feed's attribute mapping.
feed_mappings = GetFee... |
Gets the version from googleads/common.py.
We can't import this directly because new users would get ImportErrors on our
third party dependencies.
Returns:
The version of the library. | def GetVersion():
"""Gets the version from googleads/common.py.
We can't import this directly because new users would get ImportErrors on our
third party dependencies.
Returns:
The version of the library.
"""
with open(os.path.join('googleads', 'common.py')) as versions_file:
source = versions_fil... |
Builds the operations adding a Keyword Criterion to each AdGroup.
Args:
adgroup_operations: a list containing the operations that will add AdGroups.
number_of_keywords: an int defining the number of Keywords to be created.
Returns:
a list containing the operations that will create a new Keyword Criter... | def BuildAdGroupCriterionOperations(adgroup_operations, number_of_keywords=1):
"""Builds the operations adding a Keyword Criterion to each AdGroup.
Args:
adgroup_operations: a list containing the operations that will add AdGroups.
number_of_keywords: an int defining the number of Keywords to be created.
... |
Builds the operations adding desired number of AdGroups to given Campaigns.
Note: When the AdGroups are created, they will have a different Id than those
generated here as a temporary Id. This is just used to identify them in the
BatchJobService.
Args:
batch_job_helper: a BatchJobHelper instance.
camp... | def BuildAdGroupOperations(batch_job_helper,
campaign_operations, number_of_adgroups=1):
"""Builds the operations adding desired number of AdGroups to given Campaigns.
Note: When the AdGroups are created, they will have a different Id than those
generated here as a temporary Id. This i... |
Builds the operations needed to create a new Campaign.
Note: When the Campaigns are created, they will have a different Id than those
generated here as a temporary Id. This is just used to identify them in the
BatchJobService.
Args:
batch_job_helper: a BatchJobHelper instance.
budget_operations: a lis... | def BuildCampaignOperations(batch_job_helper,
budget_operations, number_of_campaigns=1):
"""Builds the operations needed to create a new Campaign.
Note: When the Campaigns are created, they will have a different Id than those
generated here as a temporary Id. This is just used to iden... |
Creates an image and uploads it to the server.
Args:
media_service: a SudsServiceProxy instance for AdWords's MediaService.
opener: an OpenerDirector instance.
url: a str URL used to load image data.
Returns:
The image that was successfully uploaded. | def _CreateImage(media_service, opener, url):
"""Creates an image and uploads it to the server.
Args:
media_service: a SudsServiceProxy instance for AdWords's MediaService.
opener: an OpenerDirector instance.
url: a str URL used to load image data.
Returns:
The image that was successfully upload... |
Creates settings for dynamic display ad.
Args:
media_service: a SudsServiceProxy instance for AdWords's MediaService.
opener: an OpenerDirector instance.
Returns:
The dynamic display ad settings. | def _CreateDynamicDisplayAdSettings(media_service, opener):
"""Creates settings for dynamic display ad.
Args:
media_service: a SudsServiceProxy instance for AdWords's MediaService.
opener: an OpenerDirector instance.
Returns:
The dynamic display ad settings.
"""
image = _CreateImage(media_servic... |
Creates a budget and returns its budgetId.
Args:
client: An AdWordsClient instance.
Returns:
An int budgetId for the created Budget. | def CreateBudget(client):
"""Creates a budget and returns its budgetId.
Args:
client: An AdWordsClient instance.
Returns:
An int budgetId for the created Budget.
"""
budget_service = client.GetService('BudgetService', version='v201809')
# Create a budget.
budget = {
'name': 'Interplanetar... |
Sets targeting criteria for the given campaign.
Args:
client: An AdWordsClient instance.
campaign: A suds object representing the campaign we wish to attach
targeting criteria. | def SetCampaignTargetingCriteria(client, campaign):
"""Sets targeting criteria for the given campaign.
Args:
client: An AdWordsClient instance.
campaign: A suds object representing the campaign we wish to attach
targeting criteria.
"""
campaign_criterion_service = client.GetService('CampaignCrite... |
Displays an account tree.
Args:
account: dict The account to display.
accounts: dict Map from customerId to account.
links: dict Map from customerId to child links.
depth: int Depth of the current account in the tree. | def DisplayAccountTree(account, accounts, links, depth=0):
"""Displays an account tree.
Args:
account: dict The account to display.
accounts: dict Map from customerId to account.
links: dict Map from customerId to child links.
depth: int Depth of the current account in the tree.
"""
prefix = '-... |
Handle get request. | def get(self):
"""Handle get request."""
try:
app_user = InitUser()
if (app_user.client_id and app_user.client_secret and
app_user.adwords_manager_cid and app_user.developer_token and
app_user.refresh_token):
self.redirect('/showAccounts')
else:
self.redire... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.