diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index cb8bc514..a6b0bd37 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -13,8 +13,7 @@ Follow either of the two links above to access the appropriate CLA and instructi
- Sign a Contributor License Agreement (see above).
- Join the appropriate product discussion forum.
- AdWords API: https://developers.google.com/adwords/api/community/
- - DFP API: https://developers.google.com/doubleclick-publishers/community
- - DFA API: https://developers.google.com/doubleclick-advertisers/reporting/community
+ - Ad Manager API: https://developers.google.com/ad-manager/community
- Create an issue on the library issue tracker if there isn't one already. Use this issue to co-ordinate the changes with the library maintainer.
- Fork the library, make the changes and send a [pull request](https://help.github.com/articles/using-pull-requests).
- The library maintainer will work with you to review and apply the patch.
diff --git a/ChangeLog b/ChangeLog
index 005d9385..4362e400 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,500 @@
+33.0.0 -- 08/16/2022
+* Added support for Ad Manager v202208.
+* Removed support for Ad Manager v202108.
+* Removed examples for Ad Manager v202111.
+
+32.0.0 -- 05/17/2022
+* Added support for Ad Manager v202205.
+* Removed support for Ad Manager v202105.
+* Removed examples for Ad Manager v202108.
+
+31.0.0 -- 02/16/2022
+* The minimum supported version of Python is now 3.7.0.
+* Added support for Ad Manager v202202.
+* Removed support for Ad Manager v202102.
+* Removed examples for Ad Manager v202105.
+
+30.0.0 -- 11/16/2021
+* Added support for Ad Manager v202111.
+* Removed support for Ad Manager v202011.
+* Removed examples for Ad Manager v202102.
+
+29.0.0 -- 08/16/2021
+* Added support for Ad Manager v202108.
+* Removed support for Ad Manager v202008.
+* Removed examples for Ad Manager v202011.
+
+28.0.0 -- 05/11/2021
+* Added support for Ad Manager v202105.
+* Removed support for Ad Manager v202005.
+* Removed examples for Ad Manager v202008.
+
+27.0.0 -- 02/17/2021
+* Added support for Ad Manager v202102.
+* Removed support for Ad Manager v202002.
+* Removed examples for Ad Manager v202005.
+
+26.0.0 -- 11/10/2020
+* Added support for Ad Manager v202011.
+* Removed support for Ad Manager v201911.
+* Removed examples for Ad Manager v202002.
+
+25.0.0 -- 08/18/2020
+* Added support for Ad Manager v202008.
+* Removed support for Ad Manager v201908.
+* Removed examples for Ad Manager v201911.
+
+24.1.0 -- 07/13/2020
+* Added 'GoogleCredentialsClient' class to re-use an OAuth2 credentials object
+
+24.0.0 -- 05/12/2020
+* Added support for Ad Manager v202005.
+* Removed support for Ad Manager v201905.
+* Removed examples for Ad Manager v201908.
+
+23.0.1 -- 02/20/2020
+* Fixed name of 'CreativeReviewService'.
+
+23.0.0 -- 02/11/2020
+* Added support for Ad Manager v202002.
+* Removed support for Ad Manager v201902.
+* Removed examples for Ad Manager v201905.
+
+22.0.0 -- 11/05/2019
+* Added support for Ad Manager v201911.
+* Removed support for Ad Manager v201811.
+* Removed examples for Ad Manager v201902.
+
+21.0.0 -- 08/14/2019
+* Added support for Ad Manager v201908
+* Removed support for Ad Manager v201808
+* Removed examples for Ad Manager v201811
+* Updated all Ad Manager examples to reflect Sales Manager sunset
+
+20.0.0 -- 06/11/2019
+* Updated examples to be Python 3 compatible
+* Removed suds dependency leaving zeep as the only supported SOAP client
+
+19.0.1 -- 05/22/2019
+* Really removed examples for Ad Manager v201808
+
+19.0.0 -- 05/09/2019
+* Added support for Ad Manager v201905
+* Removed support for Ad Manager v201805
+* Removed examples for Ad Manager v201808
+
+18.1.0 -- 04/03/2018
+* Upgrade PyYAML to 5.1 >= 6.0
+* Update comment in get_all_images_and_videos examples
+
+18.0.0 -- 03/28/2019
+* Removed support for AdWords v201806
+
+17.0.0 -- 02/12/2019
+* Added support for Ad Manager v201902.
+* Removed support for Ad Manager v201802.
+* Removed examples for Ad Manager v201805.
+
+16.0.0 -- 01/29/2019
+* Removed support for AdWords v201802
+
+15.0.2 -- 01/08/2019
+* Updated PyYAML dependencies to >=4.2b1 for https://nvd.nist.gov/vuln/detail/CVE-2017-18342
+
+15.0.1 -- 11/16/2018
+* Added Smart Shopping ad example (v201809)
+
+15.0.0 -- 11/14/2018
+* Added support for v201811.
+* Removed support for v201711.
+* Removed examples for v201802.
+* Remove ContentMetadataKeyHierarchyService
+* Added version parameter to PQL utilities to account for statement
+ differences among API versions. This parameter defaults to the most recent
+ API version. If you update your Python client library but don't plan on
+ migrating to the newest API version, you might need to explicitly declare the
+ version for the PQL utility to use.
+
+14.1.0 -- 09/21/18
+* Added support and examples for AdWords v201809.
+* Resolved issues:
+- Issue 281: https://github.com/googleads/googleads-python-lib/issues/281
+
+14.0.0 -- 08/21/18
+* DFP rebranded to Google Ad Manager.
+* Google Ad Manager v201808 release.
+* Removed support for DFP v201708.
+* Removed examples for DFP v201711.
+
+13.0.0 -- 07/25/18
+* Removed support for AdWords v201710.
+
+12.2.0 -- 06/18/18
+* Fixed some DFP examples that would loop forever with Zeep.
+
+12.1.0 -- 06/06/18
+* Added support and examples for AdWords v201806.
+* Resolved issues:
+- Issue 282: https://github.com/googleads/googleads-python-lib/issues/282
+- Issue 288: https://github.com/googleads/googleads-python-lib/issues/288
+
+12.0.0 -- 05/15/18
+* Added support and examples for DFP v201805.
+* Removed support for DFP v201705.
+* Removed examples for DFP v201708.
+* Using the wrong cache type will now raise GoogleAdsValueError instead of ValueError.
+* Added support for setting custom HTTP headers.
+* Resolved issues:
+- Issue 246: https://github.com/googleads/googleads-python-lib/issues/246
+- Issue 262: https://github.com/googleads/googleads-python-lib/issues/262
+- Issue 273: https://github.com/googleads/googleads-python-lib/issues/273
+- Issue 250: https://github.com/googleads/googleads-python-lib/issues/250
+
+11.0.1 -- 04/06/18
+* Fixed bug related to creating types from services that
+ contain multiple schemas.
+* Fixed bug in README.md related to zeep caching.
+
+11.0.0 -- 03/21/18
+* Removed support and examples for AdWords v201705, and v201708.
+* The default SOAP backend is now zeep. If you encounter any issues,
+ please report them and use your googleads.yaml file to revert back
+ to suds.
+- Zeep logs to the googleads.soap channel.
+- When using zeep (the default), you no longer need to encode your
+ image assets to base64, this will be done automatically.
+* Sunset oauth2client, replaced with google-auth.
+ https://google-auth.readthedocs.io/en/latest/
+- Updated googleads.yaml to remove service_account_email configurations that
+ are no longer necessary.
+- Removed httplib2 dependency.
+- Added google-auth, google-auth-oauthlib, and requests as dependencies.
+- AdWords and DFP auth examples have been updated to use new OAuth 2.0
+ dependencies.
+* Fixed a bug in IncrementalUploadHelper where the specified server would be
+ lost in serialization/deserialization.
+* Breaking changes:
+* Connection faults are now raised as GoogleAdsSoapTransportError
+ instances instead of suds errors.
+- Soap faults are now raised as GoogleAdsServerFault instances instead of suds
+ errors.
+- GoogleServiceAccountClient no longer supports P12 key files.
+- GoogleServiceAccountClient's initializer arguments have been refactored;
+ `key_file` is now a required positional argument, `client_email` and
+ `private_key_password` have been removed.
+- Removed Proxy from common.py. When creating a ProxyConfig, you must now
+ provide the full URI for http_proxy and https_proxy rather than a Proxy
+ instance. For an example of what these would look like, see:
+ http://docs.python-requests.org/en/master/user/advanced/#proxies
+- The proxy_config used in googleads.yaml has been updated to better resemble
+ proxy configuration for the underlying HTTP library. The http_proxy and
+ https_proxy configurations have been removed, and replaced with http and
+ https. These take the full proxy URI as their value.
+- Removed proxy_info attribute from ProxyConfig.
+- Refactored proxy_option attribute in ProxyConfig, renamed to proxies.
+* Resolved issues:
+- Issue 251: https://github.com/googleads/googleads-python-lib/issues/251
+- Issue 254: https://github.com/googleads/googleads-python-lib/issues/254
+
+10.1.1 -- 03/16/18
+* Accepted PR #222, to improve AdWords App Engine sample.
+
+10.1.0 -- 03/01/18
+* Added support and examples for AdWords v201802.
+* Added new BuildOpener utility method to ProxyConfig, which returns an
+ OpenerDirector instance configured for the ProxyConfig settings.
+
+10.0.0 -- 02/13/18
+* Added support and examples for DFP v201802.
+* Removed support and examples for AdWords v201702.
+* Resolved issues:
+- Issue 229: https://github.com/googleads/googleads-python-lib/issues/229
+- Issue 236: https://github.com/googleads/googleads-python-lib/issues/236
+
+9.0.1 -- 12/22/17
+* Improved Python 3 compatibility of library and tests.
+* Fixed reported issue with the ProductPartitionHelper utility used in AdWords
+ shopping examples.
+
+9.0.0 -- 11/14/17
+* Added support and examples for DFP v201711
+* Removed support and examples for DFP v201611
+* DFP PQL queries can now accept simple python dicts for variable substitution.
+* Resolved issues:
+- Issue 230: https://github.com/googleads/googleads-python-lib/issues/230
+
+
+8.1.0 -- 10/11/17
+* Added support for AdWords v201710.
+* Resolved issues:
+- Issue 224: https://github.com/googleads/googleads-python-lib/issues/224
+- Issue 228: https://github.com/googleads/googleads-python-lib/issues/228
+
+8.0.0 -- 8/22/17
+* Removed support and examples for AdWords v201609.
+* Resolved issues:
+- Issue 219: https://github.com/googleads/googleads-python-lib/issues/219
+- Issue 220: https://github.com/googleads/googleads-python-lib/issues/220
+
+7.0.0 -- 8/15/17
+* Added support and examples for DFP v201708.
+* Removed support and examples for DFP v201608.
+
+6.1.0 -- 8/9/17:
+* Added support for AdWords v201708.
+
+6.0.0 -- 6/27/17:
+* Removed support for AdWords v201607.
+* Improved logging support. Can now specify logging configuration from the
+ configuration file.
+* Added new GoogleAccessTokenClient, a non-refreshable client that only requires
+ the access token.
+* Resolved issues:
+- Issue 84: https://github.com/googleads/googleads-python-lib/issues/84
+- Issue 171: https://github.com/googleads/googleads-python-lib/issues/171
+
+5.6.0 -- 6/01/17:
+* Added support for AdWords v201705.
+
+5.5.0 -- 5/23/17:
+* Added more expressive python utility to build DFP PQL statements.
+* Support building DFP SOAP entities with native python date/datetime objects.
+* Added support and examples for DFP v201705.
+* Removed support and examples for DFP v201605.
+
+5.4.0 -- 4/25/17:
+* Resolved issues:
+- Issue 200: https://github.com/googleads/googleads-python-lib/issues/200
+- Issue 196: https://github.com/googleads/googleads-python-lib/issues/196
+
+5.3.0 -- 3/20/17:
+* Removed support for AdWords v201605.
+* Removed examples for AdWords v201605.
+* Added support for the complete set of DFP report download options.
+* Resolved issues:
+- Issue 169: https://github.com/googleads/googleads-python-lib/issues/169
+
+5.2.0 -- 3/1/17:
+* Added support for AdWords v201702.
+* Resolved issues:
+- Issue 110: https://github.com/googleads/googleads-python-lib/issues/110
+- Issue 180: https://github.com/googleads/googleads-python-lib/issues/180
+
+5.1.0 -- 2/13/17:
+* Added support for DFP v201702.
+* Removed examples for DFP v201605.
+* Removed support for DFP v201602.
+* Resolved issues:
+- Issue 166: https://github.com/googleads/googleads-python-lib/issues/166
+- Issue 176: https://github.com/googleads/googleads-python-lib/issues/176
+ Issue 177: https://github.com/googleads/googleads-python-lib/issues/177
+
+5.0.0 -- 1/13/17:
+* BREAKING CHANGE: The underlying suds client now has cache enabled. By default,
+ suds uses FileCache which requires access to local file system and will break
+ users using Google App Engine. For more details on how to configure or disable
+ caching, see the README.
+* The library will now automatically apply a monkey patch to the suds-jurko
+ dependency on initialization that will modify the suds.transport.http module.
+ The patch modifies HttpTransport's send method such that it can detect and
+ decompress a gzip encoded SOAP body.
+* Added new "enable_compression" optional keyword argument for AdWordsClient and
+ DfpClient. If set True, the client will request gzip compression and
+ automatically decompress the SOAP body for you. For more details on this
+ feature, see:
+ https://developers.google.com/adwords/api/docs/guides/bestpractices?hl=en#use_compression
+* Resolved issues:
+ Issue 77: https://github.com/googleads/googleads-python-lib/issues/77
+ Issue 97: https://github.com/googleads/googleads-python-lib/issues/97
+* Resolved pull requests:
+ PR 79: https://github.com/googleads/googleads-python-lib/pull/79
+ PR 81: https://github.com/googleads/googleads-python-lib/pull/81
+ PR 91: https://github.com/googleads/googleads-python-lib/pull/91
+ PR 99: https://github.com/googleads/googleads-python-lib/pull/99
+
+4.8.0 -- 11/29/16:
+* Added support for DFP v201611.
+* Removed support for DFP v201508 and v201511.
+* Removed examples for DFP v201602.
+* Resolved issues:
+ Issue 138: https://github.com/googleads/googleads-python-lib/issues/138
+ Issue 147: https://github.com/googleads/googleads-python-lib/issues/147
+ Issue 152: https://github.com/googleads/googleads-python-lib/issues/152
+ Issue 158: https://github.com/googleads/googleads-python-lib/issues/158
+ Issue 162: https://github.com/googleads/googleads-python-lib/issues/162
+* Resolved Pull Requests:
+ PR 163: https://github.com/googleads/googleads-python-lib/pull/163
+
+4.7.0 -- 10/25/16:
+* Removed support for AdWords v201603.
+
+4.6.1 -- 9/30/16:
+* Added support for AdWords v201609.
+* The library now automatically applies filters to log output to sanitize its
+ contents of sensitive data. For more details on how to configure logging or
+ disable log filtering, see the README.
+* The library will now log warnings if it detects that it is being run with
+ Python versions below 2.7.9.
+
+4.5.1 -- 8/30/2016:
+* Resolved issue #148:
+ https://github.com/googleads/googleads-python-lib/issues/148
+
+4.5.0 -- 8/26/2016
+* AdWordsClient's initializer no longer requires the user_agent field. This
+ field is also now validated to ensure that it only contains ASCII characters.
+* Removed support and examples for AdWords v201601.
+* Removed upgrade_ad_url example for AdWords v201605 and v201607.
+
+4.4.0 -- 8/23/2016
+* Removed support for DFP v201505.
+* Added support for DFP v201608.
+* Removed examples for DFP v201508 and v201511.
+
+4.3.0 -- 7/29/2016
+* Added support for AdWords v201607.
+
+4.2.0 -- 6/13/2016
+* Removed support and examples for AdWords v201509.
+* The AdWords ReportDownloader now accepts a "client_customer_id" keyword
+ argument that overrides the default client customer ID.
+* For utilities such as the ReportDownloader or BatchJobHelper, data points
+ about usage are now sent in the user-agent of API requests by default. This
+ can be disabled with the new include_utilities_in_user_agent configuration in
+ the googleads.yaml file.
+* Added a new parallel_report_download.py example.
+* Resolved issues:
+ Issue #122: https://github.com/googleads/googleads-python-lib/issues/122
+ Issue #123: https://github.com/googleads/googleads-python-lib/issues/123
+
+4.1.0 -- 5/26/2016
+* Added support for AdWords v201605.
+* Added new use_raw_enum_values keyword argument to the AdWords ReportDownloader
+ utility.
+
+4.0.0 -- 5/17/2016
+* Add support for DFP v201605.
+* Removed examples for DFP v201505.
+* Removed support for DFP v201502.
+* Improved proxy support.
+* BREAKING CHANGE: The googleads.common.LoadFromStorage function has been
+ updated to accommodate the current proxy support. This will break users with
+ a proxy configured. Check out the changes in our sample googleads.yaml file
+ to see the new format.
+
+3.15.0 -- 4/11/2016
+* Removed support for AdWords v201506.
+* Resolved issues:
+ Issue #108: https://github.com/googleads/googleads-python-lib/issues/108
+ Issue #111: https://github.com/googleads/googleads-python-lib/issues/111
+
+3.14.0 -- 3/25/2016
+* Added support for AdWords v201603.
+* Resolved Issues:
+ Issue #105: https://github.com/googleads/googleads-python-lib/issues/105
+ Issue #106: https://github.com/googleads/googleads-python-lib/issues/106
+
+3.13.0 -- 2/23/2016
+* Added support for DFP v201602.
+* Removed support for DFP v201411.
+* Removed examples for DFP v201502.
+* The library now applies a temporary patch to the suds-jurko dependency that
+ resolves multiple issues. This patch will be removed when the suds-jurko
+ library publicly exposes its 0.7 release. Thanks to GitHub user adiharush for
+ suggesting the patch!
+* The LoadFromStorage function can now load credentials for either the
+ installed application or service account (.p12 files only) OAuth2 flows.
+* The googleads.yaml configuration file has been updated to reflect the changes
+ to the LoadFromStorage function.
+* Resolved Issues:
+ Issue #58: https://github.com/googleads/googleads-python-lib/issues/58
+ Issue #62: https://github.com/googleads/googleads-python-lib/issues/62
+ Issue #63: https://github.com/googleads/googleads-python-lib/issues/63
+ Issue #68: https://github.com/googleads/googleads-python-lib/issues/68
+ Issue #78: https://github.com/googleads/googleads-python-lib/issues/78
+
+3.12.0 -- 02/01/2016
+* Removed DoubleClick Ad Exchange content. This API has been sunset.
+* Added support for AdWords v201601.
+* Updated the AdWords account_management get_account_hierarchy.py example to
+ properly handle the case where ManagedCustomerService.get returns multiple
+ pages of results.
+* Refactored AdWords upload_offline_conversions.py example, moved to
+ remarketing.
+* Refactored AdWords add_complete_campaigns_using_batch_job.py example, moved to
+ campaign_management.
+* The AdWords BatchJobHelper and IncrementalUploadHelper utilities now
+ initialize URLs for v201601 and up.
+* The AdWords IncrementalUploadHelper is now serializable.
+
+3.11.0 -- 11/24/2015
+* Removed support for AdWords v201502.
+* Added incremental upload support to BatchJobHelper.
+* Added the add_keywords_using_incremental_batch_job.py to advanced_operations
+ examples.
+* Moved add_complete_campaigns_using_batch_job.py to advanced_operations.
+* The BatchJobHelper can now be used to parse the BatchJob response. Examples
+ have been updated to demonstrate this.
+* The xmltodict library has been added as a new dependency.
+* Added option to set additional scopes in generate_refresh_token.py for
+ AdWords and DFP.
+
+3.10.0 - 11/17/2015
+* Removed support for DFP v201405 and v201408.
+* Removed examples for v201411.
+* Added support for DFP v201511.
+
+3.9.0 - 10/23/2015
+* The AdWords BatchJobHelper has been updated and added to the core library.
+* Updates to add_complete_campaigns_using_batch_job.py example.
+* Fixed issue #85.
+
+3.8.1 - 10/19/2015
+* Added BatchJobService example for AdWords v201509.
+* Removed GeoLocationService from AdWords v201509 because it isn't available
+ in this version.
+
+3.8.0 - 10/7/2015
+* Removed DFA from GoogleAds SOAP Client Library.
+* Added support for AdWords v201509.
+* Replaced references to MCC accounts with AdWords manager accounts.
+* Added upload_media_bundle as a new misc example for AdWords v201509.
+* Added add_html5_ad as a new advanced_operations example for AdWords v201509.
+* Added add_crm_based_user_list as a new remarketing example for AdWords
+ v201509.
+
+3.7.1 - 9/4/2015
+* Fixed issue #68.
+* Updated the get_keywords AdWords sample.
+
+3.7.0 - 8/20/2015
+* Update ServiceAccount constructor to open p12 file in binary mode.
+* Added support for v201508 for the Doubleclick for Publishers Client Library.
+* Removed support for v201403 for the Doubleclick for Publishers Client Library.
+
+3.6.0 - 7/31/2015
+* Removed support for AdWords v201409.
+* Removed examples for AdWords v201409.
+
+3.5.0 - 6/26/2015
+* Added support for v201506 of the AdWords Client Library.
+* Reporting parameters in ReportDownloader utility now in **kwargs.
+* Added new "include_zero_impressions" reporting parameter as keyword argument
+ for ReportDownloader utility methods.
+
+3.4.1 - 5/22/2015
+* Fixed issue #55
+* Fixed issue #57
+
+3.4.0 - 5/19/2015
+* Added support for DFP v201505.
+* Removed examples for DFP v201405.
+
+3.3.0 - 3/25/2015
+* Fixed issue #47.
+* Removed support for AdWords v201406.
+* Removed examples for AdWords v201406.
+
3.2.0 - 3/12/2015
* Added support for v201502 of the AdWords Client Library.
* Removed CampaignAdExtensionService (from v201502).
@@ -94,7 +591,7 @@
Library.
* Added CampaignSharedSetService, LabelService, SharedCriterionService, and
SharedSetService for AdWords.
-* Updated AdWords OAuth 2.0 scope.
+* Updated AdWords OAuth2 scope.
See: https://developers.google.com/adwords/api/docs/guides/authentication.
1.0.6 - 05/29/2014
diff --git a/README.md b/README.md
index 4b198efa..e8687f35 100644
--- a/README.md
+++ b/README.md
@@ -1,51 +1,84 @@
-#The googleads Python client library
-
+# The googleads Python client library
This client library simplifies accessing Google's SOAP Ads APIs - AdWords,
-DoubleClick Ad Exchange SOAP, DoubleClick for Advertisers, and DoubleClick for
-Publishers. The library provides easy ways to store your authentication and
-create SOAP web service clients. It also contains example code to help you get
-started integrating with our APIs.
+and DoubleClick for Publishers. The library provides easy ways to store your
+authentication and create SOAP web service clients. It also contains example
+code to help you get started integrating with our APIs.
+
+> **The Google AdWords API will [sunset on April 27, 2022](https://ads-developers.googleblog.com/2021/04/upgrade-to-google-ads-api-from-adwords.html).
+> Upgrade to the [Google Ads API](https://developers.google.com/google-ads/api/docs/client-libs).**
+
+## Getting started
+1. Download and install the library
+
+ *[setuptools](https://pypi.python.org/pypi/setuptools) is a pre-requisite
+ for installing the googleads library*
+
+ It is recommended that you install the library and its dependencies from
+ PyPI using [pip](https://pip.pypa.io/en/stable/installing/). This can be
+ accomplished with a single command:
+
+ `$ pip install googleads`
+
+ As an alternative, you can
+ [download the library as a tarball](https://pypi.python.org/pypi/googleads).
+ To start the installation, navigate to the directory that contains your
+ downloaded unzipped client library and run the "setup.py" script as follows:
+
+ `$ python setup.py build install`
+
+1. Copy the [googleads.yaml](https://github.com/googleads/googleads-python-lib/blob/master/googleads.yaml)
+ file to your home directory.
+
+ This will be used to store credentials and other settings that can be loaded
+ to initialize a client.
+
+1. Set up your OAuth2 credentials
+
+ The AdWords and DoubleClick for Publishers APIs use
+ [OAuth2](http://oauth.net/2/) as the authentication mechanism. Follow the
+ appropriate guide below based on your use case.
+
+ **If you're accessing an API using your own credentials...**
+
+ * [Using AdWords](https://github.com/googleads/googleads-python-lib/wiki/API-access-using-own-credentials-(installed-application-flow))
+ * [Using Ad Manager](https://github.com/googleads/googleads-python-lib/wiki/API-access-using-own-credentials-(server-to-server-flow))
+
+ **If you're accessing an API on behalf of clients...**
+ * [Developing a web application (AdWords or Ad Manager)](https://github.com/googleads/googleads-python-lib/wiki/API-access-on-behalf-of-your-clients-(web-flow))
-##How do I get started?
-####Installing the library
-Install or update the library from PyPI. If you're using pip, this is as easy
-as:
+#### Where can I find samples?
-`$ pip install [--upgrade] googleads`
+You can find code examples for the latest versions of AdWords or Ad Manager on the
+[releases](https://github.com/googleads/googleads-python-lib/releases) page.
-If you don't want to install directly from PyPI, you can download the library
-as a tarball and then install it manually. The download can be found here:
-https://pypi.python.org/pypi/googleads
-Navigate to the directory that contains your downloaded unzipped client
-library and run the "setup.py" script to install the "googleads"
-module.
+Alternatively, you can find [AdWords](https://github.com/googleads/googleads-python-lib/tree/master/examples/adwords)
+or [Ad Manager](https://github.com/googleads/googleads-python-lib/tree/master/examples/ad_manager)
+samples in the examples directory of this repository.
-`$ python setup.py build install`
+#### Where can I find the pydocs?
-You can find code examples in the git repo and in the library's releases within
-the examples folder.
+Our pydocs can be found [here](http://googleads.github.io/googleads-python-lib).
-####Where can I find the pydocs?
-Our pydocs are hosted at: http://googleads.github.io/googleads-python-lib
+#### Caching authentication information
-####Caching authentication information
It is possible to cache your API authentication information. The library
includes a sample file showing how to do this named `googleads.yaml`. Fill
-in the fields for the API you plan to use. The library's `LoadFromStorage`
-methods default to looking for a file with this name in your home directory,
-but you can pass in a path to any file with the correct yaml contents.
+in the fields for the API and features you plan to use. The library's
+`LoadFromStorage` methods default to looking for a file with this name in your
+home directory, but you can pass in a path to any file with the correct yaml
+contents.
```python
# Use the default location - your home directory:
adwords_client = adwords.AdWordsClient.LoadFromStorage()
# Alternatively, pass in the location of the file:
-dfp_client = dfp.DfpClient.LoadFromStorage('C:\My\Directory\googleads.yaml')
+ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage('C:\My\Directory\googleads.yaml')
```
-####How do I change the Client Customer Id at runtime?
+#### How do I change the Client Customer Id at runtime?
You can change the Client Customer Id with the following:
```
@@ -54,77 +87,98 @@ adwords_client.SetClientCustomerId('my_client_customer_id')
```
-##Where do I submit bug reports and/or feature requests?
+## Where do I submit bug reports and/or feature requests?
-Use the issue tracker at:
- https://github.com/googleads/googleads-python-lib/issues
+If you have issues directly related to the client library, use the [issue
+tracker](https://github.com/googleads/googleads-python-lib/issues).
-Make sure to subscribe to our Google Plus page for API change announcements and
-other news:
- https://plus.google.com/+GoogleAdsDevelopers
+If you have issues pertaining to a specific API, use the product support forums:
+* [AdWords](https://groups.google.com/forum/#!forum/adwords-api)
+* [Ad Manager](https://groups.google.com/forum/#!forum/google-doubleclick-for-publishers-api)
-##How do I log SOAP interactions?
-The library uses Python's built in logging framework. If you wish to log your
-SOAP interactions to stdout, you can do the following:
+
+## How do I log SOAP interactions?
+The library uses Python's built in logging framework. You can specify your
+configuration via the configuration file; see [googleads.yaml](https://github.com/googleads/googleads-python-lib/blob/master/googleads.yaml)
+for an example.
+
+Alternatively, you can manually specify your logging configuration. For example,
+if you want to log your SOAP interactions to stdout, and you are using the Zeep soap library, you
+can do the following:
```python
-logging.basicConfig(level=logging.INFO)
-logging.getLogger('suds.transport').setLevel(logging.DEBUG)
+logging.basicConfig(level=logging.INFO, format=googleads.util.LOGGER_FORMAT)
+logging.getLogger('googleads.soap').setLevel(logging.DEBUG)
```
If you wish to log to a file, you'll need to attach a log handler to this source
which is configured to write the output to a file.
-##I'm familiar with suds. Can I use suds features with this library?
-Yes, you can. The services returned by the `client.GetService()` functions all
-have a reference to the underlying suds client stored in the `suds_client`
-attribute. You can retrieve the client and use it in familiar ways:
+## How do I disable log filters?
+The zeep plugin used for logging strips sensitive data from its output. If you would like this data
+included in logs, you'll need to implement your own simple logging plugin. For example:
+```python
+class DangerousZeepLogger(zeep.Plugin):
+ def ingress(self, envelope, http_headers, operation):
+ logging.debug('Incoming response: \n%s', etree.tostring(envelope, pretty_print=True))
+ return envelope, http_headers
+
+ def egress(self, envelope, http_headers, operation, binding_options):
+ logging.debug('Incoming response: \n%s', etree.tostring(envelope, pretty_print=True))
+ return envelope, http_headers
+
+adwords_client.zeep_client.plugins.append(DangerousZeepLogger())
+```
+
+## How can I configure or disable caching?
+
+By default, clients are cached because reading and digesting the WSDL
+can be expensive. However, the default caching method requires permission to
+access a local file system that may not be available in certain hosting
+environments such as App Engine.
+
+You can pass an implementation of `zeep.cache.Base` to the `AdWordsClient` or
+`AdManagerClient` initializer to modify the default caching behavior.
+
+For example, configuring a different location and duration of the cache file with zeep
```python
-client = AdWordsClient.LoadFromStorage()
-campaign_service = client.GetService('CampaignService')
-suds_client = campaign_service.suds_client
-
-campaign = suds_client.factory.create('Campaign')
-# Set any attributes on the campaign object which you need.
-campaign.name = 'My Campaign'
-campaign.status = 'PAUSED'
-
-operation = suds_client.factory.create('CampaignOperation')
-operation.operator = 'ADD'
-operation.operand = campaign
-
-# The service object returned from the client.GetService() call accepts suds
-# objects and will set the SOAP and HTTP headers for you.
-campaign_service.mutate([operation])
-
-# Alternatively, if you wish to set the headers yourself, you can use the
-# suds_client.service directly.
-soap_header = suds_client.factory.create('SoapHeader')
-soap_header.clientCustomerId = client.client_customer_id
-soap_header.developerToken = client.developer_token
-soap_header.userAgent = client.user_agent
-
-suds_client.set_options(
- soapheaders=soap_header,
- headers=client.oauth2_client.CreateHttpHeader())
-
-suds_client.service.mutate([operation])
+doc_cache = zeep.cache.SqliteCache(path=cache_path)
+adwords_client = adwords.AdWordsClient(
+ developer_token, oauth2_client, user_agent,
+ client_customer_id=client_customer_id, cache=doc_cache)
```
+You can also disable caching in similar fashion with zeep
+```python
+adwords_client = adwords.AdWordsClient(
+ developer_token, oauth2_client, user_agent,
+ client_customer_id=client_customer_id,
+ cache=googleads.common.ZeepServiceProxy.NO_CACHE)
+```
+
+## Requirements
+
+### Python Versions
-##External Dependencies:
+This library only supports Python 3.7+.
+### External Dependencies:
- - oauthlib -- http://pypi.python.org/pypi/oauthlib/
- - suds-jurko -- http://pypi.python.org/pypi/suds-jurko/
+ - httplib2 -- https://pypi.python.org/pypi/httplib2/
+ - oauth2client -- https://pypi.python.org/pypi/oauth2client/
+ - pysocks -- https://pypi.python.org/pypi/PySocks/
- pytz -- https://pypi.python.org/pypi/pytz
- - pyYAML -- http://pypi.python.org/pypi/pyYAML/
- - mock -- http://pypi.python.org/pypi/mock
+ - pyYAML -- https://pypi.python.org/pypi/pyYAML/
+ - xmltodict -- https://pypi.python.org/pypi/xmltodict/
+ - zeep -- https://pypi.python.org/pypi/zeep
+ - mock -- https://pypi.python.org/pypi/mock
(only needed to run unit tests)
- pyfakefs -- https://pypi.python.org/pypi/pyfakefs
(only needed to run unit tests)
-##Authors:
- jdilallo@google.com (Joseph DiLallo)
+## Authors:
+ Mark Saniscalchi
+ David Wihl
+ Ben Karl
diff --git a/examples/ad_manager/authentication/create_ad_manager_client_with_access_token.py b/examples/ad_manager/authentication/create_ad_manager_client_with_access_token.py
new file mode 100755
index 00000000..74ecb010
--- /dev/null
+++ b/examples/ad_manager/authentication/create_ad_manager_client_with_access_token.py
@@ -0,0 +1,82 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Initializes an AdManagerClient using GoogleAccessTokenClient.
+
+Note that unlike clients initialized with GoogleRefreshTokenClient, those
+initialized with GoogleAccessTokenClient can't refresh.
+"""
+
+import argparse
+import datetime
+from googleads import ad_manager
+from googleads import oauth2
+import httplib2
+from oauth2client import client
+
+
+GOOGLE_OAUTH2_ENDPOINT = 'https://accounts.google.com/o/oauth2/token'
+USER_AGENT = 'INSERT_USER_AGENT_HERE'
+
+# OAuth2 credential information.
+DEFAULT_CLIENT_ID = 'INSERT_CLIENT_ID_HERE'
+DEFAULT_CLIENT_SECRET = 'INSERT_CLIENT_SECRET_HERE'
+DEFAULT_REFRESH_TOKEN = 'INSERT_REFRESH_TOKEN_HERE'
+
+# Ad Manager API information.
+DEFAULT_APPLICATION_NAME = 'INSERT_APPLICATION_NAME_HERE'
+
+parser = argparse.ArgumentParser(
+ description=('Creates an AdManagerClient using a GoogleAccessToken with an '
+ 'access token generated with the given credentials.'))
+parser.add_argument('--client_id', default=DEFAULT_CLIENT_ID,
+ help='Client Id retrieved from the Developer\'s Console.')
+parser.add_argument('--client_secret', default=DEFAULT_CLIENT_SECRET,
+ help='Client Secret retrieved from the Developer\'s '
+ 'Console.')
+parser.add_argument('--refresh_token', default=DEFAULT_REFRESH_TOKEN,
+ help='The refresh token used to generate an access token.')
+parser.add_argument('--application_name', default=DEFAULT_APPLICATION_NAME,
+ help='The application name for your Ad Manager account.')
+
+
+def main(access_token, token_expiry, application_name):
+ oauth2_client = oauth2.GoogleAccessTokenClient(access_token, token_expiry)
+
+ ad_manager_client = ad_manager.AdManagerClient(
+ oauth2_client, application_name)
+
+ networks = ad_manager_client.GetService('NetworkService').getAllNetworks()
+ for network in networks:
+ print('Network with network code "%s" and display name "%s" was found.'
+ % (network['networkCode'], network['displayName']))
+
+
+if __name__ == '__main__':
+ args = parser.parse_args()
+
+ # Retrieve a new access token for use in this example. In a production
+ # application, you may use a credential store to share access tokens for a
+ # given user across applications.
+ oauth2credentials = client.OAuth2Credentials(
+ None, args.client_id, args.client_secret, args.refresh_token,
+ datetime.datetime(1980, 1, 1, 12), GOOGLE_OAUTH2_ENDPOINT,
+ USER_AGENT)
+
+ oauth2credentials.refresh(httplib2.Http())
+
+ main(oauth2credentials.access_token, oauth2credentials.token_expiry,
+ args.application_name)
diff --git a/examples/ad_manager/authentication/create_ad_manager_client_with_refresh_token.py b/examples/ad_manager/authentication/create_ad_manager_client_with_refresh_token.py
new file mode 100755
index 00000000..5c3d0e10
--- /dev/null
+++ b/examples/ad_manager/authentication/create_ad_manager_client_with_refresh_token.py
@@ -0,0 +1,53 @@
+#!/usr/bin/env python
+#
+# Copyright 2014 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Initializes a AdManagerClient without using yaml-cached credentials.
+
+While our LoadFromStorage method provides a useful shortcut to instantiate a
+client if you regularly use just one set of credentials, production applications
+may need to swap out users. This example shows you how to create an OAuth2
+client and a AdManagerClient without relying on a yaml file.
+"""
+
+
+from googleads import ad_manager
+from googleads import oauth2
+
+# OAuth2 credential information. In a real application, you'd probably be
+# pulling these values from a credential storage.
+CLIENT_ID = 'INSERT_CLIENT_ID_HERE'
+CLIENT_SECRET = 'INSERT_CLIENT_SECRET_HERE'
+REFRESH_TOKEN = 'INSERT_REFRESH_TOKEN_HERE'
+
+# Ad Manager API information.
+APPLICATION_NAME = 'INSERT_APPLICATION_NAME_HERE'
+
+
+def main(client_id, client_secret, refresh_token, application_name):
+ oauth2_client = oauth2.GoogleRefreshTokenClient(
+ client_id, client_secret, refresh_token)
+
+ ad_manager_client = ad_manager.AdManagerClient(
+ oauth2_client, application_name)
+
+ networks = ad_manager_client.GetService('NetworkService').getAllNetworks()
+ for network in networks:
+ print('Network with network code "%s" and display name "%s" was found.'
+ % (network['networkCode'], network['displayName']))
+
+
+if __name__ == '__main__':
+ main(CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN, APPLICATION_NAME)
diff --git a/examples/ad_manager/authentication/create_ad_manager_client_with_service_account.py b/examples/ad_manager/authentication/create_ad_manager_client_with_service_account.py
new file mode 100755
index 00000000..de909fc3
--- /dev/null
+++ b/examples/ad_manager/authentication/create_ad_manager_client_with_service_account.py
@@ -0,0 +1,45 @@
+#!/usr/bin/env python
+#
+# Copyright 2014 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Initializes a AdManagerClient using a Service Account."""
+
+
+from googleads import ad_manager
+from googleads import oauth2
+
+# OAuth2 credential information. In a real application, you'd probably be
+# pulling these values from a credential storage.
+KEY_FILE = 'INSERT_KEY_FILE_PATH'
+
+# Ad Manager API information.
+APPLICATION_NAME = 'INSERT_APPLICATION_NAME_HERE'
+
+
+def main(key_file, application_name):
+ oauth2_client = oauth2.GoogleServiceAccountClient(
+ key_file, oauth2.GetAPIScope('ad_manager'))
+
+ ad_manager_client = ad_manager.AdManagerClient(
+ oauth2_client, application_name)
+
+ networks = ad_manager_client.GetService('NetworkService').getAllNetworks()
+ for network in networks:
+ print('Network with network code "%s" and display name "%s" was found.'
+ % (network['networkCode'], network['displayName']))
+
+
+if __name__ == '__main__':
+ main(KEY_FILE, APPLICATION_NAME)
diff --git a/examples/ad_manager/authentication/generate_refresh_token.py b/examples/ad_manager/authentication/generate_refresh_token.py
new file mode 100755
index 00000000..243f2410
--- /dev/null
+++ b/examples/ad_manager/authentication/generate_refresh_token.py
@@ -0,0 +1,121 @@
+#!/usr/bin/env python
+#
+# Copyright 2014 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Generates a refresh token for use with Ad Manager."""
+
+
+import argparse
+import sys
+
+from google_auth_oauthlib.flow import InstalledAppFlow
+from oauthlib.oauth2.rfc6749.errors import InvalidGrantError
+
+# Your OAuth2 Client ID and Secret. If you do not have an ID and Secret yet,
+# please go to https://console.developers.google.com and create a set.
+DEFAULT_CLIENT_ID = None
+DEFAULT_CLIENT_SECRET = None
+
+# The Ad Manager API OAuth2 scope.
+SCOPE = u'https://www.googleapis.com/auth/dfp'
+# The redirect URI set for the given Client ID. The redirect URI for Client ID
+# generated for an installed application will always have this value.
+_REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
+
+parser = argparse.ArgumentParser(description='Generates a refresh token with '
+ 'the provided credentials.')
+parser.add_argument('--client_id', default=DEFAULT_CLIENT_ID,
+ help='Client Id retrieved from the Developer\'s Console.')
+parser.add_argument('--client_secret', default=DEFAULT_CLIENT_SECRET,
+ help='Client Secret retrieved from the Developer\'s '
+ 'Console.')
+parser.add_argument('--additional_scopes', default=None,
+ help='Additional scopes to apply when generating the '
+ 'refresh token. Each scope should be separated by a comma.')
+
+
+class ClientConfigBuilder(object):
+ """Helper class used to build a client config dict used in the OAuth 2.0 flow.
+ """
+ _DEFAULT_AUTH_URI = 'https://accounts.google.com/o/oauth2/auth'
+ _DEFAULT_TOKEN_URI = 'https://accounts.google.com/o/oauth2/token'
+ CLIENT_TYPE_WEB = 'web'
+ CLIENT_TYPE_INSTALLED_APP = 'installed'
+
+ def __init__(self, client_type=None, client_id=None, client_secret=None,
+ auth_uri=_DEFAULT_AUTH_URI, token_uri=_DEFAULT_TOKEN_URI):
+ self.client_type = client_type
+ self.client_id = client_id
+ self.client_secret = client_secret
+ self.auth_uri = auth_uri
+ self.token_uri = token_uri
+
+ 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_secret': self.client_secret,
+ 'auth_uri': self.auth_uri,
+ 'token_uri': self.token_uri
+ }
+ }
+ else:
+ raise ValueError('Required field is missing.')
+
+ return client_config
+
+
+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.Build(), scopes=scopes)
+ # Note that from_client_config will not produce a flow with the
+ # redirect_uris (if any) set in the client_config. This must be set
+ # separately.
+ flow.redirect_uri = _REDIRECT_URI
+
+ auth_url, _ = flow.authorization_url(prompt='consent')
+
+ print('Log into the Google Account you use to access your Ad Manager account'
+ 'and go to the following URL: \n%s\n' % (auth_url))
+ print('After approving the token enter the verification code (if specified).')
+ code = input('Code: ').strip()
+
+ try:
+ flow.fetch_token(code=code)
+ except InvalidGrantError as ex:
+ print('Authentication has failed: %s' % ex)
+ sys.exit(1)
+
+ print('Access token: %s' % flow.credentials.token)
+ print('Refresh token: %s' % flow.credentials.refresh_token)
+
+
+if __name__ == '__main__':
+ args = parser.parse_args()
+ configured_scopes = [SCOPE]
+ if not (any([args.client_id, DEFAULT_CLIENT_ID]) and
+ any([args.client_secret, DEFAULT_CLIENT_SECRET])):
+ raise AttributeError('No client_id or client_secret specified.')
+ if args.additional_scopes:
+ configured_scopes.extend(args.additional_scopes.replace(' ', '').split(','))
+ main(args.client_id, args.client_secret, configured_scopes)
diff --git a/examples/ad_manager/data/README b/examples/ad_manager/data/README
new file mode 100644
index 00000000..d93b317c
--- /dev/null
+++ b/examples/ad_manager/data/README
@@ -0,0 +1 @@
+Data files used by the client library's examples.
diff --git a/examples/ad_manager/data/medium_rectangle.jpg b/examples/ad_manager/data/medium_rectangle.jpg
new file mode 100644
index 00000000..ae2ab636
Binary files /dev/null and b/examples/ad_manager/data/medium_rectangle.jpg differ
diff --git a/examples/ad_manager/v202202/activity_group_service/__init__.py b/examples/ad_manager/v202202/activity_group_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202202/activity_group_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202202/activity_group_service/create_activity_groups.py b/examples/ad_manager/v202202/activity_group_service/create_activity_groups.py
new file mode 100755
index 00000000..4ea2bf84
--- /dev/null
+++ b/examples/ad_manager/v202202/activity_group_service/create_activity_groups.py
@@ -0,0 +1,71 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new activity groups.
+
+To determine which activity groups exist, run get_all_activity_groups.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the advertiser company this activity group is associated with.
+ADVERTISER_COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
+
+
+def main(client, advertiser_company_id):
+ # Initialize appropriate service.
+ activity_group_service = client.GetService('ActivityGroupService',
+ version='v202202')
+
+ # Create a short-term activity group.
+ short_term_activity_group = {
+ 'name': 'Short-term activity group #%s' % uuid.uuid4(),
+ 'companyIds': [advertiser_company_id],
+ 'clicksLookback': '1',
+ 'impressionsLookback': '1'
+ }
+
+ # Create a long-term activity group.
+ long_term_activity_group = {
+ 'name': 'Long-term activity group #%s' % uuid.uuid4(),
+ 'companyIds': [advertiser_company_id],
+ 'clicksLookback': '30',
+ 'impressionsLookback': '30'
+ }
+
+ # Create the activity groups on the server.
+ activity_groups = activity_group_service.createActivityGroups([
+ short_term_activity_group, long_term_activity_group])
+
+ # Display results.
+ for activity_group in activity_groups:
+ print('Activity group with ID "%s" and name "%s" was created.'
+ % (activity_group['id'], activity_group['name']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ADVERTISER_COMPANY_ID)
diff --git a/examples/ad_manager/v202202/activity_group_service/get_active_activity_groups.py b/examples/ad_manager/v202202/activity_group_service/get_active_activity_groups.py
new file mode 100755
index 00000000..d77cdfe0
--- /dev/null
+++ b/examples/ad_manager/v202202/activity_group_service/get_active_activity_groups.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all active activity groups.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ activity_group_service = client.GetService(
+ 'ActivityGroupService', version='v202202')
+ # Create a statement to select activity groups.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('status = :status')
+ .WithBindVariable('status', 'ACTIVE'))
+
+ # Retrieve a small amount of activity groups at a time, paging
+ # through until all activity groups have been retrieved.
+ while True:
+ response = activity_group_service.getActivityGroupsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for activity_group in response['results']:
+ # Print out some information for each activity group.
+ print('Activity group with ID "%d" and name "%s" was found.\n' %
+ (activity_group['id'], activity_group['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/activity_group_service/get_all_activity_groups.py b/examples/ad_manager/v202202/activity_group_service/get_all_activity_groups.py
new file mode 100755
index 00000000..450f061b
--- /dev/null
+++ b/examples/ad_manager/v202202/activity_group_service/get_all_activity_groups.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all activity groups.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ activity_group_service = client.GetService(
+ 'ActivityGroupService', version='v202202')
+
+ # Create a statement to select activity groups.
+ statement = ad_manager.StatementBuilder(version='v202202')
+
+ # Retrieve a small amount of activity groups at a time, paging
+ # through until all activity groups have been retrieved.
+ while True:
+ response = activity_group_service.getActivityGroupsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for activity_group in response['results']:
+ # Print out some information for each activity group.
+ print('Activity group with ID "%d" and name "%s" was found.\n' %
+ (activity_group['id'], activity_group['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/activity_group_service/update_activity_groups.py b/examples/ad_manager/v202202/activity_group_service/update_activity_groups.py
new file mode 100755
index 00000000..f61bd685
--- /dev/null
+++ b/examples/ad_manager/v202202/activity_group_service/update_activity_groups.py
@@ -0,0 +1,70 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates activity groups.
+
+To determine which activity groups exist, run get_all_activity_groups.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the activity group and the company to update it with.
+ACTIVITY_GROUP_ID = 'INSERT_ACTIVITY_GROUP_ID_HERE'
+ADVERTISER_COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
+
+
+def main(client, activity_group_id, advertiser_company_id):
+ # Initialize appropriate service.
+ activity_group_service = client.GetService('ActivityGroupService',
+ version='v202202')
+
+ # Create statement object to select a single activity groups by ID.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('id = :activityGroupId')
+ .WithBindVariable('activityGroupId', int(activity_group_id))
+ .Limit(1))
+
+ # Get activity groups by statement.
+ response = activity_group_service.getActivityGroupsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ updated_activity_groups = []
+ for activity_group in response['results']:
+ activity_group['companyIds'].append(advertiser_company_id)
+ updated_activity_groups.append(activity_group)
+ # Update the activity groups on the server.
+ activity_groups = activity_group_service.updateActivityGroups(
+ updated_activity_groups)
+
+ for activity_group in activity_groups:
+ print(('Activity group with ID "%s" and name "%s" was updated.')
+ % (activity_group['id'], activity_group['name']))
+ else:
+ print('No activity groups found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ACTIVITY_GROUP_ID, ADVERTISER_COMPANY_ID)
diff --git a/examples/ad_manager/v202202/activity_service/__init__.py b/examples/ad_manager/v202202/activity_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202202/activity_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202202/activity_service/create_activities.py b/examples/ad_manager/v202202/activity_service/create_activities.py
new file mode 100755
index 00000000..c983f8b9
--- /dev/null
+++ b/examples/ad_manager/v202202/activity_service/create_activities.py
@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new activities.
+
+To determine which activities groups exist, run get_all_activities.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the activity group this activity is associated with.
+ACTIVITY_GROUP_ID = 'INSERT_ACTIVITY_GROUP_ID_HERE'
+
+
+def main(client, activity_group_id):
+ # Initialize appropriate service.
+ activity_service = client.GetService('ActivityService', version='v202202')
+
+ # Create a daily visits activity.
+ daily_visits_activity = {
+ 'name': 'Activity #%s' % uuid.uuid4(),
+ 'activityGroupId': activity_group_id,
+ 'type': 'DAILY_VISITS'
+ }
+
+ # Create a custom activity.
+ custom_activity = {
+ 'name': 'Activity #%s' % uuid.uuid4(),
+ 'activityGroupId': activity_group_id,
+ 'type': 'CUSTOM'
+ }
+
+ # Create the activities on the server.
+ activities = activity_service.createActivities([
+ daily_visits_activity, custom_activity])
+
+ # Display results.
+ for activity in activities:
+ print('An activity with ID "%s", name "%s", and type "%s" was '
+ 'created.' % (activity['id'], activity['name'], activity['type']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ACTIVITY_GROUP_ID)
diff --git a/examples/ad_manager/v202202/activity_service/get_active_activities.py b/examples/ad_manager/v202202/activity_service/get_active_activities.py
new file mode 100755
index 00000000..312d7dff
--- /dev/null
+++ b/examples/ad_manager/v202202/activity_service/get_active_activities.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all active activities.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ activity_service = client.GetService('ActivityService', version='v202202')
+ # Create a statement to select activities.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('status = :status')
+ .WithBindVariable('status', 'ACTIVE'))
+
+ # Retrieve a small amount of activities at a time, paging
+ # through until all activities have been retrieved.
+ while True:
+ response = activity_service.getActivitiesByStatement(statement.ToStatement(
+ ))
+ if 'results' in response and len(response['results']):
+ for activity in response['results']:
+ # Print out some information for each activity.
+ print('Activity with ID "%d", name "%s", and type "%s" was found.\n' %
+ (activity['id'], activity['name'], activity['type']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/activity_service/get_all_activities.py b/examples/ad_manager/v202202/activity_service/get_all_activities.py
new file mode 100755
index 00000000..03072e7a
--- /dev/null
+++ b/examples/ad_manager/v202202/activity_service/get_all_activities.py
@@ -0,0 +1,50 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all activities.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ activity_service = client.GetService('ActivityService', version='v202202')
+
+ # Create a statement to select activities.
+ statement = ad_manager.StatementBuilder(version='v202202')
+
+ # Retrieve a small amount of activities at a time, paging
+ # through until all activities have been retrieved.
+ while True:
+ response = activity_service.getActivitiesByStatement(statement.ToStatement(
+ ))
+ if 'results' in response and len(response['results']):
+ for activity in response['results']:
+ # Print out some information for each activity.
+ print('Activity with ID "%d" and name "%s" was found.\n' %
+ (activity['id'], activity['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/activity_service/update_activities.py b/examples/ad_manager/v202202/activity_service/update_activities.py
new file mode 100755
index 00000000..a114ae2c
--- /dev/null
+++ b/examples/ad_manager/v202202/activity_service/update_activities.py
@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates activities.
+
+To determine which activities exist, run get_all_activities.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the activity to update.
+ACTIVITY_ID = 'INSERT_ACTIVITY_ID_HERE'
+
+
+def main(client, activity_id):
+ # Initialize appropriate service.
+ activity_service = client.GetService('ActivityService', version='v202202')
+
+ # Create statement object to select one activity by ID to update.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('id = :activityId')
+ .WithBindVariable('activityId', int(activity_id))
+ .Limit(1))
+
+ # Get activities by statement.
+ response = activity_service.getActivitiesByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ updated_activities = []
+ for activity in response['results']:
+ # Update the expected URL.
+ activity['expectedURL'] = 'https://google.com'
+ updated_activities.append(activity)
+ # Update the activity on the server.
+ activities = activity_service.updateActivities(updated_activities)
+
+ for updated_activity in activities:
+ print(('Activity with ID "%s" and name "%s" was updated.')
+ % (updated_activity['id'], updated_activity['name']))
+ else:
+ print('No activities found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ACTIVITY_ID)
diff --git a/examples/ad_manager/v202202/adjustment_service/create_forecast_adjustments.py b/examples/ad_manager/v202202/adjustment_service/create_forecast_adjustments.py
new file mode 100755
index 00000000..ae3a02b1
--- /dev/null
+++ b/examples/ad_manager/v202202/adjustment_service/create_forecast_adjustments.py
@@ -0,0 +1,65 @@
+#!/usr/bin/env python
+#
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example creates a forecast adjustment for New Year's Day traffic."""
+
+import datetime
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+TRAFFIC_FORECAST_SEGMENT_ID = 'INSERT_TRAFFIC_FORECAST_SEGMENT_ID_HERE'
+
+
+def main(client, traffic_forecast_segment_id):
+ # Initialize the adjustment service.
+ adjustment_service = client.GetService('AdjustmentService', version='v202202')
+
+ # Create a new forecast adjustment for New Year's Day traffic.
+ this_new_years = datetime.date(datetime.date.today().year, 1, 1)
+ next_new_years = datetime.date(datetime.date.today().year + 1, 1, 1)
+
+ forecast = {
+ 'name': 'Forecast adjustment #%s' % uuid.uuid4(),
+ 'trafficForecastSegmentId': traffic_forecast_segment_id,
+ 'dateRange': {
+ 'startDate': next_new_years,
+ 'endDate': next_new_years
+ },
+ 'status': 'ACTIVE',
+ 'volumeType': 'HISTORICAL_BASIS_VOLUME',
+ 'historicalBasisVolumeSettings': {
+ 'useParentTrafficForecastSegmentTargeting': True,
+ 'historicalDateRange': {
+ 'startDate': this_new_years,
+ 'endDate': this_new_years
+ },
+ 'multiplierMilliPercent': 110000
+ }
+ }
+
+ forecasts = adjustment_service.createForecastAdjustments([forecast])
+
+ for forecast in forecasts:
+ print('Forecast adjustment with id %d and name "%s" was created.' % (
+ forecast['id'], forecast['name']
+ ))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, TRAFFIC_FORECAST_SEGMENT_ID)
diff --git a/examples/ad_manager/v202202/adjustment_service/create_traffic_forecast_segments.py b/examples/ad_manager/v202202/adjustment_service/create_traffic_forecast_segments.py
new file mode 100755
index 00000000..3524c6ee
--- /dev/null
+++ b/examples/ad_manager/v202202/adjustment_service/create_traffic_forecast_segments.py
@@ -0,0 +1,72 @@
+#!/usr/bin/env python
+#
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example creates a traffic forecast segment for all ad units in the U.S.
+"""
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize the adjustment service and the network service.
+ adjustment_service = client.GetService('AdjustmentService', version='v202202')
+ network_service = client.GetService('NetworkService', version='v202202')
+
+ # Get the root ad unit id to target the whole site.
+ current_network = network_service.getCurrentNetwork()
+ root_ad_unit_id = current_network['effectiveRootAdUnitId']
+
+ # Create inventory targeting.
+ inventory_targeting = {
+ 'targetedAdUnits': [{
+ 'includeDescendants': True,
+ 'adUnitId': root_ad_unit_id
+ }]
+ }
+
+ # Create targeting for United States traffic.
+ geo_targeting = {
+ 'targetedLocations': [{
+ 'id': 2840
+ }]
+ }
+
+ # Create traffic forecast segment object.
+ segment = {
+ 'name': 'Forecast segment #%s' % uuid.uuid4(),
+ 'targeting': {
+ 'inventoryTargeting': inventory_targeting,
+ 'geoTargeting': geo_targeting
+ }
+ }
+
+ # Create the traffic forecast segment on the server.
+ segments = adjustment_service.createTrafficForecastSegments([segment])
+
+ # Display the results.
+ for segment in segments:
+ print('Traffic forecast segment with id %d and %d forecast adjustments was '
+ 'created.' % (segment['id'],
+ segment['forecastAdjustmentCount']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/adjustment_service/get_all_forecast_adjustments.py b/examples/ad_manager/v202202/adjustment_service/get_all_forecast_adjustments.py
new file mode 100755
index 00000000..a310e698
--- /dev/null
+++ b/examples/ad_manager/v202202/adjustment_service/get_all_forecast_adjustments.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all forecast adjustments."""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize the adjustment service.
+ adjustment_service = client.GetService('AdjustmentService', version='v202202')
+
+ # Create a statement to get all forecast adjustments.
+ statement = ad_manager.StatementBuilder(version='v202202')
+
+ # Retrieve a small number of forecast adjustments at a time, paging
+ # through until all forecast adjustments have been retrieved.
+ while True:
+ response = adjustment_service.getForecastAdjustmentsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for adjustment in response['results']:
+ # Print out some information for each forecast adjustment.
+ print('Forecast adjustment with id %d and name "%s" belonging to '
+ 'forecast segment %d was found.' %
+ (adjustment['id'], adjustment['name'],
+ adjustment['trafficForecastSegmentId']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/adjustment_service/get_all_traffic_forecast_segments.py b/examples/ad_manager/v202202/adjustment_service/get_all_traffic_forecast_segments.py
new file mode 100755
index 00000000..8d16cf66
--- /dev/null
+++ b/examples/ad_manager/v202202/adjustment_service/get_all_traffic_forecast_segments.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+#
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all traffic forecast segments."""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize the adjustment service.
+ adjustment_service = client.GetService('AdjustmentService', version='v202202')
+
+ # Create a statement to get all traffic forecast segments.
+ statement = ad_manager.StatementBuilder(version='v202202')
+
+ # Retrieve a small number of segments at a time, paging through until all
+ # segments have been retrieved.
+ while True:
+ response = adjustment_service.getTrafficForecastSegmentsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for segment in response['results']:
+ # Print out some information for each traffic forecast segment.
+ print('Traffic forecast segment with id %d and name "%s" was found ' % (
+ segment['id'], segment['name'],
+ ))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py b/examples/ad_manager/v202202/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py
new file mode 100755
index 00000000..178ee627
--- /dev/null
+++ b/examples/ad_manager/v202202/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py
@@ -0,0 +1,57 @@
+#!/usr/bin/env python
+#
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all forecast adjustments for a traffic forecast segment."""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+TRAFFIC_FORECAST_SEGMENT_ID = 'INSERT_FORECAST_SEGMENT_ID_HERE'
+
+
+def main(client, traffic_forecast_segment_id):
+ # Initialize the adjustment service.
+ adjustment_service = client.GetService('AdjustmentService', version='v202202')
+
+ # Create a statement to get forecast adjustments for a given traffic forecast
+ # segment id.
+ statement = ad_manager.StatementBuilder(version='v202202').Where(
+ 'trafficForecastSegmentId = :segmentId').WithBindVariable(
+ 'segmentId', traffic_forecast_segment_id)
+
+ # Retrieve a small number of forecast adjustments at a time, paging
+ # through until all forecast adjustments have been retrieved.
+ while True:
+ response = adjustment_service.getForecastAdjustmentsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for adjustment in response['results']:
+ # Print out some information for each traffic adjustment.
+ print('Forecast adjustment with id %d and name "%s" belonging to '
+ 'forecast segment %d was found.' %
+ (adjustment['id'], adjustment['name'],
+ adjustment['trafficForecastSegmentId']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, int(TRAFFIC_FORECAST_SEGMENT_ID))
diff --git a/examples/ad_manager/v202202/adjustment_service/update_forecast_adjustments.py b/examples/ad_manager/v202202/adjustment_service/update_forecast_adjustments.py
new file mode 100755
index 00000000..23a8d70a
--- /dev/null
+++ b/examples/ad_manager/v202202/adjustment_service/update_forecast_adjustments.py
@@ -0,0 +1,64 @@
+#!/usr/bin/env python
+#
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example updates a forecast adjustment's name."""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+ADJUSTMENT_ID = 'INSERT_ADJUSTMENT_ID_HERE'
+
+
+def main(client, adjustment_id):
+ # Initialize the adjustment service.
+ adjustment_service = client.GetService('AdjustmentService', version='v202202')
+
+ # Create a statement to select a single forecast adjustment by id.
+ statement = (
+ ad_manager.StatementBuilder(
+ version='v202202').Where('id = :id').WithBindVariable(
+ 'id', adjustment_id))
+
+ # Get the forecast adjustment.
+ response = adjustment_service.getForecastAdjustmentsByStatement(
+ statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ # Update each local forecast adjustment's name.
+ updated_adjustments = []
+ for adjustment in response['results']:
+ adjustment['name'] += ' (updated)'
+ updated_adjustments.append(adjustment)
+
+ # Update the forecast adjustment on the server.
+ adjustments = adjustment_service.updateForecastAdjustments(
+ updated_adjustments)
+
+ # Display the results.
+ if adjustments:
+ for adjustment in adjustments:
+ print('Forecast adjustment with id %d and name "%s" was updated' % (
+ adjustment['id'], adjustment['name']))
+ else:
+ print('No forecast adjustments were updated.')
+ else:
+ print('No forecast adjustments found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ADJUSTMENT_ID)
diff --git a/examples/ad_manager/v202202/audience_segment_service/__init__.py b/examples/ad_manager/v202202/audience_segment_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202202/audience_segment_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202202/audience_segment_service/create_audience_segments.py b/examples/ad_manager/v202202/audience_segment_service/create_audience_segments.py
new file mode 100755
index 00000000..23e6166d
--- /dev/null
+++ b/examples/ad_manager/v202202/audience_segment_service/create_audience_segments.py
@@ -0,0 +1,96 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example creates a new rule based first party audience segment."""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the IDs of the custom criteria to be used in the segment rule.
+CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'
+CUSTOM_TARGETING_VALUE_ID = 'INSERT_CUSTOM_TARGETING_VALUE_ID_HERE'
+
+
+def main(client, custom_targeting_key_id, custom_targeting_value_id):
+ # Initialize appropriate services.
+ audience_segment_service = client.GetService(
+ 'AudienceSegmentService', version='v202202')
+ network_service = client.GetService('NetworkService', version='v202202')
+
+ # Get the root ad unit ID used to target the entire network.
+ root_ad_unit_id = (
+ network_service.getCurrentNetwork()['effectiveRootAdUnitId'])
+
+ # Create inventory targeting (pointed at root ad unit i.e. the whole network)
+ inventory_targeting = {
+ 'targetedAdUnits': [
+ {'adUnitId': root_ad_unit_id}
+ ]
+ }
+
+ # Create custom criteria.
+ custom_criteria = [
+ {
+ 'xsi_type': 'CustomCriteria',
+ 'keyId': custom_targeting_key_id,
+ 'valueIds': [custom_targeting_value_id],
+ 'operator': 'IS'
+ }
+ ]
+
+ # Create the custom criteria set.
+ top_custom_criteria_set = {
+ 'logicalOperator': 'AND',
+ 'children': custom_criteria
+ }
+
+ # Create the audience segment rule.
+ rule = {
+ 'inventoryRule': inventory_targeting,
+ 'customCriteriaRule': top_custom_criteria_set
+ }
+
+ # Create an audience segment.
+ audience_segment = [
+ {
+ 'xsi_type': 'RuleBasedFirstPartyAudienceSegment',
+ 'name': ('Sports enthusiasts audience segment %s' %
+ uuid.uuid4()),
+ 'description': 'Sports enthusiasts between the ages of 20 and 30',
+ 'pageViews': '6',
+ 'recencyDays': '6',
+ 'membershipExpirationDays': '88',
+ 'rule': rule
+ }
+ ]
+
+ audience_segments = (
+ audience_segment_service.createAudienceSegments(audience_segment))
+
+ for created_audience_segment in audience_segments:
+ print('An audience segment with ID "%s", name "%s", and type "%s" '
+ 'was created.' % (created_audience_segment['id'],
+ created_audience_segment['name'],
+ created_audience_segment['type']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CUSTOM_TARGETING_KEY_ID, CUSTOM_TARGETING_VALUE_ID)
diff --git a/examples/ad_manager/v202202/audience_segment_service/get_all_audience_segments.py b/examples/ad_manager/v202202/audience_segment_service/get_all_audience_segments.py
new file mode 100755
index 00000000..7818441e
--- /dev/null
+++ b/examples/ad_manager/v202202/audience_segment_service/get_all_audience_segments.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all audience segments.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ audience_segment_service = client.GetService(
+ 'AudienceSegmentService', version='v202202')
+
+ # Create a statement to select audience segments.
+ statement = ad_manager.StatementBuilder(version='v202202')
+
+ # Retrieve a small amount of audience segments at a time, paging
+ # through until all audience segments have been retrieved.
+ while True:
+ response = audience_segment_service.getAudienceSegmentsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for audience_segment in response['results']:
+ # Print out some information for each audience segment.
+ print('Audience segment with ID "%d", name "%s", and size "%d" was '
+ 'found.\n' % (audience_segment['id'], audience_segment['name'],
+ audience_segment['size']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/audience_segment_service/get_first_party_audience_segments.py b/examples/ad_manager/v202202/audience_segment_service/get_first_party_audience_segments.py
new file mode 100755
index 00000000..8885c316
--- /dev/null
+++ b/examples/ad_manager/v202202/audience_segment_service/get_first_party_audience_segments.py
@@ -0,0 +1,53 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all first party audience segments.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ audience_segment_service = client.GetService(
+ 'AudienceSegmentService', version='v202202')
+ # Create a statement to select audience segments.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('type = :type')
+ .WithBindVariable('type', 'FIRST_PARTY'))
+
+ # Retrieve a small amount of audience segments at a time, paging
+ # through until all audience segments have been retrieved.
+ while True:
+ response = audience_segment_service.getAudienceSegmentsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for audience_segment in response['results']:
+ # Print out some information for each audience segment.
+ print('Audience segment with ID "%d", name "%s", and size "%d" was '
+ 'found.\n' % (audience_segment['id'], audience_segment['name'],
+ audience_segment['size']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/audience_segment_service/populate_first_party_audience_segments.py b/examples/ad_manager/v202202/audience_segment_service/populate_first_party_audience_segments.py
new file mode 100755
index 00000000..0e9d3249
--- /dev/null
+++ b/examples/ad_manager/v202202/audience_segment_service/populate_first_party_audience_segments.py
@@ -0,0 +1,71 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example populates a specific first party audience segment.
+
+To determine which first party audience segments exist, run
+get_first_party_audience_segments.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+AUDIENCE_SEGMENT_ID = 'INSERT_AUDIENCE_SEGMENT_ID_HERE'
+
+
+def main(client, audience_segment_id):
+ # Initialize appropriate service.
+ audience_segment_service = client.GetService(
+ 'AudienceSegmentService', version='v202202')
+
+ # Create statement object to get the specified first party audience segment.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('Type = :type AND Id = :audience_segment_id')
+ .WithBindVariable('audience_segment_id',
+ int(audience_segment_id))
+ .WithBindVariable('type', 'FIRST_PARTY')
+ .Limit(1))
+
+ response = audience_segment_service.getAudienceSegmentsByStatement(
+ statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ segments = response['results']
+
+ for segment in segments:
+ print(
+ 'Audience segment with id "%s" and name "%s" will be populated.'
+ % (segment['id'], segment['name']))
+
+ action = {
+ 'xsi_type': 'PopulateAudienceSegments'
+ }
+
+ populated_audience_segments = (
+ audience_segment_service.performAudienceSegmentAction(
+ action, statement.ToStatement()))
+
+ print('%s audience segment populated' %
+ populated_audience_segments['numChanges'])
+ else:
+ print('No Results Found')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, AUDIENCE_SEGMENT_ID)
diff --git a/examples/ad_manager/v202202/audience_segment_service/update_audience_segments.py b/examples/ad_manager/v202202/audience_segment_service/update_audience_segments.py
new file mode 100755
index 00000000..3d03106e
--- /dev/null
+++ b/examples/ad_manager/v202202/audience_segment_service/update_audience_segments.py
@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example updates rule based first party audience segments.
+
+To determine which audience segments exist, run get_all_audience_segments.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+AUDIENCE_SEGMENT_ID = 'INSERT_AUDIENCE_SEGMENT_ID_HERE'
+
+
+def main(client, audience_segment_id):
+ # Initialize appropriate service.
+ audience_segment_service = client.GetService(
+ 'AudienceSegmentService', version='v202202')
+
+ # Create statement object to get the specified first party audience segment.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('Type = :type AND Id = :audience_segment_id')
+ .WithBindVariable('audience_segment_id',
+ int(audience_segment_id))
+ .WithBindVariable('type', 'FIRST_PARTY')
+ .Limit(1))
+
+ # Get audience segments by statement.
+ response = audience_segment_service.getAudienceSegmentsByStatement(
+ statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ updated_audience_segments = []
+ for audience_segment in response['results']:
+ print('Audience segment with id "%s" and name "%s" will be updated.'
+ % (audience_segment['id'], audience_segment['name']))
+
+ audience_segment['membershipExpirationDays'] = '180'
+ updated_audience_segments.append(audience_segment)
+
+ audience_segments = audience_segment_service.updateAudienceSegments(
+ updated_audience_segments)
+
+ for audience_segment in audience_segments:
+ print('Audience segment with id "%s" and name "%s" was updated' %
+ (audience_segment['id'], audience_segment['name']))
+ else:
+ print('No audience segment found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, AUDIENCE_SEGMENT_ID)
diff --git a/examples/ad_manager/v202202/cdn_configuration_service/__init__.py b/examples/ad_manager/v202202/cdn_configuration_service/__init__.py
new file mode 100755
index 00000000..473ddba1
--- /dev/null
+++ b/examples/ad_manager/v202202/cdn_configuration_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202202/cdn_configuration_service/create_cdn_configurations.py b/examples/ad_manager/v202202/cdn_configuration_service/create_cdn_configurations.py
new file mode 100755
index 00000000..33b2929e
--- /dev/null
+++ b/examples/ad_manager/v202202/cdn_configuration_service/create_cdn_configurations.py
@@ -0,0 +1,89 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new cdn configurations.
+
+To determine which configurations exist, run get_all_cdn_configurations.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ cdn_config_service = client.GetService('CdnConfigurationService',
+ version='v202202')
+
+ # Create cdn config objects.
+ # Only LIVE_STREAM_SOURCE_CONTENT is currently supported by the API.
+ configs = [{
+ # Basic example with no security policies.
+ 'name': 'ApiConfig1',
+ 'cdnConfigurationType': 'LIVE_STREAM_SOURCE_CONTENT',
+ 'sourceContentConfiguration': {
+ 'ingestSettings': {
+ 'urlPrefix': 'ingest1.com',
+ 'securityPolicy': {
+ 'securityPolicyType': 'NONE'
+ }
+ },
+ 'defaultDeliverySettings': {
+ 'urlPrefix': 'delivery1.com',
+ 'securityPolicy': {
+ 'securityPolicyType': 'NONE'
+ }
+ }
+ }
+ }, {
+ # Complex example with security policies.
+ 'name': 'ApiConfig2',
+ 'cdnConfigurationType': 'LIVE_STREAM_SOURCE_CONTENT',
+ 'sourceContentConfiguration': {
+ 'ingestSettings': {
+ 'urlPrefix': 'ingest1.com',
+ 'securityPolicy': {
+ 'securityPolicyType': 'AKAMAI',
+ 'disableServerSideUrlSigning': False,
+ 'tokenAuthenticationKey': 'abc123',
+ }
+ },
+ 'defaultDeliverySettings': {
+ 'urlPrefix': 'delivery1.com',
+ 'securityPolicy': {
+ 'securityPolicyType': 'AKAMAI',
+ 'disableServerSideUrlSigning': True,
+ 'originForwardingType': 'CONVENTIONAL',
+ 'originPathPrefix': '/path/to/my/origin'
+ }
+ }
+ }
+ }]
+
+ # Add configs.
+ configs = cdn_config_service.createCdnConfigurations(configs)
+
+ # Display results.
+ for config in configs:
+ print('Created CDN configuration with type "%s" and name "%s".'
+ % (config['cdnConfigurationType'], config['name']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/cdn_configuration_service/get_all_cdn_configurations.py b/examples/ad_manager/v202202/cdn_configuration_service/get_all_cdn_configurations.py
new file mode 100755
index 00000000..e2d68c32
--- /dev/null
+++ b/examples/ad_manager/v202202/cdn_configuration_service/get_all_cdn_configurations.py
@@ -0,0 +1,54 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all CDN configuration objects.
+
+Currently only configurations of type LIVE_STREAM_SOURCE_CONTENT will be
+returned.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ cdn_config_service = client.GetService('CdnConfigurationService',
+ version='v202202')
+
+ # Create a statement to select cdn configurations.
+ statement = ad_manager.StatementBuilder(version='v202202')
+
+ # Retrieve a small number of configs at a time, paging
+ # through until all have been retrieved.
+ while True:
+ response = (cdn_config_service
+ .getCdnConfigurationsByStatement(statement.ToStatement()))
+ if 'results' in response and len(response['results']):
+ for cdn in response['results']:
+ # Print out some information for each company.
+ print('Found CDN configuration with type "%s" and name "%s".'
+ % (cdn['cdnConfigurationType'], cdn['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/cms_metadata_service/activate_cms_metadata_values.py b/examples/ad_manager/v202202/cms_metadata_service/activate_cms_metadata_values.py
new file mode 100755
index 00000000..4f3a5d40
--- /dev/null
+++ b/examples/ad_manager/v202202/cms_metadata_service/activate_cms_metadata_values.py
@@ -0,0 +1,70 @@
+#!/usr/bin/env python
+#
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example activates CMS Metadata Values for a particular CMS Metadata Key.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the id of the CMS Metadata Key on which to activate the CMS Metadata
+# Values.
+CMS_METADATA_KEY_ID = 'INSERT_CMS_METADATA_KEY_ID_HERE'
+
+
+def main(client, cms_metadata_key_id):
+ # Initialize appropriate service.
+ cms_metadata_service = client.GetService('CmsMetadataService',
+ version='v202202')
+
+ # Create query.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('cmsKeyId = :cmsKeyId AND status = :status')
+ .WithBindVariable('status', 'INACTIVE')
+ .WithBindVariable('cmsKeyId', int(cms_metadata_key_id)))
+
+ values_activated = 0
+
+ # Get CMS Metadata Values by statement.
+ while True:
+ response = cms_metadata_service.getCmsMetadataValuesByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for cms_metadata_value in response['results']:
+ print('CMS Metadata Value with id "%s" and name "%s" will be '
+ 'activated.' % (cms_metadata_value['cmsMetadataValueId'],
+ cms_metadata_value['valueName']))
+
+ # Perform action.
+ result = cms_metadata_service.performCmsMetadataValueAction(
+ {'xsi_type': 'ActivateCmsMetadataValues'}, statement.ToStatement())
+ if result and int(result['numChanges']) > 0:
+ values_activated += int(result['numChanges'])
+ statement.offset += statement.limit
+ else:
+ break
+
+ # Display results.
+ if values_activated > 0:
+ print('Number of CMS Metadata Values activated: %s' % values_activated)
+ else:
+ print('No CMS Metadata Values were activated.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CMS_METADATA_KEY_ID)
diff --git a/examples/ad_manager/v202202/cms_metadata_service/get_all_cms_metadata_keys.py b/examples/ad_manager/v202202/cms_metadata_service/get_all_cms_metadata_keys.py
new file mode 100755
index 00000000..6c922ef1
--- /dev/null
+++ b/examples/ad_manager/v202202/cms_metadata_service/get_all_cms_metadata_keys.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2019 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all CmsMetadataKeys."""
+
+# Import appropriate modules from the client library.
+from __future__ import print_function
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ cms_metadata_service = client.GetService(
+ 'CmsMetadataService', version='v202202')
+
+ # Create a statement to select CmsMetadataKeys.
+ statement = ad_manager.StatementBuilder(version='v202202')
+
+ # Retrieve a small amount of keys at a time, paging
+ # through until all keys have been retrieved.
+ while True:
+ response = cms_metadata_service.getCmsMetadataKeysByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for cms_metadata_key in response['results']:
+ # Print out some information for each key.
+ print('CMS metadata key with Id %d and name "%s" was found.\n' %
+ (cms_metadata_key['id'], cms_metadata_key['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/cms_metadata_service/get_all_cms_metadata_values.py b/examples/ad_manager/v202202/cms_metadata_service/get_all_cms_metadata_values.py
new file mode 100755
index 00000000..434a8776
--- /dev/null
+++ b/examples/ad_manager/v202202/cms_metadata_service/get_all_cms_metadata_values.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python
+#
+# Copyright 2019 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all CmsMetadataValues."""
+
+# Import appropriate modules from the client library.
+from __future__ import print_function
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ cms_metadata_service = client.GetService(
+ 'CmsMetadataService', version='v202202')
+
+ # Create a statement to select CmsMetadataValues.
+ statement = ad_manager.StatementBuilder(version='v202202')
+
+ # Retrieve a small amount of values at a time, paging
+ # through until all values have been retrieved.
+ while True:
+ response = cms_metadata_service.getCmsMetadataValuesByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for cms_metadata_value in response['results']:
+ # Print out some information for each value.
+ print(('CMS metadata value with Id %d and name "%s", associated with '
+ 'the CmsMetadataKey with id %d and name "%s", was found.\n') %
+ (cms_metadata_value['cmsMetadataValueId'],
+ cms_metadata_value['valueName'], cms_metadata_value['key']['id'],
+ cms_metadata_value['key']['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/cms_metadata_service/get_cms_metadata_values_for_key.py b/examples/ad_manager/v202202/cms_metadata_service/get_cms_metadata_values_for_key.py
new file mode 100755
index 00000000..3619950a
--- /dev/null
+++ b/examples/ad_manager/v202202/cms_metadata_service/get_cms_metadata_values_for_key.py
@@ -0,0 +1,60 @@
+#!/usr/bin/env python
+#
+# Copyright 2019 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all CmsMetadataValues for a particular CmsMetadataKey."""
+
+# Import appropriate modules from the client library.
+from __future__ import print_function
+from googleads import ad_manager
+
+CMS_METADATA_KEY_NAME = 'INSERT_CMS_METADATA_KEY_NAME_HERE'
+
+
+def main(client, cms_metadata_key_name):
+ # Initialize appropriate service.
+ cms_metadata_service = client.GetService(
+ 'CmsMetadataService', version='v202202')
+
+ # Create a statement to select CmsMetadataValues for a particular key.
+ statement = (
+ ad_manager.StatementBuilder(version='v202202').Where(
+ 'cmsKey = :cmsMetadataKeyName').WithBindVariable(
+ 'cmsMetadataKeyName', cms_metadata_key_name))
+
+ # Retrieve a small amount of values at a time, paging
+ # through until all values have been retrieved.
+ while True:
+ response = cms_metadata_service.getCmsMetadataValuesByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for cms_metadata_value in response['results']:
+ # Print out some information for each value.
+ print(('CMS metadata value with Id %d and name "%s", associated with '
+ 'the CmsMetadataKey with id %d and name "%s", was found.\n') %
+ (cms_metadata_value['cmsMetadataValueId'],
+ cms_metadata_value['valueName'], cms_metadata_value['key']['id'],
+ cms_metadata_value['key']['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CMS_METADATA_KEY_NAME)
diff --git a/examples/ad_manager/v202202/company_service/__init__.py b/examples/ad_manager/v202202/company_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202202/company_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202202/company_service/create_companies.py b/examples/ad_manager/v202202/company_service/create_companies.py
new file mode 100755
index 00000000..96320d72
--- /dev/null
+++ b/examples/ad_manager/v202202/company_service/create_companies.py
@@ -0,0 +1,62 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new companies.
+
+To determine which companies exist, run get_all_companies.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ company_service = client.GetService('CompanyService', version='v202202')
+
+ # Create company objects.
+ companies = [
+ {
+ 'name': 'Advertiser #%s' % uuid.uuid4(),
+ 'type': 'ADVERTISER'
+ },
+ {
+ 'name': 'Agency #%s' % uuid.uuid4(),
+ 'type': 'AGENCY'
+ }
+ ]
+
+ # Add companies.
+ companies = company_service.createCompanies(companies)
+
+ # Display results.
+ for company in companies:
+ print('Company with ID "%s", name "%s", and type "%s" was created.'
+ % (company['id'], company['name'], company['type']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/company_service/get_advertisers.py b/examples/ad_manager/v202202/company_service/get_advertisers.py
new file mode 100755
index 00000000..fd37fb20
--- /dev/null
+++ b/examples/ad_manager/v202202/company_service/get_advertisers.py
@@ -0,0 +1,50 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all companies that are advertisers.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ company_service = client.GetService('CompanyService', version='v202202')
+ # Create a statement to select companies.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('type = :type')
+ .WithBindVariable('type', 'ADVERTISER'))
+
+ # Retrieve a small amount of companies at a time, paging
+ # through until all companies have been retrieved.
+ while True:
+ response = company_service.getCompaniesByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for company in response['results']:
+ # Print out some information for each company.
+ print('Company with ID "%d", name "%s", and type "%s" was found.\n' %
+ (company['id'], company['name'], company['type']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/company_service/get_all_companies.py b/examples/ad_manager/v202202/company_service/get_all_companies.py
new file mode 100755
index 00000000..b8377257
--- /dev/null
+++ b/examples/ad_manager/v202202/company_service/get_all_companies.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all companies.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ company_service = client.GetService('CompanyService', version='v202202')
+
+ # Create a statement to select companies.
+ statement = ad_manager.StatementBuilder(version='v202202')
+
+ # Retrieve a small amount of companies at a time, paging
+ # through until all companies have been retrieved.
+ while True:
+ response = company_service.getCompaniesByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for company in response['results']:
+ # Print out some information for each company.
+ print('Company with ID "%d", name "%s", and type "%s" was found.\n' %
+ (company['id'], company['name'], company['type']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/company_service/update_companies.py b/examples/ad_manager/v202202/company_service/update_companies.py
new file mode 100755
index 00000000..7664eac4
--- /dev/null
+++ b/examples/ad_manager/v202202/company_service/update_companies.py
@@ -0,0 +1,70 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates company comments.
+
+To determine which companies exist, run get_all_companies.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the company to update.
+COMPANY_ID = 'INSERT_COMPANY_ID_HERE'
+
+
+def main(client, company_id):
+ # Initialize appropriate service.
+ company_service = client.GetService('CompanyService', version='v202202')
+
+ # Create statement object to only select a single company by ID.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('id = :id')
+ .WithBindVariable('id', int(company_id))
+ .Limit(1))
+
+ # Get companies by statement.
+ response = company_service.getCompaniesByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ updated_companies = []
+ for company in response['results']:
+ company['comment'] += ' Updated.'
+ updated_companies.append(company)
+
+ # Update the companies on the server.
+ companies = company_service.updateCompanies(updated_companies)
+
+ # Display results.
+ for company in companies:
+ print(('Company with ID "%s", name "%s", and comment "%s"'
+ ' was updated.')
+ % (company['id'], company['name'], company['comment']))
+ else:
+ print('No companies found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, COMPANY_ID)
diff --git a/examples/ad_manager/v202202/contact_service/__init__.py b/examples/ad_manager/v202202/contact_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202202/contact_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202202/contact_service/create_contacts.py b/examples/ad_manager/v202202/contact_service/create_contacts.py
new file mode 100755
index 00000000..8df599f6
--- /dev/null
+++ b/examples/ad_manager/v202202/contact_service/create_contacts.py
@@ -0,0 +1,71 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new contacts.
+
+To determine which contacts exist, run get_all_contacts.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the advertiser company this contact is associated with.
+ADVERTISER_COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
+
+# Set the ID of the agency company this contact is associated with.
+AGENCY_COMPANY_ID = 'INSERT_AGENCY_COMPANY_ID_HERE'
+
+
+def main(client, advertiser_company_id, agency_company_id):
+ # Initialize appropriate service.
+ contact_service = client.GetService('ContactService', version='v202202')
+
+ # Create an advertiser contact.
+ advertiser_contact = {
+ 'name': 'Mr. Advertiser #%s' % uuid.uuid4(),
+ 'email': 'advertiser@advertising.com',
+ 'companyId': advertiser_company_id
+ }
+
+ # Create an agency contact.
+ agency_contact = {
+ 'name': 'Ms. Agency #%s' % uuid.uuid4(),
+ 'email': 'agency@agencies.com',
+ 'companyId': agency_company_id
+ }
+
+ # Create the contacts on the server.
+ contacts = contact_service.createContacts([advertiser_contact,
+ agency_contact])
+
+ # Display results.
+ for contact in contacts:
+ print('Contact with ID "%s" name "%s" was created.'
+ % (contact['id'], contact['name']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ADVERTISER_COMPANY_ID, AGENCY_COMPANY_ID)
diff --git a/examples/ad_manager/v202202/contact_service/get_all_contacts.py b/examples/ad_manager/v202202/contact_service/get_all_contacts.py
new file mode 100755
index 00000000..a98d1e6f
--- /dev/null
+++ b/examples/ad_manager/v202202/contact_service/get_all_contacts.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all contacts.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ contact_service = client.GetService('ContactService', version='v202202')
+
+ # Create a statement to select contacts.
+ statement = ad_manager.StatementBuilder(version='v202202')
+
+ # Retrieve a small amount of contacts at a time, paging
+ # through until all contacts have been retrieved.
+ while True:
+ response = contact_service.getContactsByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for contact in response['results']:
+ # Print out some information for each contact.
+ print('Contact with ID "%d" and name "%s" was found.\n' %
+ (contact['id'], contact['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/contact_service/get_uninvited_contacts.py b/examples/ad_manager/v202202/contact_service/get_uninvited_contacts.py
new file mode 100755
index 00000000..f41c7d8b
--- /dev/null
+++ b/examples/ad_manager/v202202/contact_service/get_uninvited_contacts.py
@@ -0,0 +1,50 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all contacts that aren't invited yet.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ contact_service = client.GetService('ContactService', version='v202202')
+ # Create a statement to select contacts.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('status = :status')
+ .WithBindVariable('status', 'UNINVITED'))
+
+ # Retrieve a small amount of contacts at a time, paging
+ # through until all contacts have been retrieved.
+ while True:
+ response = contact_service.getContactsByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for contact in response['results']:
+ # Print out some information for each contact.
+ print('Contact with ID "%d" and name "%s" was found.\n' %
+ (contact['id'], contact['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/contact_service/update_contacts.py b/examples/ad_manager/v202202/contact_service/update_contacts.py
new file mode 100755
index 00000000..d2f86340
--- /dev/null
+++ b/examples/ad_manager/v202202/contact_service/update_contacts.py
@@ -0,0 +1,71 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates contact addresses.
+
+To determine which contacts exist, run get_all_contacts.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the contact to update.
+CONTACT_ID = 'INSERT_CONTACT_ID_HERE'
+
+
+def main(client, contact_id):
+ # Initialize appropriate service.
+ contact_service = client.GetService('ContactService', version='v202202')
+
+ # Create statement object to select the single contact by ID.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('id = :id')
+ .WithBindVariable('id', int(contact_id))
+ .Limit(1))
+
+ # Get contacts by statement.
+ response = contact_service.getContactsByStatement(
+ statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ updated_contacts = []
+ for contact in response['results']:
+ contact['address'] = '123 New Street, New York, NY, 10011'
+ updated_contacts.append(contact)
+
+ # Update the contact on the server.
+ contacts = contact_service.updateContacts(updated_contacts)
+
+ # Display results.
+ for contact in contacts:
+ print(('Contact with ID "%s", name "%s", and address "%s" '
+ 'was updated.')
+ % (contact['id'], contact['name'], contact['address']))
+ else:
+ print('No contacts found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CONTACT_ID)
diff --git a/examples/ad_manager/v202202/content_service/__init__.py b/examples/ad_manager/v202202/content_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202202/content_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202202/content_service/get_all_content.py b/examples/ad_manager/v202202/content_service/get_all_content.py
new file mode 100755
index 00000000..dc19fa5e
--- /dev/null
+++ b/examples/ad_manager/v202202/content_service/get_all_content.py
@@ -0,0 +1,54 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all content."""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ content_service = client.GetService('ContentService', version='v202202')
+
+ # Create a statement to select content.
+ statement = ad_manager.StatementBuilder(version='v202202')
+
+ # Retrieve a small amount of content at a time, paging
+ # through until all content have been retrieved.
+ while True:
+ response = content_service.getContentByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for content in response['results']:
+ # Print out some information for each content.
+ content_description = ('Content with ID "%d" and name "%s"' %
+ (content['id'], content['name'].encode('utf-8')))
+ if content['contentBundleIds']:
+ content_description += (' belonging to bundle IDs %s' %
+ content['contentBundleIds'])
+ content_description += ' was found.'
+ print(content_description)
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/content_service/get_recently_modified_content.py b/examples/ad_manager/v202202/content_service/get_recently_modified_content.py
new file mode 100755
index 00000000..b7e98dfb
--- /dev/null
+++ b/examples/ad_manager/v202202/content_service/get_recently_modified_content.py
@@ -0,0 +1,66 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets recently modified content."""
+
+# Import appropriate modules from the client library.
+from datetime import datetime
+from datetime import timedelta
+
+from googleads import ad_manager
+import pytz
+
+
+def main(client):
+ # Initialize appropriate service.
+ content_service = client.GetService('ContentService', version='v202202')
+
+ last_modified = (datetime.now(tz=pytz.timezone('America/New_York'))
+ - timedelta(days=1))
+
+ # Create a statement to get recently modified content based on
+ # lastModifiedDateTime. Changes to content bundle associations will update
+ # the lastModifiedDateTime, but CMS metadata changes may not change the
+ # lastModifiedDateTime.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('lastModifiedDateTime >= :lastModifiedDateTime')
+ .WithBindVariable('lastModifiedDateTime', last_modified))
+
+ # Retrieve a small amount of content at a time, paging
+ # through until all content have been retrieved.
+ while True:
+ response = content_service.getContentByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for content in response['results']:
+ # Print out some information for each content.
+ content_description = ('Content with ID "%d" and name "%s"' %
+ (content['id'], content['name'].encode('utf-8')))
+ if content['contentBundleIds']:
+ content_description += (' belonging to bundle IDs %s' %
+ content['contentBundleIds'])
+ content_description += ' was found.'
+ print(content_description)
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/creative_service/__init__.py b/examples/ad_manager/v202202/creative_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202202/creative_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202202/creative_service/copy_image_creatives.py b/examples/ad_manager/v202202/creative_service/copy_image_creatives.py
new file mode 100755
index 00000000..c2f19753
--- /dev/null
+++ b/examples/ad_manager/v202202/creative_service/copy_image_creatives.py
@@ -0,0 +1,60 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example creates a copy of an image creative.
+
+To determine which image creatives exist, run get_image_creatives.py
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the line item to pause.
+CREATIVE_ID = 'INSERT_CREATIVE_ID_HERE'
+
+
+def main(client):
+ # Initialize appropriate service.
+ creative_service = client.GetService('CreativeService', version='v202202')
+
+ # Create a statement to get the image creative.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('id = :id')
+ .OrderBy('id', ascending=True)
+ .WithBindVariable('id', CREATIVE_ID))
+
+ # Get the creative.
+ query_result = creative_service.getCreativesByStatement(
+ statement.ToStatement())
+
+ image_creative = query_result['results'][0]
+
+ # Build the new creative, set id to None to create a copy.
+ image_creative['id'] = None
+ image_creative['name'] = 'Copy of %s' % image_creative['name']
+
+ result = creative_service.createCreatives([image_creative])[0]
+ print('A creative with ID %d, name "%s", and type "%s" was created and '
+ 'can be previewed at: %s' % (result['id'],
+ result['name'],
+ ad_manager.AdManagerClassType(result),
+ result['previewUrl']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/creative_service/create_creative_from_template.py b/examples/ad_manager/v202202/creative_service/create_creative_from_template.py
new file mode 100755
index 00000000..52a1e500
--- /dev/null
+++ b/examples/ad_manager/v202202/creative_service/create_creative_from_template.py
@@ -0,0 +1,111 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates a new template creative for a given advertiser.
+
+To determine which companies are advertisers, run get_advertisers.py.
+To determine which creative templates exist, run
+get_all_creative_templates.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import os
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set id of the advertiser (company) that the creative will be assigned to.
+ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
+
+
+def main(client, advertiser_id):
+ # Initialize appropriate service.
+ creative_service = client.GetService('CreativeService', version='v202202')
+
+ # Use the image banner with optional third party tracking template.
+ creative_template_id = '10000680'
+
+ # Create image asset.
+ file_name = 'image%s.jpg' % uuid.uuid4()
+ image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data',
+ 'medium_rectangle.jpg'), 'r').read()
+ size = {
+ 'width': '300',
+ 'height': '250'
+ }
+ asset = {
+ 'xsi_type': 'CreativeAsset',
+ 'fileName': file_name,
+ 'assetByteArray': image_data,
+ 'size': size
+ }
+
+ # Create creative from templates.
+ creative = {
+ 'xsi_type': 'TemplateCreative',
+ 'name': 'Template Creative #%s' % uuid.uuid4(),
+ 'advertiserId': advertiser_id,
+ 'size': size,
+ 'creativeTemplateId': creative_template_id,
+ 'creativeTemplateVariableValues': [
+ {
+ 'xsi_type': 'AssetCreativeTemplateVariableValue',
+ 'uniqueName': 'Imagefile',
+ 'asset': asset
+ },
+ {
+ 'xsi_type': 'LongCreativeTemplateVariableValue',
+ 'uniqueName': 'Imagewidth',
+ 'value': '300'
+ },
+ {
+ 'xsi_type': 'LongCreativeTemplateVariableValue',
+ 'uniqueName': 'Imageheight',
+ 'value': '250'
+ },
+ {
+ 'xsi_type': 'UrlCreativeTemplateVariableValue',
+ 'uniqueName': 'ClickthroughURL',
+ 'value': 'www.google.com'
+ },
+ {
+ 'xsi_type': 'StringCreativeTemplateVariableValue',
+ 'uniqueName': 'Targetwindow',
+ 'value': '_blank'
+ }
+ ]
+ }
+
+ # Call service to create the creative.
+ creative = creative_service.createCreatives([creative])[0]
+
+ # Display results.
+ print('Template creative with id "%s", name "%s", and type "%s" was '
+ 'created and can be previewed at %s.'
+ % (creative['id'], creative['name'],
+ ad_manager.AdManagerClassType(creative), creative['previewUrl']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ADVERTISER_ID)
diff --git a/examples/ad_manager/v202202/creative_service/create_creatives.py b/examples/ad_manager/v202202/creative_service/create_creatives.py
new file mode 100755
index 00000000..a5810a60
--- /dev/null
+++ b/examples/ad_manager/v202202/creative_service/create_creatives.py
@@ -0,0 +1,93 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new image creatives for a given advertiser.
+
+To determine which companies are advertisers, run get_advertisers.py.
+To determine which creatives already exist, run get_all_creatives.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import os
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set id of the advertiser (company) that all creatives will be assigned to.
+ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
+
+
+def main(client, advertiser_id):
+ # Initialize appropriate service.
+ creative_service = client.GetService('CreativeService', version='v202202')
+
+ # Create creative objects.
+ creatives = []
+ with open(
+ os.path.join(
+ os.path.split(__file__)[0], '..', '..', 'data',
+ 'medium_rectangle.jpg'), 'rb') as image:
+ image_data = image.read()
+
+ for _ in range(5):
+ # Create creative size.
+ size = {
+ 'width': '300',
+ 'height': '250'
+ }
+
+ # Create image asset.
+ creative_asset = {
+ 'xsi_type': 'CreativeAsset',
+ 'fileName': 'image.jpg',
+ 'assetByteArray': image_data,
+ 'size': size
+ }
+
+ # Create an image creative.
+ creative = {
+ 'xsi_type': 'ImageCreative',
+ 'name': 'Image Creative #%s' % uuid.uuid4(),
+ 'advertiserId': advertiser_id,
+ 'destinationUrl': 'http://google.com',
+ 'size': size,
+ 'primaryImageAsset': creative_asset
+ }
+
+ creatives.append(creative)
+
+ # Add creatives.
+ creatives = creative_service.createCreatives(creatives)
+
+ # Display results.
+ for creative in creatives:
+ print('Image creative with id "%s", name "%s", and type "%s" was '
+ 'created and can be previewed at %s.' %
+ (creative['id'], creative['name'],
+ ad_manager.AdManagerClassType(creative), creative['previewUrl']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ADVERTISER_ID)
diff --git a/examples/ad_manager/v202202/creative_service/create_custom_creative.py b/examples/ad_manager/v202202/creative_service/create_custom_creative.py
new file mode 100755
index 00000000..c04bdea0
--- /dev/null
+++ b/examples/ad_manager/v202202/creative_service/create_custom_creative.py
@@ -0,0 +1,88 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example creates a custom creative for a given advertiser.
+
+This feature is only available to Ad Manager 360 solution networks. To determine
+which companies are advertisers, run get_advertisers.py. To determine
+which creative templates exist, run get_all_creative_templates.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import os
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set id of the advertiser (company) that the creative will be assigned to.
+ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
+
+
+def main(client, advertiser_id):
+ # Initialize appropriate service.
+ creative_service = client.GetService('CreativeService', version='v202202')
+
+ # Get the image data for the creative.
+ image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data',
+ 'medium_rectangle.jpg'), 'r').read()
+
+ # Create the HTML snippet used in the custom creative.
+ html_snippet = (' Click above for '
+ 'great deals!') % ('%%CLICK_URL_UNESC%%', '%%DEST_URL%%',
+ '%%FILE:IMAGE_ASSET%%')
+
+ # Create custom creative.
+ creative = {
+ 'xsi_type': 'CustomCreative',
+ 'name': 'Custom Creative #%s' % uuid.uuid4(),
+ 'advertiserId': advertiser_id,
+ 'size': {'width': '300', 'height': '250'},
+ 'destinationUrl': 'http://google.com',
+ 'customCreativeAssets': [
+ {
+ 'xsi_type': 'CustomCreativeAsset',
+ 'macroName': 'IMAGE_ASSET',
+ 'asset': {
+ 'assetByteArray': image_data,
+ 'fileName': 'image%s.jpg' % uuid.uuid4()
+ }
+ }
+ ],
+ 'htmlSnippet': html_snippet
+ }
+
+ # Call service to create the creative.
+ creatives = creative_service.createCreatives([creative])
+
+ # Display results.
+ if creatives:
+ creative = creatives[0]
+ print('Template creative with id "%s", name "%s", and type "%s" was '
+ 'created and can be previewed at %s.'
+ % (creative['id'], creative['name'],
+ ad_manager.AdManagerClassType(creative), creative['previewUrl']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ADVERTISER_ID)
diff --git a/examples/ad_manager/v202202/creative_service/create_native_creative.py b/examples/ad_manager/v202202/creative_service/create_native_creative.py
new file mode 100755
index 00000000..5fbf0988
--- /dev/null
+++ b/examples/ad_manager/v202202/creative_service/create_native_creative.py
@@ -0,0 +1,132 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates a new native creative for a given advertiser.
+
+To determine which companies are advertisers, run get_advertisers.py.
+
+The code in this example will use app data from the Google sample app
+'Pie Noon':
+
+https://play.google.com/store/apps/details?id=com.google.fpl.pie_noon&hl=en
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+"""
+
+import uuid
+from urllib.request import urlopen
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set id of the advertiser (company) that the creative will be assigned to.
+ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE'
+ICON_URL = ('https://lh4.ggpht.com/GIGNKdGHMEHFDw6TM2bgAUDKPQQRIReKZPqEpMeEhZO'
+ 'PYnTdOQGaSpGSEZflIFs0iw=h300')
+APP_ICON_SMALL = ('https://lh6.ggpht.com/Jzvjne5CLs6fJ1MHF-XeuUfpABzl0YNMlp4Rp'
+ 'HnvPRCIj4--eTDwtyouwUDzVVekXw=w300')
+
+
+def main(client, advertiser_id):
+ # Initialize appropriate service.
+ creative_service = client.GetService('CreativeService', version='v202202')
+
+ # Use the system defined native app install creative template.
+ creative_template_id = '10004400'
+
+ image_data = urlopen(ICON_URL).read()
+
+ app_icon_data = urlopen(APP_ICON_SMALL).read()
+
+ # Create creative from templates.
+ creative = {
+ 'xsi_type': 'TemplateCreative',
+ 'name': 'Native Creative #%s' % uuid.uuid4(),
+ 'advertiserId': advertiser_id,
+ 'size': {'width': '1', 'height': '1', 'isAspectRatio': False},
+ 'creativeTemplateId': creative_template_id,
+ 'destinationUrl': ('https://play.google.com/store/apps/details?id='
+ 'com.google.fpl.pie_noon'),
+ 'creativeTemplateVariableValues': [
+ {
+ 'xsi_type': 'AssetCreativeTemplateVariableValue',
+ 'uniqueName': 'Image',
+ 'asset': {
+ 'assetByteArray': image_data,
+ 'fileName': 'file%s.png' % uuid.uuid4()
+ }
+ },
+ {
+ 'xsi_type': 'AssetCreativeTemplateVariableValue',
+ 'uniqueName': 'Appicon',
+ 'asset': {
+ 'assetByteArray': app_icon_data,
+ 'fileName': 'appicon%s.png' % uuid.uuid4()
+ }
+ },
+ {
+ 'xsi_type': 'StringCreativeTemplateVariableValue',
+ 'uniqueName': 'Price',
+ 'value': 'Free'
+ },
+ {
+ 'xsi_type': 'StringCreativeTemplateVariableValue',
+ 'uniqueName': 'Calltoaction',
+ 'value': 'Install'
+ },
+ {
+ 'xsi_type': 'StringCreativeTemplateVariableValue',
+ 'uniqueName': 'Starrating',
+ 'value': '4'
+ },
+ {
+ 'xsi_type': 'StringCreativeTemplateVariableValue',
+ 'uniqueName': 'Store',
+ 'value': 'Google Play'
+ },
+ {
+ 'xsi_type': 'UrlCreativeTemplateVariableValue',
+ 'uniqueName': 'DeeplinkclickactionURL',
+ 'value': 'market://details?id=com.google.fpl.pie_noon'
+ },
+ {
+ 'xsi_type': 'StringCreativeTemplateVariableValue',
+ 'uniqueName': 'Body',
+ 'value': 'Try multi-screen mode!'
+ },
+ {
+ 'xsi_type': 'StringCreativeTemplateVariableValue',
+ 'uniqueName': 'Headline',
+ 'value': 'Pie Noon'
+ }
+ ]
+ }
+
+ # Call service to create the creative.
+ creative = creative_service.createCreatives([creative])[0]
+
+ # Display results.
+ print('Native creative with id "%s" and name "%s" was '
+ 'created and can be previewed at %s.'
+ % (creative['id'], creative['name'], creative['previewUrl']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ADVERTISER_ID)
diff --git a/examples/ad_manager/v202202/creative_service/create_video_creatives.py b/examples/ad_manager/v202202/creative_service/create_video_creatives.py
new file mode 100755
index 00000000..d927ad47
--- /dev/null
+++ b/examples/ad_manager/v202202/creative_service/create_video_creatives.py
@@ -0,0 +1,66 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates a new video creative for a given advertiser.
+
+To determine which companies are advertisers, run get_advertisers.py.
+To determine which creatives already exist, run get_all_creatives.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+"""
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set id of the advertiser (company) that the creative will be assigned to.
+ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE'
+
+
+def main(client, advertiser_id):
+ # Initialize appropriate service.
+ creative_service = client.GetService('CreativeService', version='v202202')
+
+ # Create a video creative.
+ creative = {
+ 'xsi_type': 'VideoCreative',
+ 'name': 'Video Creative #%s' % uuid.uuid4(),
+ 'advertiserId': advertiser_id,
+ 'size': {'width': '640', 'height': '360', 'isAspectRatio': False},
+ 'destinationUrl': 'https://google.com',
+ 'duration': '115000',
+ 'videoSourceUrl': (
+ 'https://storage.googleapis.com/interactive-media-ads/media/'
+ 'android.mp4')
+ }
+
+ # Call service to create the creative.
+ creative = creative_service.createCreatives([creative])[0]
+
+ # Display results.
+ print('Video creative with id "%s" and name "%s" was created and can be '
+ 'previewed at:\n%s.'
+ % (creative['id'], creative['name'], creative['vastPreviewUrl']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ADVERTISER_ID)
diff --git a/examples/ad_manager/v202202/creative_service/get_all_creatives.py b/examples/ad_manager/v202202/creative_service/get_all_creatives.py
new file mode 100755
index 00000000..f7d62f25
--- /dev/null
+++ b/examples/ad_manager/v202202/creative_service/get_all_creatives.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all creatives.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ creative_service = client.GetService('CreativeService', version='v202202')
+
+ # Create a statement to select creatives.
+ statement = ad_manager.StatementBuilder(version='v202202')
+
+ # Retrieve a small amount of creatives at a time, paging
+ # through until all creatives have been retrieved.
+ while True:
+ response = creative_service.getCreativesByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for creative in response['results']:
+ # Print out some information for each creative.
+ print('Creative with ID "%d" and name "%s" was found.\n' %
+ (creative['id'], creative['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/creative_service/get_image_creatives.py b/examples/ad_manager/v202202/creative_service/get_image_creatives.py
new file mode 100755
index 00000000..86dab75d
--- /dev/null
+++ b/examples/ad_manager/v202202/creative_service/get_image_creatives.py
@@ -0,0 +1,50 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all image creatives.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ creative_service = client.GetService('CreativeService', version='v202202')
+ # Create a statement to select creatives.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('creativeType = :creativeType')
+ .WithBindVariable('creativeType', 'ImageCreative'))
+
+ # Retrieve a small amount of creatives at a time, paging
+ # through until all creatives have been retrieved.
+ while True:
+ response = creative_service.getCreativesByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for creative in response['results']:
+ # Print out some information for each creative.
+ print('Creative with ID "%d" and name "%s" was found.\n' %
+ (creative['id'], creative['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/creative_service/update_creatives.py b/examples/ad_manager/v202202/creative_service/update_creatives.py
new file mode 100755
index 00000000..868990a6
--- /dev/null
+++ b/examples/ad_manager/v202202/creative_service/update_creatives.py
@@ -0,0 +1,71 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates the destination URL of a single image creative.
+
+To determine which image creatives exist, run get_all_creatives.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+IMAGE_CREATIVE_ID = 'INSERT_IMAGE_CREATIVE_ID_HERE'
+
+
+def main(client, image_creative_id):
+ # Initialize appropriate service.
+ creative_service = client.GetService('CreativeService', version='v202202')
+
+ # Create statement object to get the creative by ID.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('creativeType = :type AND id = :id')
+ .WithBindVariable('type', 'ImageCreative')
+ .WithBindVariable('id', int(image_creative_id))
+ .Limit(1))
+
+ # Get creatives by statement.
+ response = creative_service.getCreativesByStatement(
+ statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ # Update each local creative object by changing its destination URL.
+ updated_creatives = []
+ for creative in response['results']:
+ creative['destinationUrl'] = 'http://news.google.com'
+ updated_creatives.append(creative)
+
+ # Update creatives remotely.
+ creatives = creative_service.updateCreatives(updated_creatives)
+
+ # Display results.
+ for creative in creatives:
+ print('Image creative with id "%s" and destination URL "%s" was '
+ 'updated.' % (creative['id'], creative['destinationUrl']))
+ else:
+ print('No creatives found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, IMAGE_CREATIVE_ID)
diff --git a/examples/ad_manager/v202202/creative_set_service/__init__.py b/examples/ad_manager/v202202/creative_set_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202202/creative_set_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202202/creative_set_service/associate_creative_set_to_line_item.py b/examples/ad_manager/v202202/creative_set_service/associate_creative_set_to_line_item.py
new file mode 100755
index 00000000..f371563b
--- /dev/null
+++ b/examples/ad_manager/v202202/creative_set_service/associate_creative_set_to_line_item.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Creates a line item creative association for a creative set.
+
+To create creative sets, run create_creative_set.py. To create creatives, run
+create_creatives.py. To determine which LICAs exist, run get_all_licas.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+CREATIVE_SET_ID = 'INSERT_CREATIVE_SET_ID_HERE'
+LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
+
+
+def main(client, creative_set_id, line_item_id):
+ # Initialize appropriate service.
+ lica_service = client.GetService(
+ 'LineItemCreativeAssociationService', version='v202202')
+
+ # Create LICA for a creative set.
+ lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id}
+
+ # Add LICA.
+ lica = lica_service.createLineItemCreativeAssociations([lica])
+
+ # Display results.
+ print(('LICA with line item ID "%s" and creative set ID "%s" was '
+ 'created.') % (lica['lineItemId'], lica['creativeSetId']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CREATIVE_SET_ID, LINE_ITEM_ID)
diff --git a/examples/ad_manager/v202202/creative_set_service/create_creative_set.py b/examples/ad_manager/v202202/creative_set_service/create_creative_set.py
new file mode 100755
index 00000000..01b0ebc7
--- /dev/null
+++ b/examples/ad_manager/v202202/creative_set_service/create_creative_set.py
@@ -0,0 +1,62 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new creative sets.
+
+To determine which creative sets exist, run get_all_creative_sets.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+MASTER_CREATIVE_ID = 'INSERT_MASTER_CREATIVE_ID_HERE'
+COMPANION_CREATIVE_ID = 'INSERT_COMPANION_CREATIVE_ID_HERE'
+
+
+def main(client, master_creative_id, companion_creative_id):
+ # Initialize appropriate service.
+ creative_set_service = client.GetService('CreativeSetService',
+ version='v202202')
+
+ # Create creative set objects.
+ creative_set = {'name': 'Creative set #%s' % uuid.uuid4(),
+ 'masterCreativeId': master_creative_id,
+ 'companionCreativeIds': [companion_creative_id]}
+
+ # Add creative sets.
+ creative_set = creative_set_service.createCreativeSet(creative_set)
+
+ # Display results.
+ if creative_set:
+ print(('Creative set with ID "%s", master creative ID "%s", and '
+ 'companion creative IDs "%s" was created.') %
+ (creative_set['id'], creative_set['masterCreativeId'], ','.join(
+ str(v) for v in creative_set['companionCreativeIds'])))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, MASTER_CREATIVE_ID, COMPANION_CREATIVE_ID)
diff --git a/examples/ad_manager/v202202/creative_set_service/get_all_creative_sets.py b/examples/ad_manager/v202202/creative_set_service/get_all_creative_sets.py
new file mode 100755
index 00000000..5b9e192f
--- /dev/null
+++ b/examples/ad_manager/v202202/creative_set_service/get_all_creative_sets.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all creative sets.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ creative_set_service = client.GetService(
+ 'CreativeSetService', version='v202202')
+
+ # Create a statement to select creative sets.
+ statement = ad_manager.StatementBuilder(version='v202202')
+
+ # Retrieve a small amount of creative sets at a time, paging
+ # through until all creative sets have been retrieved.
+ while True:
+ response = creative_set_service.getCreativeSetsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for creative_set in response['results']:
+ # Print out some information for each creative set.
+ print('Creative set with ID "%d" and name "%s" was found.\n' %
+ (creative_set['id'], creative_set['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/creative_set_service/get_creative_sets_for_master_creative.py b/examples/ad_manager/v202202/creative_set_service/get_creative_sets_for_master_creative.py
new file mode 100755
index 00000000..51ea56f3
--- /dev/null
+++ b/examples/ad_manager/v202202/creative_set_service/get_creative_sets_for_master_creative.py
@@ -0,0 +1,54 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all creative sets for a master creative.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+MASTER_CREATIVE_ID = 'INSERT_MASTER_CREATIVE_ID_HERE'
+
+
+def main(client, master_creative_id):
+ # Initialize appropriate service.
+ creative_set_service = client.GetService(
+ 'CreativeSetService', version='v202202')
+ # Create a statement to select creative sets.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('masterCreativeId = :masterCreativeId')
+ .WithBindVariable('masterCreativeId', master_creative_id))
+
+ # Retrieve a small amount of creative sets at a time, paging
+ # through until all creative sets have been retrieved.
+ while True:
+ response = creative_set_service.getCreativeSetsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for creative_set in response['results']:
+ # Print out some information for each creative set.
+ print('Creative set with ID "%d" and name "%s" was found.\n' %
+ (creative_set['id'], creative_set['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, MASTER_CREATIVE_ID)
diff --git a/examples/ad_manager/v202202/creative_set_service/update_creative_set.py b/examples/ad_manager/v202202/creative_set_service/update_creative_set.py
new file mode 100755
index 00000000..799f72a4
--- /dev/null
+++ b/examples/ad_manager/v202202/creative_set_service/update_creative_set.py
@@ -0,0 +1,73 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates a creative set by adding a companion creative.
+
+To determine which creative sets exist, run get_all_creative_sets.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the creative set to update.
+CREATIVE_SET_ID = 'INSERT_CREATIVE_SET_ID_HERE'
+COMPANION_CREATIVE_ID = 'INSERT_COMPANION_CREATIVE_ID_HERE'
+
+
+def main(client, creative_set_id, companion_creative_id):
+ # Initialize appropriate service.
+ creative_set_service = client.GetService('CreativeSetService',
+ version='v202202')
+
+ # Create statement to select a single creative set by ID.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('id = :creativeSetId')
+ .WithBindVariable('creativeSetId', int(creative_set_id)))
+
+ # Get creative set.
+ response = creative_set_service.getCreativeSetsByStatement(
+ statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ updated_created_sets = []
+ for creative_set in response['results']:
+ creative_set['companionCreativeIds'].append(companion_creative_id)
+ updated_created_sets.append(creative_set)
+
+ # Update the creative sets on the server.
+ creative_sets = creative_set_service.updateCreativeSet(updated_created_sets)
+
+ # Display results.
+ for creative_set in creative_sets:
+ print(('Creative set with ID "%s", master creative ID "%s", and '
+ 'companion creative IDs {%s} was updated.')
+ % (creative_set['id'], creative_set['masterCreativeId'],
+ ','.join(creative_set['companionCreativeIds'])))
+ else:
+ print('No creative sets found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CREATIVE_SET_ID, COMPANION_CREATIVE_ID)
diff --git a/examples/ad_manager/v202202/creative_template_service/__init__.py b/examples/ad_manager/v202202/creative_template_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202202/creative_template_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202202/creative_template_service/get_all_creative_templates.py b/examples/ad_manager/v202202/creative_template_service/get_all_creative_templates.py
new file mode 100755
index 00000000..def20016
--- /dev/null
+++ b/examples/ad_manager/v202202/creative_template_service/get_all_creative_templates.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all creative templates.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ creative_template_service = client.GetService(
+ 'CreativeTemplateService', version='v202202')
+
+ # Create a statement to select creative templates.
+ statement = ad_manager.StatementBuilder(version='v202202')
+
+ # Retrieve a small amount of creative templates at a time, paging
+ # through until all creative templates have been retrieved.
+ while True:
+ response = creative_template_service.getCreativeTemplatesByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for creative_template in response['results']:
+ # Print out some information for each creative template.
+ print('Creative template with ID "%d" and name "%s" was found.\n' %
+ (creative_template['id'], creative_template['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/creative_template_service/get_system_defined_creative_templates.py b/examples/ad_manager/v202202/creative_template_service/get_system_defined_creative_templates.py
new file mode 100755
index 00000000..3c954c22
--- /dev/null
+++ b/examples/ad_manager/v202202/creative_template_service/get_system_defined_creative_templates.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all system defined creative templates.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ creative_template_service = client.GetService(
+ 'CreativeTemplateService', version='v202202')
+ # Create a statement to select creative templates.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('type = :type')
+ .WithBindVariable('type', 'SYSTEM_DEFINED'))
+
+ # Retrieve a small amount of creative templates at a time, paging
+ # through until all creative templates have been retrieved.
+ while True:
+ response = creative_template_service.getCreativeTemplatesByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for creative_template in response['results']:
+ # Print out some information for each creative template.
+ print('Creative template with ID "%d" and name "%s" was found.\n' %
+ (creative_template['id'], creative_template['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/creative_wrapper_service/create_creative_wrappers.py b/examples/ad_manager/v202202/creative_wrapper_service/create_creative_wrappers.py
new file mode 100755
index 00000000..4ac1c575
--- /dev/null
+++ b/examples/ad_manager/v202202/creative_wrapper_service/create_creative_wrappers.py
@@ -0,0 +1,63 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates a new creative wrapper.
+
+Creative wrappers must be associated with a LabelType.CREATIVE_WRAPPER label and
+applied to ad units by AdUnit.appliedLabels. To determine which creative
+wrappers exist, run get_all_creative_wrappers.py
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+LABEL_ID = 'INSERT_CREATIVE_WRAPPER_LABEL_ID_HERE'
+
+
+def main(client, label_id):
+ # Initialize appropriate service.
+ creative_wrapper_service = client.GetService('CreativeWrapperService',
+ version='v202202')
+
+ # Create creative wrapper objects.
+ creative_wrapper = {
+ # A label can only be associated with one creative wrapper.
+ 'labelId': label_id,
+ 'ordering': 'INNER',
+ 'htmlHeader': 'My creative wrapper header',
+ 'htmlFooter': 'My creative wrapper footer'
+ }
+
+ # Add creative wrapper.
+ creative_wrappers = creative_wrapper_service.createCreativeWrappers(
+ [creative_wrapper])
+
+ # Display results.
+ for creative_wrapper in creative_wrappers:
+ print('Creative wrapper with ID "%s" applying to label "%s" was '
+ 'created.' % (creative_wrapper['id'], creative_wrapper['labelId']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, LABEL_ID)
diff --git a/examples/ad_manager/v202202/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/ad_manager/v202202/creative_wrapper_service/deactivate_creative_wrapper.py
new file mode 100755
index 00000000..533bdad7
--- /dev/null
+++ b/examples/ad_manager/v202202/creative_wrapper_service/deactivate_creative_wrapper.py
@@ -0,0 +1,78 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example deactivates a creative wrapper belonging to a label.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+LABEL_ID = 'INSERT_LABEL_ID_HERE'
+
+
+def main(client, label_id):
+ # Initialize appropriate service.
+ creative_wrapper_service = client.GetService('CreativeWrapperService',
+ version='v202202')
+
+ # Create a query to select the active creative wrappers for the given label.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('status = :status AND labelId = :labelId')
+ .WithBindVariable('status', 'ACTIVE')
+ .WithBindVariable('labelId', int(label_id)))
+
+ creative_wrappers_deactivated = 0
+
+ # Get creative wrappers by statement.
+ while True:
+ response = creative_wrapper_service.getCreativeWrappersByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ # Display results.
+ for creative_wrapper in response['results']:
+ print('Creative wrapper with ID "%s" applying to label "%s" with '
+ 'status "%s" will be deactivated.' %
+ (creative_wrapper['id'],
+ creative_wrapper['labelId'],
+ creative_wrapper['status']))
+ # Perform action.
+ result = creative_wrapper_service.performCreativeWrapperAction(
+ {'xsi_type': 'DeactivateCreativeWrappers'}, statement.ToStatement())
+ if result and int(result['numChanges']) > 0:
+ creative_wrappers_deactivated += int(result['numChanges'])
+ statement.offset += statement.limit
+ else:
+ break
+
+ # Display results.
+ if creative_wrappers_deactivated > 0:
+ print('Number of creative wrappers deactivated: %s' %
+ creative_wrappers_deactivated)
+ else:
+ print('No creative wrappers were deactivated.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, LABEL_ID)
diff --git a/examples/ad_manager/v202202/creative_wrapper_service/get_active_creative_wrappers.py b/examples/ad_manager/v202202/creative_wrapper_service/get_active_creative_wrappers.py
new file mode 100755
index 00000000..416c94a9
--- /dev/null
+++ b/examples/ad_manager/v202202/creative_wrapper_service/get_active_creative_wrappers.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all active creative wrappers.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ creative_wrapper_service = client.GetService(
+ 'CreativeWrapperService', version='v202202')
+ # Create a statement to select creative wrappers.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('status = :status')
+ .WithBindVariable('status', 'ACTIVE'))
+
+ # Retrieve a small amount of creative wrappers at a time, paging
+ # through until all creative wrappers have been retrieved.
+ while True:
+ response = creative_wrapper_service.getCreativeWrappersByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for creative_wrapper in response['results']:
+ # Print out some information for each creative wrapper.
+ print('Creative wrapper with ID "%d" and label ID "%d" was found.\n' %
+ (creative_wrapper['id'], creative_wrapper['labelId']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/creative_wrapper_service/get_all_creative_wrappers.py b/examples/ad_manager/v202202/creative_wrapper_service/get_all_creative_wrappers.py
new file mode 100755
index 00000000..4957c174
--- /dev/null
+++ b/examples/ad_manager/v202202/creative_wrapper_service/get_all_creative_wrappers.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all creative wrappers.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ creative_wrapper_service = client.GetService(
+ 'CreativeWrapperService', version='v202202')
+
+ # Create a statement to select creative wrappers.
+ statement = ad_manager.StatementBuilder(version='v202202')
+
+ # Retrieve a small amount of creative wrappers at a time, paging
+ # through until all creative wrappers have been retrieved.
+ while True:
+ response = creative_wrapper_service.getCreativeWrappersByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for creative_wrapper in response['results']:
+ # Print out some information for each creative wrapper.
+ print('Creative wrapper with ID "%d" and label id "%d" was found.\n' %
+ (creative_wrapper['id'], creative_wrapper['labelId']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/creative_wrapper_service/update_creative_wrappers.py b/examples/ad_manager/v202202/creative_wrapper_service/update_creative_wrappers.py
new file mode 100755
index 00000000..db314f66
--- /dev/null
+++ b/examples/ad_manager/v202202/creative_wrapper_service/update_creative_wrappers.py
@@ -0,0 +1,73 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates a creative wrapper to the 'OUTER' wrapping order.
+
+To determine which creative wrappers exist, run get_all_creative_wrappers.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the creative wrapper to update.
+CREATIVE_WRAPPER_ID = 'INSERT_CREATIVE_WRAPPER_ID_HERE'
+
+
+def main(client, creative_wrapper_id):
+ # Initialize appropriate service.
+ creative_wrapper_service = client.GetService('CreativeWrapperService',
+ version='v202202')
+
+ # Create statement to get a creative wrapper by ID.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('id = :creativeWrapperId')
+ .WithBindVariable('creativeWrapperId',
+ int(creative_wrapper_id)))
+
+ # Get creative wrappers.
+ response = creative_wrapper_service.getCreativeWrappersByStatement(
+ statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ updated_creative_wrappers = []
+ for creative_wrapper in response['results']:
+ creative_wrapper['ordering'] = 'OUTER'
+ updated_creative_wrappers.append(creative_wrapper)
+
+ # Update the creative wrappers on the server.
+ creative_wrappers = creative_wrapper_service.updateCreativeWrappers(
+ updated_creative_wrappers)
+
+ # Display results.
+ for creative_wrapper in creative_wrappers:
+ print(('Creative wrapper with ID "%s" and wrapping order "%s" '
+ 'was updated.') % (creative_wrapper['id'],
+ creative_wrapper['ordering']))
+ else:
+ print('No creative wrappers found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CREATIVE_WRAPPER_ID)
diff --git a/examples/ad_manager/v202202/custom_field_service/__init__.py b/examples/ad_manager/v202202/custom_field_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202202/custom_field_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202202/custom_field_service/create_custom_field_options.py b/examples/ad_manager/v202202/custom_field_service/create_custom_field_options.py
new file mode 100755
index 00000000..f944e908
--- /dev/null
+++ b/examples/ad_manager/v202202/custom_field_service/create_custom_field_options.py
@@ -0,0 +1,67 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example creates custom field options for a drop-down custom field.
+
+Once created, custom field options can be found under the options fields of the
+drop-down custom field and they cannot be deleted. To determine which custom
+fields exist, run get_all_custom_fields.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the drop-down custom field to create options for.
+CUSTOM_FIELD_ID = 'INSERT_DROP_DOWN_CUSTOM_FIELD_ID_HERE'
+
+
+def main(client, custom_field_id):
+ # Initialize appropriate service.
+ custom_field_service = client.GetService(
+ 'CustomFieldService', version='v202202')
+
+ # Create custom field options.
+ custom_field_options = [
+ {
+ 'displayName': 'Approved',
+ 'customFieldId': custom_field_id
+ },
+ {
+ 'displayName': 'Unapproved',
+ 'customFieldId': custom_field_id
+ }
+ ]
+
+ # Add custom field options.
+ custom_field_options = custom_field_service.createCustomFieldOptions(
+ custom_field_options)
+
+ # Display results.
+ for custom_field_option in custom_field_options:
+ print('Custom field option with ID "%s" and name "%s" was created.'
+ % (custom_field_option['id'], custom_field_option['displayName']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CUSTOM_FIELD_ID)
diff --git a/examples/ad_manager/v202202/custom_field_service/create_custom_fields.py b/examples/ad_manager/v202202/custom_field_service/create_custom_fields.py
new file mode 100755
index 00000000..7a596091
--- /dev/null
+++ b/examples/ad_manager/v202202/custom_field_service/create_custom_fields.py
@@ -0,0 +1,66 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example creates custom fields.
+
+To determine which custom fields exist, run get_all_custom_fields.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ custom_field_service = client.GetService(
+ 'CustomFieldService', version='v202202')
+
+ # Create custom field objects.
+ custom_fields = [
+ {
+ 'name': 'Customer comments #%s' % uuid.uuid4(),
+ 'entityType': 'LINE_ITEM',
+ 'dataType': 'STRING',
+ 'visibility': 'FULL'
+ }, {
+ 'name': 'Internal approval status #%s' % uuid.uuid4(),
+ 'entityType': 'LINE_ITEM',
+ 'dataType': 'DROP_DOWN',
+ 'visibility': 'FULL'
+ }
+ ]
+
+ # Add custom fields.
+ custom_fields = custom_field_service.createCustomFields(custom_fields)
+
+ # Display results.
+ for custom_field in custom_fields:
+ print('Custom field with ID "%s" and name "%s" was created.'
+ % (custom_field['id'], custom_field['name']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/ad_manager/v202202/custom_field_service/deactivate_all_line_item_custom_fields.py
new file mode 100755
index 00000000..5c4740bf
--- /dev/null
+++ b/examples/ad_manager/v202202/custom_field_service/deactivate_all_line_item_custom_fields.py
@@ -0,0 +1,73 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example deactivates all active line items custom fields.
+
+To determine which custom fields exist, run get_all_custom_fields.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ custom_field_service = client.GetService(
+ 'CustomFieldService', version='v202202')
+
+ # Create statement to select only active custom fields that apply to
+ # line items.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('entityType = :entityType and isActive = :isActive')
+ .WithBindVariable('entityType', 'LINE_ITEM')
+ .WithBindVariable('isActive', True))
+
+ custom_fields_deactivated = 0
+
+ # Get custom fields by statement.
+ while True:
+ response = custom_field_service.getCustomFieldsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ # Display results.
+ for custom_field in response['results']:
+ print('Custom field with ID "%s" and name "%s" will'
+ ' be deactivated.' % (custom_field['id'], custom_field['name']))
+ result = custom_field_service.performCustomFieldAction(
+ {'xsi_type': 'DeactivateCustomFields'}, statement.ToStatement())
+ if result and int(result['numChanges']) > 0:
+ custom_fields_deactivated += int(result['numChanges'])
+ statement.offset += statement.limit
+ else:
+ break
+
+ if custom_fields_deactivated > 0:
+ print('Number of custom fields deactivated: %s' % custom_fields_deactivated)
+ else:
+ print('No custom fields were deactivated.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/custom_field_service/get_all_custom_fields.py b/examples/ad_manager/v202202/custom_field_service/get_all_custom_fields.py
new file mode 100755
index 00000000..71d6a126
--- /dev/null
+++ b/examples/ad_manager/v202202/custom_field_service/get_all_custom_fields.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all custom fields.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ custom_field_service = client.GetService(
+ 'CustomFieldService', version='v202202')
+
+ # Create a statement to select custom fields.
+ statement = ad_manager.StatementBuilder(version='v202202')
+
+ # Retrieve a small amount of custom fields at a time, paging
+ # through until all custom fields have been retrieved.
+ while True:
+ response = custom_field_service.getCustomFieldsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for custom_field in response['results']:
+ # Print out some information for each custom field.
+ print('Custom field with ID "%d" and name "%s" was found.\n' %
+ (custom_field['id'], custom_field['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/custom_field_service/get_custom_fields_for_line_items.py b/examples/ad_manager/v202202/custom_field_service/get_custom_fields_for_line_items.py
new file mode 100755
index 00000000..52726fc1
--- /dev/null
+++ b/examples/ad_manager/v202202/custom_field_service/get_custom_fields_for_line_items.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all custom fields that can be applied to line items.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ custom_field_service = client.GetService(
+ 'CustomFieldService', version='v202202')
+ # Create a statement to select custom fields.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('entityType = :entityType')
+ .WithBindVariable('entityType', 'LINE_ITEM'))
+
+ # Retrieve a small amount of custom fields at a time, paging
+ # through until all custom fields have been retrieved.
+ while True:
+ response = custom_field_service.getCustomFieldsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for custom_field in response['results']:
+ # Print out some information for each custom field.
+ print('Custom field with ID "%d" and name "%s" was found.\n' %
+ (custom_field['id'], custom_field['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/custom_field_service/set_line_item_custom_field_value.py b/examples/ad_manager/v202202/custom_field_service/set_line_item_custom_field_value.py
new file mode 100755
index 00000000..23cbfe44
--- /dev/null
+++ b/examples/ad_manager/v202202/custom_field_service/set_line_item_custom_field_value.py
@@ -0,0 +1,139 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example sets custom field values on a line item.
+
+To determine which custom fields exist, run get_all_custom_fields.py.
+To determine which line item exist, run get_all_line_items.py.
+To create custom field options, run create_custom_field_options.py
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the custom fields, custom field option, and line item.
+CUSTOM_FIELD_ID = 'INSERT_CUSTOM_FIELD_ID_HERE'
+DROP_DOWN_CUSTOM_FIELD_ID = 'INSERT_DROP_DOWN_CUSTOM_FIELD_ID_HERE'
+CUSTOM_FIELD_OPTION_ID = 'INSERT_CUSTOM_FIELD_OPTION_ID_HERE'
+LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
+
+
+def main(client, custom_field_id, drop_down_custom_field_id,
+ custom_field_option_id, line_item_id):
+ # Initialize appropriate services.
+ custom_field_service = client.GetService(
+ 'CustomFieldService', version='v202202')
+
+ line_item_service = client.GetService('LineItemService', version='v202202')
+
+ # Create statement to get a custom field.
+ custom_field_statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('id = :customFieldId')
+ .WithBindVariable('customFieldId', custom_field_id)
+ .Limit(1))
+
+ # Get custom field.
+ custom_field = custom_field_service.getCustomFieldsByStatement(
+ custom_field_statement.ToStatement())['results'][0]
+
+ # Create statement to get a drop down custom field.
+ drop_down_custom_field_statement = (
+ ad_manager.StatementBuilder(version='v202202')
+ .Where('id = :dropDownCustomFieldId')
+ .WithBindVariable('dropDownCustomFieldId', drop_down_custom_field_id)
+ .Limit(1))
+
+ # Get drop-down custom field.
+ drop_down_custom_field = custom_field_service.getCustomFieldsByStatement(
+ drop_down_custom_field_statement.ToStatement())['results'][0]
+
+ # Create statement to get a line item.
+ line_item_statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('id = :lineItemId')
+ .WithBindVariable('lineItemId', line_item_id)
+ .Limit(1))
+
+ # Get line item.
+ line_item = line_item_service.getLineItemsByStatement(
+ line_item_statement.ToStatement())['results'][0]
+
+ if custom_field and line_item:
+ # Create custom field values.
+ custom_field_value = {
+ 'customFieldId': custom_field['id'],
+ 'xsi_type': 'CustomFieldValue',
+ 'value': {
+ 'xsi_type': 'TextValue',
+ 'value': 'Custom field value'
+ }
+ }
+
+ drop_down_custom_field_value = {
+ 'customFieldId': drop_down_custom_field['id'],
+ 'xsi_type': 'DropDownCustomFieldValue',
+ 'customFieldOptionId': custom_field_option_id,
+ }
+
+ custom_field_values = [custom_field_value, drop_down_custom_field_value]
+
+ old_custom_field_values = []
+ if 'customFieldValues' in line_item:
+ old_custom_field_values = line_item['customFieldValues']
+
+ # Only add existing custom field values for different custom fields than the
+ # ones you are setting.
+ for old_custom_field_value in old_custom_field_values:
+ if (old_custom_field_value['customFieldId'] !=
+ custom_field_value['customFieldId']
+ and old_custom_field_value['customFieldId'] !=
+ drop_down_custom_field_value['customFieldId']):
+ custom_field_values.append(old_custom_field_value)
+
+ line_item['customFieldValues'] = custom_field_values
+
+ # Update the line item on the server.
+ line_items = line_item_service.updateLineItems([line_item])
+
+ # Display results.
+ for line_item in line_items:
+ custom_field_value_strings = []
+ for value in line_item['customFieldValues']:
+ if ad_manager.AdManagerClassType(value) == 'CustomFieldValue':
+ custom_field_value_string = (
+ '{ID: "%s", value: "%s"}'
+ % (value['customFieldId'], value['value']['value']))
+ elif ad_manager.AdManagerClassType(value) == 'DropDownCustomFieldValue':
+ custom_field_value_string = (
+ '{ID: "%s", custom field option ID: "%s"}'
+ % (value['customFieldId'], value['customFieldOptionId']))
+ custom_field_value_strings.append(custom_field_value_string)
+ print('Line item with ID "%s" set with custom field values %s.'
+ % (line_item['id'], ','.join(custom_field_value_strings)))
+ else:
+ print('Line item or custom field not found.')
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CUSTOM_FIELD_ID, DROP_DOWN_CUSTOM_FIELD_ID,
+ CUSTOM_FIELD_OPTION_ID, LINE_ITEM_ID)
diff --git a/examples/ad_manager/v202202/custom_field_service/update_custom_fields.py b/examples/ad_manager/v202202/custom_field_service/update_custom_fields.py
new file mode 100755
index 00000000..7db37627
--- /dev/null
+++ b/examples/ad_manager/v202202/custom_field_service/update_custom_fields.py
@@ -0,0 +1,70 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example updates custom field descriptions.
+
+To determine which custom fields exist, run get_all_custom_fields.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the custom field to update.
+CUSTOM_FIELD_ID = 'INSERT_CUSTOM_FIELD_ID_HERE'
+
+
+def main(client, custom_field_id):
+ # Initialize appropriate service.
+ custom_field_service = client.GetService(
+ 'CustomFieldService', version='v202202')
+
+ # Create statement to get a custom field.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('id = :customFieldId')
+ .WithBindVariable('customFieldId', int(custom_field_id)))
+
+ # Get custom field.
+ custom_fields = custom_field_service.getCustomsFieldByStatement(
+ statement.ToStatement())
+
+ if custom_fields:
+ for custom_field in custom_fields:
+ custom_field['description'] += ' Updated.'
+
+ # Update the custom field on the server.
+ custom_fields = custom_field_service.updateCustomFields(custom_fields)
+
+ # Display results.
+ for custom_field in custom_fields:
+ print(('Custom field with ID "%s", name "%s", and '
+ 'description "%s" was updated.')
+ % (custom_field['id'], custom_field['name'],
+ custom_field['description']))
+ else:
+ print('No custom fields found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CUSTOM_FIELD_ID)
diff --git a/examples/ad_manager/v202202/custom_targeting_service/__init__.py b/examples/ad_manager/v202202/custom_targeting_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202202/custom_targeting_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202202/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/ad_manager/v202202/custom_targeting_service/create_custom_targeting_keys_and_values.py
new file mode 100755
index 00000000..b230118c
--- /dev/null
+++ b/examples/ad_manager/v202202/custom_targeting_service/create_custom_targeting_keys_and_values.py
@@ -0,0 +1,132 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example creates new custom targeting keys and values.
+
+To determine which custom targeting keys and values exist, run
+get_all_custom_targeting_keys_and_values.py. To target these custom targeting
+keys and values, run target_custom_criteria_example.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ custom_targeting_service = client.GetService(
+ 'CustomTargetingService', version='v202202')
+
+ # Create custom targeting key objects.
+ keys = [
+ {
+ 'displayName': 'gender',
+ 'name': 'g',
+ 'type': 'PREDEFINED'
+ },
+ {
+ 'displayName': 'car model',
+ 'name': 'c',
+ 'type': 'FREEFORM'
+ },
+ # Add predefined key that may be use for content targeting.
+ {
+ 'displayName': 'genre',
+ 'name': 'genre',
+ 'type': 'PREDEFINED'
+ }
+ ]
+
+ # Add custom targeting keys.
+ keys = custom_targeting_service.createCustomTargetingKeys(keys)
+
+ # Display results.
+ if keys:
+ for key in keys:
+ print('A custom targeting key with id "%s", name "%s", and display '
+ 'name "%s" was created.' % (key['id'], key['name'],
+ key['displayName']))
+ else:
+ print('No keys were created.')
+
+ # Create custom targeting value objects.
+ values = [
+ {
+ 'customTargetingKeyId': keys[0]['id'],
+ 'displayName': 'male',
+ # Name is set to 1 so that the actual name can be hidden from website
+ # users.
+ 'name': '1',
+ 'matchType': 'EXACT'
+ },
+ {
+ 'customTargetingKeyId': keys[0]['id'],
+ 'displayName': 'female',
+ # Name is set to 2 so that the actual name can be hidden from website
+ # users.
+ 'name': '2',
+ 'matchType': 'EXACT'
+ },
+ {
+ 'customTargetingKeyId': keys[1]['id'],
+ 'displayName': 'honda civic',
+ 'name': 'honda civic',
+ 'matchType': 'EXACT'
+ },
+ {
+ 'customTargetingKeyId': keys[1]['id'],
+ 'displayName': 'toyota',
+ 'name': 'toyota',
+ 'matchType': 'EXACT'
+ },
+ {
+ 'customTargetingKeyId': keys[2]['id'],
+ 'displayName': 'comedy',
+ 'name': 'comedy',
+ 'matchType': 'EXACT'
+ },
+ {
+ 'customTargetingKeyId': keys[2]['id'],
+ 'displayName': 'drama',
+ 'name': 'drama',
+ 'matchType': 'EXACT'
+ }
+ ]
+
+ # Add custom targeting values.
+ values = custom_targeting_service.createCustomTargetingValues(values)
+
+ # Display results.
+ if values:
+ for value in values:
+ print('A custom targeting value with id "%s", belonging to key with id'
+ ' "%s", name "%s", and display name "%s" was created.'
+ % (value['id'], value['customTargetingKeyId'], value['name'],
+ value['displayName']))
+ else:
+ print('No values were created.')
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/custom_targeting_service/delete_custom_targeting_keys.py b/examples/ad_manager/v202202/custom_targeting_service/delete_custom_targeting_keys.py
new file mode 100755
index 00000000..4e81d48b
--- /dev/null
+++ b/examples/ad_manager/v202202/custom_targeting_service/delete_custom_targeting_keys.py
@@ -0,0 +1,77 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example deletes a custom targeting key by its name.
+
+To determine which custom targeting keys exist, run
+get_all_custom_targeting_keys_and_values.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+KEY_NAME = 'INSERT_CUSTOM_TARGETING_KEY_NAME_HERE'
+
+
+def main(client, key_name):
+ # Initialize appropriate service.
+ custom_targeting_service = client.GetService(
+ 'CustomTargetingService', version='v202202')
+
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('name = :name')
+ .WithBindVariable('name', key_name))
+
+ deleted_custom_targeting_keys = 0
+
+ # Get custom targeting keys.
+ while True:
+ response = custom_targeting_service.getCustomTargetingKeysByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ key_ids = [str(key['id']) for key in response['results']]
+ action = {'xsi_type': 'DeleteCustomTargetingKeys'}
+ key_statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('id IN (%s)' % ', '.join(key_ids)))
+
+ # Delete custom targeting keys.
+ result = custom_targeting_service.performCustomTargetingKeyAction(
+ action, key_statement.ToStatement())
+
+ if result and int(result['numChanges']) > 0:
+ deleted_custom_targeting_keys += int(result['numChanges'])
+ statement.offset += statement.limit
+ else:
+ break
+
+ if deleted_custom_targeting_keys > 0:
+ print('Number of custom targeting keys deleted: %s'
+ % deleted_custom_targeting_keys)
+ else:
+ print('No custom targeting keys were deleted.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, KEY_NAME)
diff --git a/examples/ad_manager/v202202/custom_targeting_service/delete_custom_targeting_values.py b/examples/ad_manager/v202202/custom_targeting_service/delete_custom_targeting_values.py
new file mode 100755
index 00000000..e9d30a07
--- /dev/null
+++ b/examples/ad_manager/v202202/custom_targeting_service/delete_custom_targeting_values.py
@@ -0,0 +1,77 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Deletes custom targeting values for a given custom targeting key.
+
+To determine which custom targeting keys and values exist, run
+get_all_custom_targeting_keys_and_values.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'
+
+
+def main(client, key_id):
+ # Initialize appropriate service.
+ custom_targeting_service = client.GetService(
+ 'CustomTargetingService', version='v202202')
+
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('customTargetingKeyId = :keyId')
+ .WithBindVariable('keyId', key_id))
+
+ deleted_custom_targeting_values = 0
+
+ # Get custom targeting values.
+ while True:
+ response = custom_targeting_service.getCustomTargetingValuesByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ value_ids = [str(value['id']) for value in response['results']]
+ action = {'xsi_type': 'DeleteCustomTargetingValues'}
+ value_statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('customTargetingKeyId = :keyId '
+ 'AND id IN (%s)' % ', '.join(value_ids))
+ .WithBindVariable('keyId', key_id))
+
+ # Delete custom targeting values.
+ result = custom_targeting_service.performCustomTargetingValueAction(
+ action, value_statement.ToStatement())
+ if result and int(result['numChanges']) > 0:
+ deleted_custom_targeting_values += int(result['numChanges'])
+ statement.offset += statement.limit
+ else:
+ break
+
+ if deleted_custom_targeting_values > 0:
+ print('Number of custom targeting values deleted: %s'
+ % deleted_custom_targeting_values)
+ else:
+ print('No custom targeting values were deleted.')
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, KEY_ID)
diff --git a/examples/ad_manager/v202202/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/ad_manager/v202202/custom_targeting_service/get_all_custom_targeting_keys_and_values.py
new file mode 100755
index 00000000..b07d63d5
--- /dev/null
+++ b/examples/ad_manager/v202202/custom_targeting_service/get_all_custom_targeting_keys_and_values.py
@@ -0,0 +1,72 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all custom targeting keys and values.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ custom_targeting_service = client.GetService(
+ 'CustomTargetingService', version='v202202')
+
+ # Create statement to get all targeting keys.
+ targeting_key_statement = ad_manager.StatementBuilder(version='v202202')
+
+ all_keys = []
+
+ # Get custom targeting keys by statement.
+ while True:
+ response = custom_targeting_service.getCustomTargetingKeysByStatement(
+ targeting_key_statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ all_keys.extend(response['results'])
+ targeting_key_statement.offset += targeting_key_statement.limit
+ else:
+ break
+
+ if all_keys:
+ # Create a statement to select custom targeting values.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('customTargetingKeyId IN (%s)' %
+ ', '.join([str(key['id']) for key in all_keys])))
+
+ # Retrieve a small amount of custom targeting values at a time, paging
+ # through until all custom targeting values have been retrieved.
+ while True:
+ response = custom_targeting_service.getCustomTargetingValuesByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for custom_targeting_value in response['results']:
+ # Print out some information for each custom targeting value.
+ print('Custom targeting value with ID "%d", name "%s", display name '
+ '"%s", and custom targeting key ID "%d" was found.\n' %
+ (custom_targeting_value['id'], custom_targeting_value['name'],
+ custom_targeting_value['displayName'],
+ custom_targeting_value['customTargetingKeyId']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/ad_manager/v202202/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py
new file mode 100755
index 00000000..3e44bd34
--- /dev/null
+++ b/examples/ad_manager/v202202/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py
@@ -0,0 +1,74 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all custom targeting keys and values.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ custom_targeting_service = client.GetService(
+ 'CustomTargetingService', version='v202202')
+
+ # Create statement to get targeting keys for predefined values.
+ targeting_key_statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('type = :type')
+ .WithBindVariable('type', 'PREDEFINED'))
+
+ all_keys = []
+
+ # Get custom targeting keys by statement.
+ while True:
+ response = custom_targeting_service.getCustomTargetingKeysByStatement(
+ targeting_key_statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ all_keys.extend(response['results'])
+ targeting_key_statement.offset += targeting_key_statement.limit
+ else:
+ break
+
+ if all_keys:
+ # Create a statement to select custom targeting values.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('customTargetingKeyId IN (:ids)')
+ .WithBindVariable('ids', [key['id'] for key in all_keys]))
+
+ # Retrieve a small amount of custom targeting values at a time, paging
+ # through until all custom targeting values have been retrieved.
+ while True:
+ response = custom_targeting_service.getCustomTargetingValuesByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for custom_targeting_value in response['results']:
+ # Print out some information for each custom targeting value.
+ print('Custom targeting value with ID "%d", name "%s", display name '
+ '"%s", and custom targeting key ID "%d" was found.\n' %
+ (custom_targeting_value['id'], custom_targeting_value['name'],
+ custom_targeting_value['displayName'],
+ custom_targeting_value['customTargetingKeyId']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/custom_targeting_service/update_custom_targeting_keys.py b/examples/ad_manager/v202202/custom_targeting_service/update_custom_targeting_keys.py
new file mode 100755
index 00000000..93f438cb
--- /dev/null
+++ b/examples/ad_manager/v202202/custom_targeting_service/update_custom_targeting_keys.py
@@ -0,0 +1,67 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example updates the display name of a single custom targeting key.
+
+To determine which custom targeting keys exist, run
+get_all_custom_targeting_keys_and_values.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'
+
+
+def main(client, key_id):
+ # Initialize appropriate service.
+ custom_targeting_service = client.GetService(
+ 'CustomTargetingService', version='v202202')
+
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('id = :keyId')
+ .WithBindVariable('keyId', int(key_id))
+ .Limit(1))
+
+ # Get custom targeting keys by statement.
+ response = custom_targeting_service.getCustomTargetingKeysByStatement(
+ statement.ToStatement())
+
+ # Update each local custom targeting key object by changing its display name.
+ if 'results' in response and len(response['results']):
+ updated_keys = []
+ for key in response['results']:
+ if not key['displayName']:
+ key['displayName'] = key['name']
+ key['displayName'] += ' (Deprecated)'
+ updated_keys.append(key)
+ keys = custom_targeting_service.updateCustomTargetingKeys(updated_keys)
+
+ # Display results.
+ if keys:
+ for key in keys:
+ print('Custom targeting key with id "%s", name "%s", display name '
+ '"%s", and type "%s" was updated.'
+ % (key['id'], key['name'], key['displayName'], key['type']))
+ else:
+ print('No custom targeting keys were found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CUSTOM_TARGETING_KEY_ID)
diff --git a/examples/ad_manager/v202202/custom_targeting_service/update_custom_targeting_values.py b/examples/ad_manager/v202202/custom_targeting_service/update_custom_targeting_values.py
new file mode 100755
index 00000000..66963ead
--- /dev/null
+++ b/examples/ad_manager/v202202/custom_targeting_service/update_custom_targeting_values.py
@@ -0,0 +1,71 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Updates name of custom targeting values belonging to a custom targeting key.
+
+To determine which custom targeting keys exist, run
+get_all_custom_targeting_keys_and_values.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'
+
+
+def main(client, key_id):
+ # Initialize appropriate service.
+ custom_targeting_service = client.GetService(
+ 'CustomTargetingService', version='v202202')
+
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('customTargetingKeyId = :keyId')
+ .WithBindVariable('keyId', int(key_id)))
+
+ while True:
+ # Get custom targeting values by statement.
+ response = custom_targeting_service.getCustomTargetingValuesByStatement(
+ statement.ToStatement())
+
+ # Update each local custom targeting value object by changing its name.
+ if 'results' in response and len(response['results']):
+ updated_values = []
+ for value in response['results']:
+ if not value['displayName']:
+ value['displayName'] = value['name']
+ value['displayName'] += ' (Deprecated)'
+ updated_values.append(value)
+ values = custom_targeting_service.updateCustomTargetingValues(
+ updated_values)
+
+ # Display results.
+ for value in values:
+ print('Custom targeting value with id "%s", name "%s", and display'
+ ' name "%s" was updated.'
+ % (value['id'], value['name'], value['displayName']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ if response['totalResultSetSize'] == 0:
+ print('No custom targeting values were updated.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CUSTOM_TARGETING_KEY_ID)
diff --git a/examples/ad_manager/v202202/forecast_service/get_availability_forecast.py b/examples/ad_manager/v202202/forecast_service/get_availability_forecast.py
new file mode 100755
index 00000000..0e1cb806
--- /dev/null
+++ b/examples/ad_manager/v202202/forecast_service/get_availability_forecast.py
@@ -0,0 +1,251 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets a forecast for a prospective line item.
+
+The prospective line item targets the entire network. The targeting can be
+modified to determine forecasts for other criteria such as custom criteria
+targeting (in addition to targeting the whole network). See
+create_line_items.py for an example of how to create more complex targeting.
+
+"""
+
+
+import datetime
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+import pytz
+
+# Set the ID of the advertiser (company) to forecast for. Setting an advertiser
+# will cause the forecast to apply the appropriate unified blocking rules.
+ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE'
+
+
+def main(client, advertiser_id):
+ # Initialize appropriate service.
+ forecast_service = client.GetService('ForecastService', version='v202202')
+ network_service = client.GetService('NetworkService', version='v202202')
+
+ # get the root ad unit ID to target the entire network.
+ root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId']
+
+ now_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York'))
+ end_datetime = now_datetime + datetime.timedelta(days=5)
+
+ # Create prospective line item.
+ line_item = {
+ 'targeting': {
+ 'inventoryTargeting': {
+ 'targetedAdUnits': [
+ {
+ 'includeDescendants': True,
+ 'adUnitId': root_ad_unit_id,
+ }
+ ]
+ }
+ },
+ 'creativePlaceholders': [
+ {
+ 'size': {
+ 'width': '300',
+ 'height': '250'
+ },
+ 'isAmpOnly': True,
+ },
+ {
+ 'size': {
+ 'width': '120',
+ 'height': '600'
+ }
+ }
+ ],
+ 'lineItemType': 'SPONSORSHIP',
+ 'startDateTimeType': 'IMMEDIATELY',
+ 'endDateTime': end_datetime,
+ 'costType': 'CPM',
+ 'costPerUnit': {
+ 'currencyCode': 'USD',
+ 'microAmount': '2000000'
+ },
+ 'primaryGoal': {
+ 'units': '50',
+ 'unitType': 'IMPRESSIONS',
+ 'goalType': 'DAILY'
+ },
+ 'contractedUnitsBought': '100',
+ 'creativeRotationType': 'EVEN',
+ 'discountType': 'PERCENTAGE',
+ }
+
+ prospective_line_item = {
+ 'lineItem': line_item,
+ 'advertiserId': advertiser_id
+ }
+
+ # Set forecasting options.
+ forecast_options = {
+ 'includeContendingLineItems': True,
+ # The field includeTargetingCriteriaBreakdown can only be set if
+ # breakdowns are not manually specified.
+ # 'includeTargetingCriteriaBreakdown': True,
+ 'breakdown': {
+ 'timeWindows': [
+ now_datetime,
+ now_datetime + datetime.timedelta(days=1),
+ now_datetime + datetime.timedelta(days=2),
+ now_datetime + datetime.timedelta(days=3),
+ now_datetime + datetime.timedelta(days=4),
+ end_datetime
+ ],
+ 'targets': [
+ {
+ # Optional, the name field is only used to identify this
+ # breakdown in the response.
+ 'name': 'United States',
+ 'targeting': {
+ 'inventoryTargeting': {
+ 'targetedAdUnits': [
+ {
+ 'includeDescendants': True,
+ 'adUnitId': root_ad_unit_id,
+ }
+ ]
+ },
+ 'geoTargeting': {
+ 'targetedLocations': [
+ {
+ 'id': '2840',
+ 'displayName': 'US'
+ }
+ ]
+ }
+ }
+ },
+ {
+ # Optional, the name field is only used to identify this
+ # breakdown in the response.
+ 'name': 'Geneva',
+ 'targeting': {
+ 'inventoryTargeting': {
+ 'targetedAdUnits': [
+ {
+ 'includeDescendants': True,
+ 'adUnitId': root_ad_unit_id,
+ }
+ ]
+ },
+ 'geoTargeting': {
+ 'targetedLocations': [
+ {
+ 'id': '20133',
+ 'displayName': 'Geneva'
+ }
+ ]
+ }
+ }
+ }
+ ]
+ }
+ }
+
+ # Get forecast.
+ forecast = forecast_service.getAvailabilityForecast(
+ prospective_line_item, forecast_options)
+ matched = forecast['matchedUnits']
+ available = forecast['availableUnits']
+ possible = forecast['possibleUnits'] if 'possibleUnits' in forecast else None
+ unit_type = forecast['unitType'].lower()
+
+ available_percent_overall, possible_percent_overall = CalculateForecastStats(
+ matched, available, possible)
+
+ contending_line_items = getattr(forecast, 'contendingLineItems', [])
+
+ # Display results.
+ print('%s %s matched overall.' % (matched, unit_type))
+ print('%s%% %s available overall.' % (available_percent_overall, unit_type))
+ print('%d contending line items overall.' % len(contending_line_items))
+ if possible:
+ print('%s%% %s possible overall.' % (possible_percent_overall, unit_type))
+
+ if 'breakdowns' in forecast and len(forecast['breakdowns']):
+ for breakdown in forecast['breakdowns']:
+ print('For breakdown time period %s - %s:' % (
+ FormatSOAPDateTime(breakdown['startTime']),
+ FormatSOAPDateTime(breakdown['endTime'])))
+ for breakdown_entry in breakdown['breakdownEntries']:
+ matched = breakdown_entry['forecast']['matched']
+ available = breakdown_entry['forecast']['available']
+ possible = (breakdown_entry['forecast']['possible']
+ if 'possible' in breakdown_entry['forecast'] else None)
+ name = breakdown_entry['name'] if 'name' in breakdown_entry else None
+ if name:
+ print('\tFor targeting breakdown named \'%s\'' % name)
+ available_percent, possible_percent = CalculateForecastStats(
+ matched, available, possible)
+ print('\t\t%s %s matched.' % (matched, unit_type))
+ print('\t\t%s%% %s available.' % (available_percent, unit_type))
+ if possible:
+ print('\t\t%s%% %s possible.' % (possible_percent, unit_type))
+
+
+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'],
+ value['hour'], value['minute'], value['second'], value['timeZoneId'])
+
+
+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 that are available and possible.
+ """
+ if matched > 0:
+ available_percent = (float(available) / matched) * 100.
+ else:
+ available_percent = 0
+
+ if possible is not None:
+ if matched > 0:
+ possible_percent = (possible/float(matched)) * 100.
+ else:
+ possible_percent = 0
+ else:
+ possible_percent = None
+
+ return available_percent, possible_percent
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ADVERTISER_ID)
diff --git a/examples/ad_manager/v202202/forecast_service/get_availability_forecast_for_line_item.py b/examples/ad_manager/v202202/forecast_service/get_availability_forecast_for_line_item.py
new file mode 100755
index 00000000..ce6a941a
--- /dev/null
+++ b/examples/ad_manager/v202202/forecast_service/get_availability_forecast_for_line_item.py
@@ -0,0 +1,67 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example gets an availability forecast for an existing line item.
+
+To determine which line items exist, run get_all_line_items.py.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the line item to get a forecast for.
+LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
+
+
+def main(client, line_item_id):
+ # Initialize appropriate service.
+ forecast_service = client.GetService('ForecastService', version='v202202')
+
+ # Set forecasting options.
+ forecast_options = {
+ 'includeContendingLineItems': True,
+ 'includeTargetingCriteriaBreakdown': True,
+ }
+
+ # Get forecast for line item.
+ forecast = forecast_service.getAvailabilityForecastById(
+ line_item_id, forecast_options)
+ matched = int(forecast['matchedUnits'])
+ available_units = int(forecast['availableUnits'])
+
+ if matched > 0:
+ available_percent = (float(available_units) / matched) * 100.
+ else:
+ available_percent = 0
+
+ contending_line_items = getattr(forecast, 'contentingLineItems', [])
+
+ # Display results.
+ print('%s %s matched.' % (matched, forecast['unitType'].lower()))
+ print('%s%% %s available.' % (
+ available_percent, forecast['unitType'].lower()))
+ print('%d contending line items.' % len(contending_line_items))
+
+ if 'possibleUnits' in forecast and matched:
+ possible_percent = (int(forecast['possibleUnits'])/float(matched)) * 100.
+ print('%s%% %s possible' % (possible_percent, forecast['unitType'].lower()))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, LINE_ITEM_ID)
diff --git a/examples/ad_manager/v202202/forecast_service/get_delivery_forecast_for_line_items.py b/examples/ad_manager/v202202/forecast_service/get_delivery_forecast_for_line_items.py
new file mode 100755
index 00000000..71c2711e
--- /dev/null
+++ b/examples/ad_manager/v202202/forecast_service/get_delivery_forecast_for_line_items.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example gets a delivery forecast for two existing line items.
+
+To determine which line items exist, run get_all_line_items.py.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the line items to get forecasts for.
+LINE_ITEM_ID_1 = 'INSERT_LINE_ITEM_1_ID_HERE'
+LINE_ITEM_ID_2 = 'INSERT_LINE_ITEM_2_ID_HERE'
+
+
+def main(client, line_item_id1, line_item_id2):
+ # Initialize appropriate service.
+ forecast_service = client.GetService('ForecastService', version='v202202')
+
+ # Get forecast for line item.
+ forecast = forecast_service.getDeliveryForecastByIds(
+ [line_item_id1, line_item_id2], {'ignoredLineItemIds': []})
+
+ for single_forecast in forecast['lineItemDeliveryForecasts']:
+ unit_type = single_forecast['unitType']
+ print('Forecast for line item %d:\n\t%d %s matched\n\t%d %s delivered\n\t'
+ '%d %s predicted\n' % (
+ single_forecast['lineItemId'], single_forecast['matchedUnits'],
+ unit_type, single_forecast['deliveredUnits'], unit_type,
+ single_forecast['predictedDeliveryUnits'], unit_type))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, LINE_ITEM_ID_1, LINE_ITEM_ID_2)
diff --git a/examples/ad_manager/v202202/forecast_service/get_traffic_data.py b/examples/ad_manager/v202202/forecast_service/get_traffic_data.py
new file mode 100755
index 00000000..d20045f6
--- /dev/null
+++ b/examples/ad_manager/v202202/forecast_service/get_traffic_data.py
@@ -0,0 +1,123 @@
+#!/usr/bin/env python
+#
+# Copyright 2020, Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets the forecasted run-of-network traffic data."""
+
+
+import datetime
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ forecast_service = client.GetService('ForecastService', version='v202202')
+ network_service = client.GetService('NetworkService', version='v202202')
+
+ # get the root ad unit ID to target the entire network.
+ root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId']
+
+ # Create a start date that's 7 days in the past and an end date that's 7 days
+ # in the future.
+ today = datetime.date.today()
+ start_date = today - datetime.timedelta(days=7)
+ end_date = today + datetime.timedelta(days=7)
+
+ # Create targeting.
+ targeting = {
+ 'inventoryTargeting': {
+ 'targetedAdUnits': [
+ {
+ 'includeDescendants': True,
+ 'adUnitId': root_ad_unit_id,
+ }
+ ]
+ }
+ }
+
+ # Request the traffic forecast data.
+ traffic_data = forecast_service.getTrafficData({
+ 'targeting': targeting,
+ 'requestedDateRange': {
+ 'startDate': start_date,
+ 'endDate': end_date
+ }
+ })
+
+ # Display historical data.
+ historical_time_series = traffic_data['historicalTimeSeries']
+ if historical_time_series is None:
+ print('No historical data to display.')
+ else:
+ historical_start_date, historical_end_date = GetDatesFromForecastTimeSeries(
+ historical_time_series)
+
+ print('Historical Data:')
+ offset = 0
+ current_date = historical_start_date
+ while current_date <= historical_end_date:
+ print('%s: %d' % (current_date.isoformat(),
+ historical_time_series['values'][offset]))
+ offset += 1
+ current_date = historical_start_date + datetime.timedelta(days=offset)
+
+ # Display forecasted data.
+ forecasted_time_series = traffic_data['forecastedTimeSeries']
+ if forecasted_time_series is None:
+ print('No forecasted data to display.')
+ else:
+ forecasted_start_date, forecasted_end_date = GetDatesFromForecastTimeSeries(
+ forecasted_time_series)
+
+ print('Forecasted Data:')
+ offset = 0
+ current_date = forecasted_start_date
+ while current_date <= forecasted_end_date:
+ print('%s: %d' % (current_date.isoformat(),
+ forecasted_time_series['values'][offset]))
+ offset += 1
+ current_date = forecasted_start_date + datetime.timedelta(days=offset)
+
+
+def GetDatesFromForecastTimeSeries(time_series):
+ """Creates datetime.date objects from a forecast time series object.
+
+ Args:
+ time_series: The forecast time series containing start and end date info.
+
+ Returns:
+ A tuple of datetime.date objects, the first representing the start date and
+ the second representing the end date.
+ """
+ date_range = time_series['timeSeriesDateRange']
+ start_date = datetime.date(
+ date_range['startDate']['year'],
+ date_range['startDate']['month'],
+ date_range['startDate']['day']
+ )
+ end_date = datetime.date(
+ date_range['endDate']['year'],
+ date_range['endDate']['month'],
+ date_range['endDate']['day']
+ )
+ return start_date, end_date
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/inventory_service/__init__.py b/examples/ad_manager/v202202/inventory_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202202/inventory_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202202/inventory_service/archive_ad_units.py b/examples/ad_manager/v202202/inventory_service/archive_ad_units.py
new file mode 100755
index 00000000..85e3e12f
--- /dev/null
+++ b/examples/ad_manager/v202202/inventory_service/archive_ad_units.py
@@ -0,0 +1,75 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example archives ad units.
+
+The parent ad unit and all ad units underneath it will be archived. To create ad
+units, run create_ad_units.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+PARENT_AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE'
+
+
+def main(client, parent_id):
+ # Initialize appropriate service.
+ inventory_service = client.GetService('InventoryService', version='v202202')
+
+ # Create a query to select ad units under the parent ad unit and the parent ad
+ # unit.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('parentId = :parentId or id = :parentId')
+ .WithBindVariable('parentId', int(parent_id)))
+
+ ad_units_archived = 0
+
+ # Get ad units by statement.
+ while True:
+ response = inventory_service.getAdUnitsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for ad_unit in response['results']:
+ print('Ad unit with ID "%s" and name "%s" will be archived.'
+ % (ad_unit['id'], ad_unit['name']))
+ # Perform action.
+ result = inventory_service.performAdUnitAction(
+ {'xsi_type': 'ArchiveAdUnits'}, statement.ToStatement())
+ if result and int(result['numChanges']) > 0:
+ ad_units_archived += int(result['numChanges'])
+ statement.offset += statement.limit
+ else:
+ break
+
+ # Display results.
+ if ad_units_archived > 0:
+ print('Number of ad units archived: %s' % ad_units_archived)
+ else:
+ print('No ad units were archived.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, PARENT_AD_UNIT_ID)
diff --git a/examples/ad_manager/v202202/inventory_service/create_ad_units.py b/examples/ad_manager/v202202/inventory_service/create_ad_units.py
new file mode 100755
index 00000000..490af8ec
--- /dev/null
+++ b/examples/ad_manager/v202202/inventory_service/create_ad_units.py
@@ -0,0 +1,70 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new ad units.
+
+To determine which ad units exist, run get_all_ad_units.py
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+PARENT_AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE'
+
+
+def main(client, parent_id):
+ # Initialize appropriate service.
+ inventory_service = client.GetService('InventoryService', version='v202202')
+
+ # Create ad unit size.
+ ad_unit_size = {
+ 'size': {
+ 'width': '300',
+ 'height': '250'
+ },
+ 'environmentType': 'BROWSER'
+ }
+
+ # Create ad unit objects.
+ ad_unit = {
+ 'name': 'Ad_unit_%s' % uuid.uuid4(),
+ 'parentId': parent_id,
+ 'description': 'Ad unit description.',
+ 'targetWindow': 'BLANK',
+ 'adUnitSizes': [ad_unit_size]
+ }
+
+ # Add ad units.
+ ad_units = inventory_service.createAdUnits([ad_unit])
+
+ # Display results.
+ for ad_unit in ad_units:
+ print('Ad unit with ID "%s" and name "%s" was created.'
+ % (ad_unit['id'], ad_unit['name']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, PARENT_AD_UNIT_ID)
diff --git a/examples/ad_manager/v202202/inventory_service/get_ad_unit_hierarchy.py b/examples/ad_manager/v202202/inventory_service/get_ad_unit_hierarchy.py
new file mode 100755
index 00000000..14760db6
--- /dev/null
+++ b/examples/ad_manager/v202202/inventory_service/get_ad_unit_hierarchy.py
@@ -0,0 +1,115 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example prints all ad unit names as a tree."""
+
+
+# Import appropriate modules from the client library.
+import collections
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate services.
+ network_service = client.GetService('NetworkService', version='v202202')
+ inventory_service = client.GetService('InventoryService', version='v202202')
+
+ # Set the parent ad unit's ID for all children ad units to be fetched from.
+ current_network = network_service.getCurrentNetwork()
+ root_ad_unit_id = current_network['effectiveRootAdUnitId']
+
+ # Create a statement to select only the root ad unit by ID.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('id = :id')
+ .OrderBy('id', ascending=True)
+ .Limit(1)
+ .WithBindVariable('id', root_ad_unit_id))
+
+ # Make a request for the root ad unit
+ response = inventory_service.getAdUnitsByStatement(statement.ToStatement())
+ root_ad_unit = response['results'][0]
+
+ all_ad_units = get_all_ad_units(inventory_service)
+
+ display_hierarchy(root_ad_unit, 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='v202202')
+ .OrderBy('id', ascending=True))
+
+ # Pull down all ad units into a list
+ keep_iterating = True
+ total_results = 0
+ found_ad_units = []
+ while keep_iterating:
+ page = inventory_service.getAdUnitsByStatement(statement.ToStatement())
+ if 'results' in page and len(page['results']):
+ total_results = page['totalResultSetSize']
+ found_ad_units.extend(page['results'])
+
+ statement.offset += statement.limit
+ keep_iterating = statement.offset < total_results
+
+ return found_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.defaultdict(list)
+ for ad_unit in all_ad_units:
+ if 'parentId' in ad_unit:
+ parent_id_to_children[ad_unit['parentId']].append(ad_unit)
+ parent_id_to_children = dict(parent_id_to_children)
+
+ display_hierarchy_helper(root_ad_unit, parent_id_to_children, 0)
+
+
+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([' '] * depth)),
+ root['name'], root['id']))
+
+ # Recurse for each child of this root that has children.
+ for child in parent_id_to_children.get(root['id'], []):
+ display_hierarchy_helper(child, parent_id_to_children, depth + 1)
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/inventory_service/get_all_ad_unit_sizes.py b/examples/ad_manager/v202202/inventory_service/get_all_ad_unit_sizes.py
new file mode 100755
index 00000000..514997c2
--- /dev/null
+++ b/examples/ad_manager/v202202/inventory_service/get_all_ad_unit_sizes.py
@@ -0,0 +1,46 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all ad unit sizes.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ ad_unit_size_service = client.GetService(
+ 'InventoryService', version='v202202')
+
+ # Create a statement to select ad unit sizes.
+ statement = ad_manager.StatementBuilder(version='v202202')
+
+ # Retrieve a small amount of ad unit sizes at a time, paging
+ # through until all ad unit sizes have been retrieved.
+ response = ad_unit_size_service.getAdUnitSizesByStatement(
+ statement.ToStatement())
+ if response:
+ for ad_unit_size in response:
+ # Print out some information for each ad unit size.
+ if 'fullDisplayString' in ad_unit_size:
+ print('Ad unit size with dimensions "%s" was found.\n' %
+ (ad_unit_size['fullDisplayString']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/inventory_service/get_all_ad_units.py b/examples/ad_manager/v202202/inventory_service/get_all_ad_units.py
new file mode 100755
index 00000000..67bf0a1f
--- /dev/null
+++ b/examples/ad_manager/v202202/inventory_service/get_all_ad_units.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all ad units.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ ad_unit_service = client.GetService('InventoryService', version='v202202')
+
+ # Create a statement to select ad units.
+ statement = ad_manager.StatementBuilder(version='v202202')
+
+ # Retrieve a small amount of ad units at a time, paging
+ # through until all ad units have been retrieved.
+ while True:
+ response = ad_unit_service.getAdUnitsByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for ad_unit in response['results']:
+ # Print out some information for each ad unit.
+ print('Ad unit with ID "%s" and name "%s" was found.\n' %
+ (ad_unit['id'], ad_unit['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/inventory_service/get_top_level_ad_units.py b/examples/ad_manager/v202202/inventory_service/get_top_level_ad_units.py
new file mode 100755
index 00000000..8c1723d5
--- /dev/null
+++ b/examples/ad_manager/v202202/inventory_service/get_top_level_ad_units.py
@@ -0,0 +1,58 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all child ad units of the effective root ad unit."""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate services.
+ network_service = client.GetService('NetworkService', version='v202202')
+ inventory_service = client.GetService('InventoryService', version='v202202')
+
+ # Set the parent ad unit's ID for all children ad units to be fetched from.
+ current_network = network_service.getCurrentNetwork()
+ parent_ad_unit_id = current_network['effectiveRootAdUnitId']
+
+ # Create a statement to select ad units under the parent ad unit.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('parentId = :parentId')
+ .OrderBy('id', ascending=True)
+ .WithBindVariable('parentId', parent_ad_unit_id))
+
+ # Retrieve a small amount of ad units at a time, paging
+ # through until all ad units have been retrieved.
+ while True:
+ response = inventory_service.getAdUnitsByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for ad_unit in response['results']:
+ # Print out some information for each ad unit.
+ print('Ad unit with ID "%s" and name "%s" was found.\n' %
+ (ad_unit['id'], ad_unit['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/inventory_service/update_ad_units.py b/examples/ad_manager/v202202/inventory_service/update_ad_units.py
new file mode 100755
index 00000000..f2a84e7e
--- /dev/null
+++ b/examples/ad_manager/v202202/inventory_service/update_ad_units.py
@@ -0,0 +1,82 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates ad unit sizes by adding a banner ad size.
+
+To determine which ad units exist, run get_all_ad_units.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+# Set the ID of the ad unit to get.
+AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE'
+
+
+def main(client, ad_unit_id):
+ # Initialize appropriate service.
+ inventory_service = client.GetService('InventoryService', version='v202202')
+
+ # Create a statement to select a single ad unit by ID.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('id = :id')
+ .WithBindVariable('id', ad_unit_id))
+
+ # Get ad units by statement.
+ response = inventory_service.getAdUnitsByStatement(
+ statement.ToStatement())
+
+ # Add the size 468x60 to the ad unit.
+ ad_unit_size = {
+ 'size': {
+ 'width': '468',
+ 'height': '60'
+ },
+ 'environmentType': 'BROWSER'
+ }
+
+ if 'results' in response and len(response['results']):
+ updated_ad_units = []
+ for ad_unit in response['results']:
+ if 'adUnitSizes' not in ad_unit:
+ ad_unit['adUnitSizes'] = []
+ ad_unit['adUnitSizes'].append(ad_unit_size)
+ updated_ad_units.append(ad_unit)
+
+ # Update ad unit on the server.
+ ad_units = inventory_service.updateAdUnits(updated_ad_units)
+
+ # Display results.
+ for ad_unit in ad_units:
+ ad_unit_sizes = ['{%s x %s}' % (size['size']['width'],
+ size['size']['height'])
+ for size in ad_unit['adUnitSizes']]
+ print('Ad unit with ID "%s", name "%s", and sizes [%s] was updated'
+ % (ad_unit['id'], ad_unit['name'], ','.join(ad_unit_sizes)))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, AD_UNIT_ID)
diff --git a/examples/ad_manager/v202202/label_service/__init__.py b/examples/ad_manager/v202202/label_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202202/label_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202202/label_service/create_labels.py b/examples/ad_manager/v202202/label_service/create_labels.py
new file mode 100755
index 00000000..b3cf9876
--- /dev/null
+++ b/examples/ad_manager/v202202/label_service/create_labels.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new labels.
+
+To determine which labels exist, run get_all_labels.py. This feature is only
+available to Ad Manager 360 solution networks.
+"""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ label_service = client.GetService('LabelService', version='v202202')
+
+ # Create label objects.
+ labels = []
+ for _ in range(5):
+ label = {
+ 'name': 'Label #%s' % uuid.uuid4(),
+ 'isActive': 'true',
+ 'types': ['COMPETITIVE_EXCLUSION']
+ }
+ labels.append(label)
+
+ # Add Labels.
+ labels = label_service.createLabels(labels)
+
+ # Display results.
+ for label in labels:
+ print('Label with id "%s", name "%s", and types {%s} was found.'
+ % (label['id'], label['name'], ','.join(label['types'])))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/label_service/deactivate_labels.py b/examples/ad_manager/v202202/label_service/deactivate_labels.py
new file mode 100755
index 00000000..c3067b3e
--- /dev/null
+++ b/examples/ad_manager/v202202/label_service/deactivate_labels.py
@@ -0,0 +1,65 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example deactivates all active Labels.
+
+To determine which labels exist, run get_all_labels.py. This feature is only
+available to Ad Manager 360 solution networks.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ label_service = client.GetService('LabelService', version='v202202')
+
+ # Create query.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('isActive = :isActive')
+ .WithBindVariable('isActive', True))
+
+ labels_deactivated = 0
+
+ # Get labels by statement.
+ while True:
+ response = label_service.getLabelsByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for label in response['results']:
+ print('Label with id "%s" and name "%s" will be '
+ 'deactivated.' % (label['id'], label['name']))
+ # Perform action.
+ result = label_service.performLabelAction(
+ {'xsi_type': 'DeactivateLabels'}, statement.ToStatement())
+ if result and int(result['numChanges']) > 0:
+ labels_deactivated += int(result['numChanges'])
+ statement.offset += statement.limit
+ else:
+ break
+
+ # Display results.
+ if labels_deactivated > 0:
+ print('Number of labels deactivated: %s' % labels_deactivated)
+ else:
+ print('No labels were deactivated.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/label_service/get_active_labels.py b/examples/ad_manager/v202202/label_service/get_active_labels.py
new file mode 100755
index 00000000..e31a0e45
--- /dev/null
+++ b/examples/ad_manager/v202202/label_service/get_active_labels.py
@@ -0,0 +1,50 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all active labels.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ label_service = client.GetService('LabelService', version='v202202')
+ # Create a statement to select labels.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('isActive = :isActive')
+ .WithBindVariable('isActive', True))
+
+ # Retrieve a small amount of labels at a time, paging
+ # through until all labels have been retrieved.
+ while True:
+ response = label_service.getLabelsByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for label in response['results']:
+ # Print out some information for each label.
+ print('Label with ID "%d" and name "%s" was found.\n' % (label['id'],
+ label['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/label_service/get_all_labels.py b/examples/ad_manager/v202202/label_service/get_all_labels.py
new file mode 100755
index 00000000..35e7d91f
--- /dev/null
+++ b/examples/ad_manager/v202202/label_service/get_all_labels.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all labels.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ label_service = client.GetService('LabelService', version='v202202')
+
+ # Create a statement to select labels.
+ statement = ad_manager.StatementBuilder(version='v202202')
+
+ # Retrieve a small amount of labels at a time, paging
+ # through until all labels have been retrieved.
+ while True:
+ response = label_service.getLabelsByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for label in response['results']:
+ # Print out some information for each label.
+ print('Label with ID "%d" and name "%s" was found.\n' % (label['id'],
+ label['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/label_service/update_labels.py b/examples/ad_manager/v202202/label_service/update_labels.py
new file mode 100755
index 00000000..48d6d131
--- /dev/null
+++ b/examples/ad_manager/v202202/label_service/update_labels.py
@@ -0,0 +1,63 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates the description of a single label.
+
+To determine which labels exist, run get_all_labels.py. This feature is only
+available to Ad Manager 360 solution networks.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+LABEL_ID = 'INSERT_LABEL_ID_HERE'
+
+
+def main(client, label_id):
+ # Initialize appropriate service.
+ label_service = client.GetService('LabelService', version='v202202')
+
+ # Create a statement to select only active labels.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('id = :labelId')
+ .WithBindVariable('labelId', int(label_id)))
+
+ # Get labels by filter.
+ response = label_service.getLabelsByStatement(statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ # Update each local label object by changing the description.
+ updated_labels = []
+ for label in response['results']:
+ label['description'] = 'These labels are updated.'
+ updated_labels.append(label)
+
+ # Update labels remotely.
+ labels = label_service.updateLabels(updated_labels)
+
+ for label in labels:
+ print('Label with id "%s" and name "%s" was updated.'
+ % (label['id'], label['name']))
+ else:
+ print('No labels found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, LABEL_ID)
+
diff --git a/examples/ad_manager/v202202/line_item_creative_association_service/__init__.py b/examples/ad_manager/v202202/line_item_creative_association_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202202/line_item_creative_association_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202202/line_item_creative_association_service/create_licas.py b/examples/ad_manager/v202202/line_item_creative_association_service/create_licas.py
new file mode 100755
index 00000000..d419720f
--- /dev/null
+++ b/examples/ad_manager/v202202/line_item_creative_association_service/create_licas.py
@@ -0,0 +1,57 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new line item creative associations (LICAs) for an
+existing line item and a set of creative ids.
+
+To determine which LICAs exist, run get_all_licas.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the line item ID and creative IDs to associate.
+LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
+CREATIVE_IDS = ['INSERT_CREATIVE_IDS_HERE']
+
+
+def main(client, line_item_id, creative_ids):
+ # Initialize appropriate service.
+ lica_service = client.GetService(
+ 'LineItemCreativeAssociationService', version='v202202')
+
+ licas = []
+ for creative_id in creative_ids:
+ licas.append({'creativeId': creative_id,
+ 'lineItemId': line_item_id})
+
+ # Create the LICAs remotely.
+ licas = lica_service.createLineItemCreativeAssociations(licas)
+
+ # Display results.
+ if licas:
+ for lica in licas:
+ print('LICA with line item id "%s", creative id "%s", and '
+ 'status "%s" was created.' %
+ (lica['lineItemId'], lica['creativeId'], lica['status']))
+ else:
+ print('No LICAs created.')
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, LINE_ITEM_ID, CREATIVE_IDS)
diff --git a/examples/ad_manager/v202202/line_item_creative_association_service/deactivate_licas.py b/examples/ad_manager/v202202/line_item_creative_association_service/deactivate_licas.py
new file mode 100755
index 00000000..e46dab72
--- /dev/null
+++ b/examples/ad_manager/v202202/line_item_creative_association_service/deactivate_licas.py
@@ -0,0 +1,73 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example deactivates all LICAs for the line item.
+
+To determine which LICAs exist, run get_all_licas.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the id of the line item in which to deactivate LICAs.
+LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
+
+
+def main(client, line_item_id):
+ # Initialize appropriate service.
+ lica_service = client.GetService(
+ 'LineItemCreativeAssociationService', version='v202202')
+
+ # Create query.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('lineItemId = :lineItemId AND status = :status')
+ .WithBindVariable('status', 'ACTIVE')
+ .WithBindVariable('lineItemId', int(line_item_id)))
+
+ num_deactivated_licas = 0
+
+ # Get LICAs by statement.
+ while True:
+ response = lica_service.getLineItemCreativeAssociationsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for lica in response['results']:
+ print('LICA with line item id "%s", creative id "%s", and status'
+ ' "%s" will be deactivated.' %
+ (lica['lineItemId'], lica['creativeId'], lica['status']))
+
+ # Perform action.
+ result = lica_service.performLineItemCreativeAssociationAction(
+ {'xsi_type': 'DeactivateLineItemCreativeAssociations'},
+ statement.ToStatement())
+ if result and int(result['numChanges']) > 0:
+ num_deactivated_licas += int(result['numChanges'])
+ statement.offset += statement.limit
+ else:
+ break
+
+ # Display results.
+ if num_deactivated_licas > 0:
+ print('Number of LICAs deactivated: %s' % num_deactivated_licas)
+ else:
+ print('No LICAs were deactivated.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, LINE_ITEM_ID)
diff --git a/examples/ad_manager/v202202/line_item_creative_association_service/get_all_licas.py b/examples/ad_manager/v202202/line_item_creative_association_service/get_all_licas.py
new file mode 100755
index 00000000..b4ef82a5
--- /dev/null
+++ b/examples/ad_manager/v202202/line_item_creative_association_service/get_all_licas.py
@@ -0,0 +1,57 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all line item creative associations.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ lica_service = client.GetService(
+ 'LineItemCreativeAssociationService', version='v202202')
+
+ # Create a statement to select line item creative associations.
+ statement = ad_manager.StatementBuilder(version='v202202')
+
+ # Retrieve a small amount of line item creative associations at a time, paging
+ # through until all line item creative associations have been retrieved.
+ while True:
+ response = lica_service.getLineItemCreativeAssociationsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for lica in response['results']:
+ # Print out some information for each line item creative association.
+ if 'creativeSetId' in lica:
+ print('LICA with line item ID "%s", creative set ID "%s", and '
+ 'status "%s" was found.' %
+ (lica['lineItemId'], lica['creativeSetId'], lica['status']))
+ else:
+ print('Line item creative association with line item ID "%d" and '
+ 'creative ID "%d" was found.\n' %
+ (lica['lineItemId'], lica['creativeId']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/line_item_creative_association_service/get_licas_for_line_item.py b/examples/ad_manager/v202202/line_item_creative_association_service/get_licas_for_line_item.py
new file mode 100755
index 00000000..3f1d46f2
--- /dev/null
+++ b/examples/ad_manager/v202202/line_item_creative_association_service/get_licas_for_line_item.py
@@ -0,0 +1,60 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all line item creative associations for a given line item.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
+
+
+def main(client, line_item_id):
+ # Initialize appropriate service.
+ lica_service = client.GetService(
+ 'LineItemCreativeAssociationService', version='v202202')
+ # Create a statement to select line item creative associations.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('lineItemId = :lineItemId')
+ .WithBindVariable('lineItemId', line_item_id))
+
+ # Retrieve a small amount of line item creative associations at a time, paging
+ # through until all line item creative associations have been retrieved.
+ while True:
+ response = lica_service.getLineItemCreativeAssociationsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for lica in response['results']:
+ # Print out some information for each line item creative association.
+ if 'creativeSetId' in lica:
+ print('LICA with line item ID "%s", creative set ID "%s", and '
+ 'status "%s" was found.' %
+ (lica['lineItemId'], lica['creativeSetId'], lica['status']))
+ else:
+ print('Line item creative association with line item ID "%d" and '
+ 'creative ID "%d" was found.\n' %
+ (lica['lineItemId'], lica['creativeId']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, LINE_ITEM_ID)
diff --git a/examples/ad_manager/v202202/line_item_creative_association_service/push_creative_to_devices.py b/examples/ad_manager/v202202/line_item_creative_association_service/push_creative_to_devices.py
new file mode 100755
index 00000000..90de873e
--- /dev/null
+++ b/examples/ad_manager/v202202/line_item_creative_association_service/push_creative_to_devices.py
@@ -0,0 +1,61 @@
+#!/usr/bin/env python
+#
+# Copyright 2021, Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example pushes a LICA to a linked device for preview.
+
+To determine which linked devices exist, use the PublisherQueryLanguageService
+linked_device table.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the associated line item id and creative id to push, and set the linked
+# device id where it will be pushed.
+LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
+CREATIVE_ID = 'INSERT_CREATIVE_ID_HERE'
+LINKED_DEVICE_ID = 'INSERT_LINKED_DEVICE_ID_HERE'
+
+
+def main(client, line_item_id, creative_id, linked_device_id):
+ # Initialize appropriate service.
+ lica_service = client.GetService(
+ 'LineItemCreativeAssociationService', version='v202202')
+
+ # Create query to select a single linked device.
+ # Linked devices can be read from the linked_device PQL table.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('id = :linkedDeviceId')
+ .WithBindVariable('linkedDeviceId', int(linked_device_id)))
+
+ # Make call to push creatives to devices.
+ result = lica_service.pushCreativeToDevices(statement.ToStatement(), {
+ 'lineItemId': line_item_id,
+ 'creativeId': creative_id
+ })
+
+ # Display results.
+ if result and int(result['numChanges']) > 0:
+ print('Pushed creatives to %s devices.' % result['numChanges'])
+ else:
+ print('No creatives were pushed.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, LINE_ITEM_ID, CREATIVE_ID, LINKED_DEVICE_ID)
diff --git a/examples/ad_manager/v202202/line_item_creative_association_service/update_licas.py b/examples/ad_manager/v202202/line_item_creative_association_service/update_licas.py
new file mode 100755
index 00000000..c8f5eca1
--- /dev/null
+++ b/examples/ad_manager/v202202/line_item_creative_association_service/update_licas.py
@@ -0,0 +1,66 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates the destination URL of all line item creative
+associations (LICA).
+
+To determine which LICAs exist, run get_all_licas.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ lica_service = client.GetService(
+ 'LineItemCreativeAssociationService', version='v202202')
+
+ # Create statement object to get all LICAs.
+ statement = ad_manager.StatementBuilder(version='v202202')
+
+ while True:
+ # Get LICAs by statement.
+ response = lica_service.getLineItemCreativeAssociationsByStatement(
+ statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ # Update each local LICA object by changing its destination URL.
+ updated_licas = []
+ for lica in response['results']:
+ lica['destinationUrl'] = 'http://news.google.com'
+ updated_licas.append(lica)
+
+ # Update LICAs remotely.
+ licas = lica_service.updateLineItemCreativeAssociations(updated_licas)
+
+ # Display results.
+ for lica in licas:
+ print('LICA with line item id "%s", creative id "%s", and status '
+ '"%s" was updated.' % (lica['lineItemId'], lica['creativeId'],
+ lica['status']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ if response['totalResultSetSize'] == 0:
+ print('No LICAs found to update.')
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/line_item_service/__init__.py b/examples/ad_manager/v202202/line_item_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202202/line_item_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202202/line_item_service/activate_line_items.py b/examples/ad_manager/v202202/line_item_service/activate_line_items.py
new file mode 100755
index 00000000..a38c3919
--- /dev/null
+++ b/examples/ad_manager/v202202/line_item_service/activate_line_items.py
@@ -0,0 +1,75 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example activates all line items for the given order.
+
+To be activated, line items need to be in the approved state and have at least
+one creative associated with them. To approve line items, approve the order to
+which they belong by running approve_orders.py. To create LICAs, run
+create_licas.py. To determine which line items exist, run
+get_all_line_items.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the id of the order to get line items from.
+ORDER_ID = 'INSERT_ORDER_ID_HERE'
+
+
+def main(client, order_id):
+ # Initialize appropriate service.
+ line_item_service = client.GetService('LineItemService', version='v202202')
+
+ # Create query.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('orderId = :orderId AND status = :status')
+ .WithBindVariable('status', 'NEEDS_CREATIVES')
+ .WithBindVariable('orderId', int(order_id)))
+
+ line_items_activated = 0
+
+ # Get line items by statement.
+ while True:
+ response = line_item_service.getLineItemsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for line_item in response['results']:
+ print('Line item with id "%s", belonging to order id "%s", and '
+ 'name "%s" will be activated.' %
+ (line_item['id'], line_item['orderId'], line_item['name']))
+
+ # Perform action.
+ result = line_item_service.performLineItemAction(
+ {'xsi_type': 'ActivateLineItems'}, statement.ToStatement())
+ if result and int(result['numChanges']) > 0:
+ line_items_activated += int(result['numChanges'])
+ statement.offset += statement.limit
+ else:
+ break
+
+ # Display results.
+ if line_items_activated > 0:
+ print('Number of line items activated: %s' % line_items_activated)
+ else:
+ print('No line items were activated.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ORDER_ID)
diff --git a/examples/ad_manager/v202202/line_item_service/create_line_items.py b/examples/ad_manager/v202202/line_item_service/create_line_items.py
new file mode 100755
index 00000000..00a4a7e7
--- /dev/null
+++ b/examples/ad_manager/v202202/line_item_service/create_line_items.py
@@ -0,0 +1,165 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new line items.
+
+To determine which line items exist, run get_all_line_items.py. To determine
+which orders exist, run get_all_orders.py. To determine which placements exist,
+run get_all_placements.py.
+"""
+
+
+import datetime
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+import pytz
+
+# Set order that the created line item will belong to and add the id of a
+# placement containing ad units to target.
+ORDER_ID = 'INSERT_ORDER_ID_HERE'
+TARGETED_PLACEMENT_IDS = ['INSERT_PLACEMENT_IDS_HERE']
+
+
+def main(client, order_id, targeted_placement_ids):
+ # Initialize appropriate service.
+ line_item_service = client.GetService('LineItemService', version='v202202')
+
+ end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York'))
+ end_datetime += datetime.timedelta(days=365)
+
+ # Create line item objects.
+ line_items = []
+ for _ in range(5):
+ line_item = {
+ 'name': 'Line item #%s' % uuid.uuid4(),
+ 'orderId': order_id,
+ 'targeting': {
+ 'inventoryTargeting': {
+ 'targetedPlacementIds': targeted_placement_ids
+ },
+ 'geoTargeting': {
+ 'targetedLocations': [
+ {
+ 'id': '2840',
+ 'displayName': 'US'
+ },
+ {
+ 'id': '20133',
+ 'displayName': 'Geneva'
+ },
+ {
+ 'id': '9000093',
+ 'displayName': 'B3P',
+ }
+ ],
+ 'excludedLocations': [
+ {
+ 'id': '1016367',
+ 'displayName': 'Chicago',
+ },
+ {
+ 'id': '200501',
+ 'displayName': 'New York NY'
+ }
+ ]
+ },
+ 'dayPartTargeting': {
+ 'dayParts': [
+ {
+ 'dayOfWeek': 'SATURDAY',
+ 'startTime': {
+ 'hour': '0',
+ 'minute': 'ZERO'
+ },
+ 'endTime': {
+ 'hour': '24',
+ 'minute': 'ZERO'
+ }
+ },
+ {
+ 'dayOfWeek': 'SUNDAY',
+ 'startTime': {
+ 'hour': '0',
+ 'minute': 'ZERO'
+ },
+ 'endTime': {
+ 'hour': '24',
+ 'minute': 'ZERO'
+ }
+ }
+ ],
+ 'timeZone': 'BROWSER'
+ },
+ 'userDomainTargeting': {
+ 'domains': ['usa.gov'],
+ 'targeted': 'false'
+ },
+ 'technologyTargeting': {
+ 'browserTargeting': {
+ 'browsers': [{'id': '500072'}],
+ 'isTargeted': 'true'
+ }
+ }
+ },
+ 'creativePlaceholders': [
+ {
+ 'size': {
+ 'width': '300',
+ 'height': '250'
+ }
+ },
+ {
+ 'size': {
+ 'width': '120',
+ 'height': '600'
+ }
+ }
+ ],
+ 'startDateTimeType': 'IMMEDIATELY',
+ 'lineItemType': 'STANDARD',
+ 'endDateTime': end_datetime,
+ 'costType': 'CPM',
+ 'costPerUnit': {
+ 'currencyCode': 'USD',
+ 'microAmount': '2000000'
+ },
+ 'primaryGoal': {
+ 'units': '50',
+ 'unitType': 'IMPRESSIONS',
+ 'goalType': 'LIFETIME'
+ },
+ 'contractedUnitsBought': '100',
+ 'creativeRotationType': 'EVEN',
+ 'discountType': 'PERCENTAGE',
+ 'allowOverbook': 'true'
+ }
+ line_items.append(line_item)
+
+ # Add line items.
+ line_items = line_item_service.createLineItems(line_items)
+
+ # Display results.
+ for line_item in line_items:
+ print('Line item with id "%s", belonging to order id "%s", and named '
+ '"%s" was created.' % (line_item['id'], line_item['orderId'],
+ line_item['name']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ORDER_ID, TARGETED_PLACEMENT_IDS)
diff --git a/examples/ad_manager/v202202/line_item_service/create_video_line_item.py b/examples/ad_manager/v202202/line_item_service/create_video_line_item.py
new file mode 100755
index 00000000..f94574d1
--- /dev/null
+++ b/examples/ad_manager/v202202/line_item_service/create_video_line_item.py
@@ -0,0 +1,135 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates a new line item to serve to video content.
+
+This feature is only available to Ad Manager 360 solution networks.
+"""
+
+import datetime
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+import pytz
+
+# Set order that all created line item will belong to and the video ad unit id
+# to target.
+ORDER_ID = 'INSERT_ORDER_ID_HERE'
+TARGETED_VIDEO_AD_UNIT_ID = 'INSERT_TARGETED_VIDEO_AD_UNIT_ID_HERE'
+
+# Set the video content to target.
+CONTENT_ID = 'INSERT_CONTENT_ID_HERE'
+# Set the video content bundle to target.
+CONTENT_BUNDLE_ID = 'INSERT_CONTENT_BUNDLE_ID_HERE'
+# Set the CMS metadata value to target.
+CMS_METADATA_VALUE_ID = 'INSERT_CMS_METADATA_VALUE_ID_HERE'
+
+
+def main(client, order_id, targeted_video_ad_unit_id, content_id,
+ content_bundle_id, cms_metadata_value_id):
+ # Initialize appropriate service.
+ line_item_service = client.GetService('LineItemService', version='v202202')
+
+ end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York'))
+ end_datetime += datetime.timedelta(days=365)
+
+ # Create line item object.
+ line_item = {
+ 'name': 'Line item #%s' % uuid.uuid4(),
+ 'orderId': order_id,
+ 'targeting': {
+ 'contentTargeting': {
+ 'targetedContentIds': [content_id],
+ 'targetedVideoContentBundleIds': [content_bundle_id]
+ },
+ 'customTargeting': {
+ 'logicalOperator': 'AND',
+ 'children': [{
+ 'xsi_type': 'CmsMetadataCriteria',
+ 'cmsMetadataValueIds': [cms_metadata_value_id],
+ 'operator': 'EQUALS'
+ }]
+ },
+ 'inventoryTargeting': {
+ 'targetedAdUnits': [{
+ 'adUnitId': targeted_video_ad_unit_id,
+ 'includeDescendants': 'true'
+ }]
+ },
+ 'requestPlatformTargeting': {
+ 'targetedRequestPlatforms': ['VIDEO_PLAYER']
+ },
+ 'videoPositionTargeting': {
+ 'targetedPositions': [{
+ 'videoPosition': {
+ 'positionType': 'PREROLL'
+ }
+ }]
+ }
+ },
+ 'creativePlaceholders': [{
+ 'size': {
+ 'width': '400',
+ 'height': '300'
+ },
+ 'companions': [{
+ 'size': {
+ 'width': '300',
+ 'height': '250'
+ },
+ }, {
+ 'size': {
+ 'width': '728',
+ 'height': '90'
+ },
+ }]
+ }],
+ 'environmentType': 'VIDEO_PLAYER',
+ 'companionDeliveryOption': 'OPTIONAL',
+ 'videoMaxDuration': 15000,
+ 'startDateTimeType': 'IMMEDIATELY',
+ 'lineItemType': 'SPONSORSHIP',
+ 'endDateTime': end_datetime,
+ 'costType': 'CPM',
+ 'costPerUnit': {
+ 'currencyCode': 'USD',
+ 'microAmount': '2000000'
+ },
+ 'primaryGoal': {
+ 'units': '50',
+ 'unitType': 'IMPRESSIONS',
+ 'goalType': 'DAILY'
+ },
+ 'contractedUnitsBought': '100',
+ 'creativeRotationType': 'OPTIMIZED',
+ 'discountType': 'PERCENTAGE',
+ 'allowOverbook': 'true'
+ }
+
+ # Add line item.
+ line_item = line_item_service.createLineItems([line_item])[0]
+
+ # Display results.
+ print('Video line item with id "%s", belonging to order id "%s", and '
+ 'named "%s" was created.' % (line_item['id'], line_item['orderId'],
+ line_item['name']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ORDER_ID, TARGETED_VIDEO_AD_UNIT_ID, CONTENT_ID,
+ CONTENT_BUNDLE_ID, CMS_METADATA_VALUE_ID)
diff --git a/examples/ad_manager/v202202/line_item_service/get_all_line_items.py b/examples/ad_manager/v202202/line_item_service/get_all_line_items.py
new file mode 100755
index 00000000..62042eae
--- /dev/null
+++ b/examples/ad_manager/v202202/line_item_service/get_all_line_items.py
@@ -0,0 +1,50 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all line items.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ line_item_service = client.GetService('LineItemService', version='v202202')
+
+ # Create a statement to select line items.
+ statement = ad_manager.StatementBuilder(version='v202202')
+
+ # Retrieve a small amount of line items at a time, paging
+ # through until all line items have been retrieved.
+ while True:
+ response = line_item_service.getLineItemsByStatement(statement.ToStatement(
+ ))
+ if 'results' in response and len(response['results']):
+ for line_item in response['results']:
+ # Print out some information for each line item.
+ print('Line item with ID "%d" and name "%s" was found.\n' %
+ (line_item['id'], line_item['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/line_item_service/get_line_items_that_need_creatives.py b/examples/ad_manager/v202202/line_item_service/get_line_items_that_need_creatives.py
new file mode 100755
index 00000000..487b8464
--- /dev/null
+++ b/examples/ad_manager/v202202/line_item_service/get_line_items_that_need_creatives.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all line items that are missing creatives.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ line_item_service = client.GetService('LineItemService', version='v202202')
+ # Create a statement to select line items.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('isMissingCreatives = :isMissingCreatives')
+ .WithBindVariable('isMissingCreatives', True))
+
+ # Retrieve a small amount of line items at a time, paging
+ # through until all line items have been retrieved.
+ while True:
+ response = line_item_service.getLineItemsByStatement(statement.ToStatement(
+ ))
+ if 'results' in response and len(response['results']):
+ for line_item in response['results']:
+ # Print out some information for each line item.
+ print('Line item with ID "%d" and name "%s" was found.\n' %
+ (line_item['id'], line_item['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/line_item_service/get_recently_updated_line_items.py b/examples/ad_manager/v202202/line_item_service/get_recently_updated_line_items.py
new file mode 100755
index 00000000..1e6fddd8
--- /dev/null
+++ b/examples/ad_manager/v202202/line_item_service/get_recently_updated_line_items.py
@@ -0,0 +1,59 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets only recently updated line items.
+"""
+
+# Import appropriate modules from the client library.
+from datetime import datetime
+from datetime import timedelta
+
+from googleads import ad_manager
+import pytz
+
+
+def main(client):
+ # Initialize appropriate service.
+ line_item_service = client.GetService('LineItemService', version='v202202')
+
+ last_modified = (datetime.now(tz=pytz.timezone('America/New_York'))
+ - timedelta(days=1))
+
+ # Create a statement to select line items.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('lastModifiedDateTime >= :lastModifiedDateTime')
+ .WithBindVariable('lastModifiedDateTime', last_modified))
+
+ # Retrieve a small amount of line items at a time, paging
+ # through until all line items have been retrieved.
+ while True:
+ response = line_item_service.getLineItemsByStatement(statement.ToStatement(
+ ))
+ if 'results' in response and len(response['results']):
+ for line_item in response['results']:
+ # Print out some information for each line item.
+ print('Line item with ID "%d" and name "%s" was found.\n' %
+ (line_item['id'], line_item['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/line_item_service/pause_line_items.py b/examples/ad_manager/v202202/line_item_service/pause_line_items.py
new file mode 100755
index 00000000..d9e48906
--- /dev/null
+++ b/examples/ad_manager/v202202/line_item_service/pause_line_items.py
@@ -0,0 +1,74 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example pauses a line item.
+
+Line items must be paused before they can be updated. To determine which line
+items exist, run get_all_line_items.py
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the line item to pause.
+LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
+
+
+def main(client):
+ # Initialize appropriate service.
+ line_item_service = client.GetService('LineItemService', version='v202202')
+
+ # Create a statement to select the line item.
+ # Change this to operate on more than one Line Item.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('id = :id')
+ .OrderBy('id', ascending=True)
+ .WithBindVariable('id', LINE_ITEM_ID))
+
+ result_set_size = 0
+ should_continue = True
+
+ # Iterate over paged results from the statement.
+ while should_continue:
+ page = line_item_service.getLineItemsByStatement(statement.ToStatement())
+ if 'results' in page and len(page['results']):
+ result_set_size = page['totalResultSetSize']
+ # Iterate over individual results in the page.
+ for line_item in page['results']:
+ print('Pausing line item with ID %d' % line_item['id'])
+ # Update statement for next page.
+ statement.offset += statement.limit
+ should_continue = statement.offset < result_set_size
+
+ print('Pausing %d line item(s)' % result_set_size)
+
+ if result_set_size > 0:
+ statement.offset = None
+ statement.limit = None
+
+ # Perform Pause action on all Line Items that match the statement.
+ update_result = line_item_service.performLineItemAction(
+ {'xsi_type': 'PauseLineItems'}, statement.ToStatement())
+
+ if update_result and update_result['numChanges'] > 0:
+ print('Updated %d line item(s)' % update_result['numChanges'])
+ else:
+ print('No line items were paused')
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/line_item_service/target_custom_criteria.py b/examples/ad_manager/v202202/line_item_service/target_custom_criteria.py
new file mode 100755
index 00000000..709f33e9
--- /dev/null
+++ b/examples/ad_manager/v202202/line_item_service/target_custom_criteria.py
@@ -0,0 +1,110 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example updates a line item to add custom criteria targeting.
+
+To determine which line items exist, run get_all_line_items.py. To determine
+which custom targeting keys and values exist, run
+get_all_custom_targeting_keys_and_values.py.
+"""
+
+
+import pprint
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
+KEY_ID1 = 'INSERT_TARGETING_KEY_ID_HERE'
+KEY_ID2 = 'INSERT_TARGETING_KEY_ID_HERE'
+KEY_ID3 = 'INSERT_TARGETING_KEY_ID_HERE'
+
+VALUE_ID1 = 'INSERT_TARGETING_VALUE_ID_HERE'
+VALUE_ID2 = 'INSERT_TARGETING_VALUE_ID_HERE'
+VALUE_ID3 = 'INSERT_TARGETING_VALUE_ID_HERE'
+
+
+def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2,
+ value_id3):
+ # Initialize appropriate service.
+ line_item_service = client.GetService('LineItemService', version='v202202')
+
+ # create custom criterias
+ custom_criteria1 = {
+ 'xsi_type': 'CustomCriteria',
+ 'keyId': key_id1,
+ 'valueIds': [value_id1],
+ 'operator': 'IS'
+ }
+
+ custom_criteria2 = {
+ 'xsi_type': 'CustomCriteria',
+ 'keyId': key_id2,
+ 'valueIds': [value_id2],
+ 'operator': 'IS_NOT'
+ }
+
+ custom_criteria3 = {
+ 'xsi_type': 'CustomCriteria',
+ 'keyId': key_id3,
+ 'valueIds': [value_id3],
+ 'operator': 'IS'
+ }
+
+ # Create the custom criteria set that will resemble:
+ # (custom_criteria1.key == custom_criteria1.value OR
+ # (custom_criteria2.key != custom_criteria2.value AND
+ # custom_criteria13.key == custom_criteria3.value))
+ sub_set = {
+ 'xsi_type': 'CustomCriteriaSet',
+ 'logicalOperator': 'AND',
+ 'children': [custom_criteria2, custom_criteria3]
+ }
+
+ top_set = {
+ 'xsi_type': 'CustomCriteriaSet',
+ 'logicalOperator': 'OR',
+ 'children': [custom_criteria1, sub_set]
+ }
+
+ # Create statement to get the line item
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('id = :lineItemId')
+ .WithBindVariable('lineItemId', int(line_item_id))
+ .Limit(1))
+
+ # Set custom criteria targeting on the line item.
+ line_item = line_item_service.getLineItemsByStatement(
+ statement.ToStatement())['results'][0]
+ line_item['targeting']['customTargeting'] = top_set
+
+ # Update line item.
+ line_item = line_item_service.updateLineItems([line_item])[0]
+
+ # Display results.
+ if line_item:
+ print('Line item with id "%s" updated with custom criteria targeting:'
+ % line_item['id'])
+ pprint.pprint(line_item['targeting']['customTargeting'])
+ else:
+ print('No line items were updated.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, LINE_ITEM_ID, KEY_ID1, KEY_ID2, KEY_ID3, VALUE_ID1,
+ VALUE_ID2, VALUE_ID3)
diff --git a/examples/ad_manager/v202202/line_item_service/update_line_items.py b/examples/ad_manager/v202202/line_item_service/update_line_items.py
new file mode 100755
index 00000000..8171ab11
--- /dev/null
+++ b/examples/ad_manager/v202202/line_item_service/update_line_items.py
@@ -0,0 +1,74 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates the delivery rate of all line items in an order.
+
+To determine which line items exist, run get_all_line_items.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set id of the order to get line items from.
+ORDER_ID = 'INSERT_ORDER_ID_HERE'
+
+
+def main(client, order_id):
+ # Initialize appropriate service.
+ line_item_service = client.GetService('LineItemService', version='v202202')
+
+ # Create statement object to only select line items with even delivery rates.
+
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where(('deliveryRateType = :deliveryRateType AND '
+ 'orderId = :orderId'))
+ .WithBindVariable('orderId', int(order_id))
+ .WithBindVariable('deliveryRateType', 'EVENLY')
+ .Limit(500))
+
+ # Get line items by statement.
+ response = line_item_service.getLineItemsByStatement(
+ statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ # Update each local line item by changing its delivery rate type.
+ updated_line_items = []
+ for line_item in response['results']:
+ if not line_item['isArchived']:
+ line_item['deliveryRateType'] = 'AS_FAST_AS_POSSIBLE'
+ updated_line_items.append(line_item)
+
+ # Update line items remotely.
+ line_items = line_item_service.updateLineItems(updated_line_items)
+
+ # Display results.
+ if line_items:
+ for line_item in line_items:
+ print('Line item with id "%s", belonging to order id "%s", named '
+ '"%s", and delivery rate "%s" was updated.'
+ % (line_item['id'], line_item['orderId'], line_item['name'],
+ line_item['deliveryRateType']))
+ else:
+ print('No line items were updated.')
+ else:
+ print('No line items found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ORDER_ID)
diff --git a/examples/ad_manager/v202202/live_stream_event_service/activate_live_stream_events.py b/examples/ad_manager/v202202/live_stream_event_service/activate_live_stream_events.py
new file mode 100755
index 00000000..b2ac8301
--- /dev/null
+++ b/examples/ad_manager/v202202/live_stream_event_service/activate_live_stream_events.py
@@ -0,0 +1,71 @@
+#!/usr/bin/env python
+#
+# Copyright 2018 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example activates paused live stream events."""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the id of the LiveStreamEvent to get live stream events from.
+LIVE_STREAM_EVENT_ID = 'INSERT_LIVE_STREAM_EVENT_ID_HERE'
+
+
+def main(client, live_stream_event_id):
+ # Initialize appropriate service.
+ live_stream_event_service = client.GetService(
+ 'LiveStreamEventService', version='v202202')
+
+ # Create query to find paused live stream events.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where(('id = :id AND '
+ 'status = :status'))
+ .WithBindVariable('status', 'PAUSED')
+ .WithBindVariable('id', int(live_stream_event_id))
+ .Limit(500))
+
+ live_stream_events_activated = 0
+
+ # Get live stream events by statement.
+ while True:
+ response = live_stream_event_service.getLiveStreamEventsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for live_stream_event in response['results']:
+ print('live stream event with id "%s" and name "%s" will be activated.'
+ % (live_stream_event['id'], live_stream_event['name']))
+
+ # Perform action.
+ result = live_stream_event_service.performLiveStreamEventAction({
+ 'xsi_type': 'ActivateLiveStreamEvents'
+ }, statement.ToStatement())
+ if result and int(result['numChanges']) > 0:
+ live_stream_events_activated += int(result['numChanges'])
+ statement.offset += ad_manager.SUGGESTED_PAGE_LIMIT
+ else:
+ break
+
+ # Display results.
+ if live_stream_events_activated > 0:
+ print('# of live stream events activated: %s' % (
+ live_stream_events_activated))
+ else:
+ print('No live stream events were activated.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, LIVE_STREAM_EVENT_ID)
diff --git a/examples/ad_manager/v202202/live_stream_event_service/create_live_stream_events.py b/examples/ad_manager/v202202/live_stream_event_service/create_live_stream_events.py
new file mode 100755
index 00000000..02109ec1
--- /dev/null
+++ b/examples/ad_manager/v202202/live_stream_event_service/create_live_stream_events.py
@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+#
+# Copyright 2018 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new live stream events.
+
+To determine which live stream events exist, run get_all_live_stream_events.py.
+To determine which cdn configurations exist, run get_cdn_configurations.py.
+"""
+
+import datetime
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+import pytz
+
+# Set content urls and adTags to use
+CONTENT_URLS = ['INSERT_CONTENT_URLS_HERE']
+AD_TAGS = ['INSERT_AD_TAGS_HERE']
+
+
+def main(client, content_urls, ad_tags):
+ # Initialize appropriate services.
+ live_events_service = client.GetService(
+ 'LiveStreamEventService', version='v202202')
+
+ # Stream will play for 365 days
+ start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York'))
+ end_datetime = start_datetime + datetime.timedelta(days=365)
+
+ # Create live stream event objects
+ live_stream_events = [{
+ 'name': 'Live Stream Event #%s' % uuid.uuid4(),
+ 'startDateTime': start_datetime,
+ 'endDateTime': end_datetime,
+ 'contentUrls': content_urls,
+ 'adTags': ad_tags
+ }]
+
+ # Add live stream events.
+ live_stream_events = live_events_service.createLiveStreamEvents(
+ live_stream_events)
+
+ # Display results.
+ for live_stream_event in live_stream_events:
+ print(
+ 'Live stream event with id "%s", named "%s" and status %s was created.'
+ % (live_stream_event['id'], live_stream_event['name'],
+ live_stream_event['status']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CONTENT_URLS, AD_TAGS)
diff --git a/examples/ad_manager/v202202/live_stream_event_service/get_all_live_stream_events.py b/examples/ad_manager/v202202/live_stream_event_service/get_all_live_stream_events.py
new file mode 100755
index 00000000..72a94a9c
--- /dev/null
+++ b/examples/ad_manager/v202202/live_stream_event_service/get_all_live_stream_events.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2018 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all live stream events.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ live_stream_event_service = client.GetService(
+ 'LiveStreamEventService', version='v202202')
+
+ # Create a statement to select live stream events.
+ statement = ad_manager.StatementBuilder(version='v202202')
+
+ # Retrieve a small amount of live stream events at a time, paging
+ # through until all live stream events have been retrieved.
+ while True:
+ response = live_stream_event_service.getLiveStreamEventsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for live_stream_event in response['results']:
+ # Print out some information for each live stream event.
+ print('live stream event with id "%d" and name "%s" was found.' %
+ (live_stream_event['id'], live_stream_event['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/live_stream_event_service/register_sessions_for_monitoring.py b/examples/ad_manager/v202202/live_stream_event_service/register_sessions_for_monitoring.py
new file mode 100755
index 00000000..c201177d
--- /dev/null
+++ b/examples/ad_manager/v202202/live_stream_event_service/register_sessions_for_monitoring.py
@@ -0,0 +1,45 @@
+#!/usr/bin/env python
+#
+# Copyright 2018 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example registers all live stream event-sessions ids for monitoring."""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# List of session ids
+SESSION_IDS = ['INSERT_SESSION_IDS_HERE']
+
+
+def main(client, session_ids):
+ # Initialize appropriate service.
+ live_stream_event_service = client.GetService(
+ 'LiveStreamEventService', version='v202202')
+
+ # Retrieve all sessions id that are being monitored
+ session_ids = live_stream_event_service.registerSessionsForMonitoring(
+ session_ids)
+ if session_ids:
+ for session_id in session_ids:
+ # Print out some information for each live stream event.
+ print('Session with ID "%s" registered for monitoring.' % (session_id))
+
+ print('\nNumber of results found: %s' % session_ids.size)
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, SESSION_IDS)
diff --git a/examples/ad_manager/v202202/live_stream_event_service/update_live_stream_events.py b/examples/ad_manager/v202202/live_stream_event_service/update_live_stream_events.py
new file mode 100755
index 00000000..40aef5c2
--- /dev/null
+++ b/examples/ad_manager/v202202/live_stream_event_service/update_live_stream_events.py
@@ -0,0 +1,69 @@
+#!/usr/bin/env python
+#
+# Copyright 2018 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates live stream events.
+
+To determine which live stream events exist, run get_all_live_stream_events.py.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set ID of the LiveStreamEvent to get live stream events from.
+LIVE_STREAM_EVENT_ID = 'INSERT_LIVE_STREAM_EVENT_ID_HERE'
+
+
+def main(client, live_stream_event_id):
+ # Initialize appropriate services.
+ live_stream_events_service = client.GetService(
+ 'LiveStreamEventService', version='v202202')
+
+ # Create statement object to only select matching live stream event.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where(('Id = :id'))
+ .WithBindVariable('id', int(live_stream_event_id))
+ .Limit(500))
+
+ # Get live stream events by statement.
+ response = live_stream_events_service.getLiveStreamEventsByStatement(
+ statement.ToStatement())
+
+ # Set adTags to be updated.
+ new_ad_tags = ['INSERT_NEW_AD_TAGS_HERE']
+
+ if 'results' in response and len(response['results']):
+ # Update each local live stream event by changing its attributes.
+ updated_live_stream_events = []
+ for live_stream_event in response['results']:
+ live_stream_event['startDateTimeType'] = 'IMMEDIATELY'
+ live_stream_event['adTags'] = new_ad_tags
+ updated_live_stream_events.append(live_stream_event)
+
+ # Update live stream events.
+ live_stream_events = live_stream_events_service.updateLiveStreamEvents(
+ updated_live_stream_events)
+
+ # Display results.
+ for live_stream_event in live_stream_events:
+ print('Live stream event with id "%s", named "%s" and status %s was '
+ 'updated.' % (live_stream_event['id'], live_stream_event['name'],
+ live_stream_event['status']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, LIVE_STREAM_EVENT_ID)
diff --git a/examples/ad_manager/v202202/native_style_service/__init__.py b/examples/ad_manager/v202202/native_style_service/__init__.py
new file mode 100755
index 00000000..473ddba1
--- /dev/null
+++ b/examples/ad_manager/v202202/native_style_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202202/native_style_service/create_native_styles.py b/examples/ad_manager/v202202/native_style_service/create_native_styles.py
new file mode 100755
index 00000000..b805cebb
--- /dev/null
+++ b/examples/ad_manager/v202202/native_style_service/create_native_styles.py
@@ -0,0 +1,178 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Creates a native app install ad."""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+# This is the creative template ID for the system-defined native app install ad
+# format, which we will create the native style from. Use
+# CreativeTemplateService.getCreativeTemplateByStatement() and
+# CreativeTemplate.isNativeEligible() to get other native ad formats available
+# in your network.
+CREATIVE_TEMPLATE_ID = 10004400
+WIDTH = 300
+HEIGHT = 345
+
+HTML_SNIPPET = """
+"""
+
+CSS_SNIPPET = """body {
+ background-color: rgba(255, 255, 255, 1);
+ font-family: "Roboto-Regular", sans-serif;
+ font-weight: normal;
+ font-size: 12px;
+ line-height: 14px;
+}
+.attribution {
+ background-color: rgba(236, 182, 0, 1);
+ color: rgba(255, 255, 255, 1);
+ font-size: 13px;
+ display: table;
+ margin: 4px 8px;
+ padding: 0 3px;
+ border-radius: 2px;
+}
+.image {
+ text-align: center;
+ margin: 8px;
+}
+.image img,
+.image-link {
+ width: 100%;
+}
+.app-icon {
+ float: left;
+ margin: 0 8px 4px 8px;
+ height: 40px;
+ width: 40px;
+ background-color: transparent;
+}
+.app-icon img {
+ height: 100%;
+ width: 100%;
+ border-radius: 20%;
+}
+.title {
+ font-weight: bold;
+ font-size: 14px;
+ line-height: 20px;
+ margin: 8px 8px 4px 8px;
+}
+.title a {
+ color: rgba(112, 112, 112, 1);
+ text-decoration: none;
+}
+.reviews {
+ float: left;
+}
+.reviews svg {
+ fill: rgba(0, 0, 0, 0.7);
+}
+.body {
+ clear: left;
+ margin: 8px;
+}
+.body a {
+ color: rgba(110, 110, 110, 1);
+ text-decoration: none;
+}
+.price {
+ display: none;
+}
+.button {
+ font-size: 14px;
+ font-weight: bold;
+ float: right;
+ margin: 0px 16px 16px 0px;
+ white-space: nowrap;
+}
+.button a {
+ color: #2196F3;
+ text-decoration: none;
+}
+.button svg {
+ display: none;
+}
+"""
+
+
+def main(client, html_snippet, css_snippet, creative_template_id, width,
+ height):
+ # Initialize appropriate service.
+ native_style_service = client.GetService('NativeStyleService',
+ version='v202202')
+
+ native_style = {
+ 'name': 'Native style #%d' % uuid.uuid4(),
+ 'htmlSnippet': html_snippet,
+ 'cssSnippet': css_snippet,
+ 'creativeTemplateId': creative_template_id,
+ 'size': {
+ 'width': width,
+ 'height': height,
+ 'isAspectRatio': False
+ }
+ }
+
+ # Create the native style on the server.
+ native_styles = native_style_service.createNativeStyles([native_style])
+
+ # Display results.
+ for native_style in native_styles:
+ print('A Native style with ID "%s", name "%s", and creative template ID'
+ '"%d" was created.' % (native_style['id'], native_style['name'],
+ native_style['creativeTemplateId']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, HTML_SNIPPET, CSS_SNIPPET, CREATIVE_TEMPLATE_ID,
+ WIDTH, HEIGHT)
diff --git a/examples/ad_manager/v202202/native_style_service/get_all_native_styles.py b/examples/ad_manager/v202202/native_style_service/get_all_native_styles.py
new file mode 100755
index 00000000..2d1d0fa9
--- /dev/null
+++ b/examples/ad_manager/v202202/native_style_service/get_all_native_styles.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all native styles."""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ native_style_service = client.GetService('NativeStyleService',
+ version='v202202')
+
+ # Create a statement to select native styles.
+ statement = ad_manager.StatementBuilder(version='v202202')
+
+ # Retrieve a small amount of native styles at a time, paging
+ # through until all native styles have been retrieved.
+ while True:
+ response = native_style_service.getNativeStylesByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for native_style in response['results']:
+ # Print out some information for each native style.
+ print('Native style with ID "%d" and name "%s" was found.\n' %
+ (native_style['id'], native_style['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/network_service/__init__.py b/examples/ad_manager/v202202/network_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202202/network_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202202/network_service/get_all_networks.py b/examples/ad_manager/v202202/network_service/get_all_networks.py
new file mode 100755
index 00000000..5ce069bd
--- /dev/null
+++ b/examples/ad_manager/v202202/network_service/get_all_networks.py
@@ -0,0 +1,40 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all networks.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ network_service = client.GetService('NetworkService', version='v202202')
+
+ networks = network_service.getAllNetworks()
+
+ # Print out some information for each network.
+ for network in networks:
+ print('Network with network code "%s" and display name "%s" was found.'
+ % (network['networkCode'], network['displayName']))
+
+ print('\nNumber of results found: %s' % len(networks))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/network_service/get_current_network.py b/examples/ad_manager/v202202/network_service/get_current_network.py
new file mode 100755
index 00000000..a04a1f0b
--- /dev/null
+++ b/examples/ad_manager/v202202/network_service/get_current_network.py
@@ -0,0 +1,37 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets the current network."""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ network_service = client.GetService('NetworkService', version='v202202')
+
+ current_network = network_service.getCurrentNetwork()
+
+ print("Current network has network code '%s' and display name '%s'." %
+ (current_network['networkCode'], current_network['displayName']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/network_service/get_default_third_party_data_declaration.py b/examples/ad_manager/v202202/network_service/get_default_third_party_data_declaration.py
new file mode 100755
index 00000000..6ea1ea45
--- /dev/null
+++ b/examples/ad_manager/v202202/network_service/get_default_third_party_data_declaration.py
@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+#
+# Copyright 2020, Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets the network's default third party data declarations."""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate services.
+ network_service = client.GetService('NetworkService', version='v202202')
+ pql_service = client.GetService('PublisherQueryLanguageService',
+ version='v202202')
+
+ # Fetch the default third party data declarations.
+ declarations = network_service.getDefaultThirdPartyDataDeclaration()
+
+ # Display the results.
+ if declarations is None:
+ print('No default ad technology partners have been set on this network.')
+ elif (declarations['declarationType'] == 'NONE' or
+ not declarations['thirdPartyCompanyIds']):
+ print('This network has specified that there are no ad technology providers'
+ ' associated with its reservation creatives by default.')
+ else:
+ print('This network has specified %d ad technology provider(s) associated'
+ ' with its reservation creatives by default:' %
+ len(declarations['thirdPartyCompanyIds']))
+
+ # In this case, there are third party companies to be displayed, so fetch
+ # the company names from the Rich_Media_Ad_Company PQL table.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Select('Id, Name')
+ .From('Rich_Media_Ad_Company')
+ .Where('Id IN (:company_ids)')
+ .WithBindVariable('company_ids',
+ declarations['thirdPartyCompanyIds']))
+
+ while True:
+ response = pql_service.select(statement.ToStatement())
+ if 'rows' in response and len(response['rows']):
+ for company in response['rows']:
+ print('Name: %s, id: %s' % (company['values'][1]['value'],
+ company['values'][0]['value']))
+ statement.offset += statement.limit
+ else:
+ break
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/network_service/make_test_network.py b/examples/ad_manager/v202202/network_service/make_test_network.py
new file mode 100755
index 00000000..07f00c39
--- /dev/null
+++ b/examples/ad_manager/v202202/network_service/make_test_network.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example creates a test network.
+
+You do not need to have an Ad Manager account to run this example, but you do
+need to have a Google account (created at
+http://www.google.com/accounts/newaccount if you currently don't have one) that
+is not associated with any other Ad Manager test networks. Once this network is
+created, you can supply the network code in your settings to make calls to
+other services.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ network_service = client.GetService('NetworkService', version='v202202')
+
+ # Create a test network.
+ network = network_service.makeTestNetwork()
+
+ # Display results.
+ print('Test network with network code "%s" and display name "%s" '
+ 'created.' % (network['networkCode'], network['displayName']))
+ print('You may now sign in at '
+ 'http://www.google.com/admanager/main?networkCode=%s'
+ % network['networkCode'])
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/order_service/__init__.py b/examples/ad_manager/v202202/order_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202202/order_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202202/order_service/approve_orders.py b/examples/ad_manager/v202202/order_service/approve_orders.py
new file mode 100755
index 00000000..13e6f246
--- /dev/null
+++ b/examples/ad_manager/v202202/order_service/approve_orders.py
@@ -0,0 +1,67 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example approves all eligible draft and pending orders.
+
+To determine which orders exist, run get_all_orders.py.
+"""
+
+
+import datetime
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ order_service = client.GetService('OrderService', version='v202202')
+
+ # Create a filter statement.
+ today = datetime.date.today()
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where(('status in (\'DRAFT\', \'PENDING_APPROVAL\') '
+ 'AND endDateTime >= :today AND isArchived = FALSE'))
+ .WithBindVariable('today', today))
+ orders_approved = 0
+
+ # Get orders by statement.
+ while True:
+ response = order_service.getOrdersByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ # Display results.
+ for order in response['results']:
+ print('Order with id "%s", name "%s", and status "%s" will be '
+ 'approved.' % (order['id'], order['name'], order['status']))
+ # Perform action.
+ result = order_service.performOrderAction(
+ {'xsi_type': 'ApproveOrders'}, statement.ToStatement())
+ if result and int(result['numChanges']) > 0:
+ orders_approved += int(result['numChanges'])
+ statement.offset += statement.limit
+ else:
+ break
+
+ # Display results.
+ if orders_approved > 0:
+ print('Number of orders approved: %s' % orders_approved)
+ else:
+ print('No orders were approved.')
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/order_service/create_orders.py b/examples/ad_manager/v202202/order_service/create_orders.py
new file mode 100755
index 00000000..9673abfa
--- /dev/null
+++ b/examples/ad_manager/v202202/order_service/create_orders.py
@@ -0,0 +1,59 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new orders.
+
+To determine which orders exist, run get_all_orders.py.
+"""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
+SALESPERSON_ID = 'INSERT_SALESPERSON_ID_HERE'
+TRAFFICKER_ID = 'INSERT_TRAFFICKER_ID_HERE'
+
+
+def main(client, company_id, salesperson_id, trafficker_id):
+ # Initialize appropriate service.
+ order_service = client.GetService('OrderService', version='v202202')
+
+ # Create order objects.
+ orders = []
+ for _ in range(5):
+ order = {
+ 'name': 'Order #%s' % uuid.uuid4(),
+ 'advertiserId': company_id,
+ 'salespersonId': salesperson_id,
+ 'traffickerId': trafficker_id
+ }
+ orders.append(order)
+
+ # Add orders.
+ orders = order_service.createOrders(orders)
+
+ # Display results.
+ for order in orders:
+ print('Order with id "%s" and name "%s" was created.'
+ % (order['id'], order['name']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, COMPANY_ID, SALESPERSON_ID, TRAFFICKER_ID)
diff --git a/examples/ad_manager/v202202/order_service/get_all_orders.py b/examples/ad_manager/v202202/order_service/get_all_orders.py
new file mode 100755
index 00000000..bf20e081
--- /dev/null
+++ b/examples/ad_manager/v202202/order_service/get_all_orders.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all orders.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ order_service = client.GetService('OrderService', version='v202202')
+
+ # Create a statement to select orders.
+ statement = ad_manager.StatementBuilder(version='v202202')
+
+ # Retrieve a small amount of orders at a time, paging
+ # through until all orders have been retrieved.
+ while True:
+ response = order_service.getOrdersByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for order in response['results']:
+ # Print out some information for each order.
+ print('Order with ID "%d" and name "%s" was found.\n' % (order['id'],
+ order['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/order_service/get_orders_starting_soon.py b/examples/ad_manager/v202202/order_service/get_orders_starting_soon.py
new file mode 100755
index 00000000..1f18ae3e
--- /dev/null
+++ b/examples/ad_manager/v202202/order_service/get_orders_starting_soon.py
@@ -0,0 +1,60 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all orders that are starting soon.
+"""
+
+# Import appropriate modules from the client library.
+from datetime import datetime
+from datetime import timedelta
+
+from googleads import ad_manager
+import pytz
+
+
+def main(client):
+ # Initialize appropriate service.
+ order_service = client.GetService('OrderService', version='v202202')
+ now = datetime.now(tz=pytz.timezone('America/New_York'))
+ soon = now + timedelta(days=5)
+
+ # Create a statement to select orders.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where(('status = :status AND startDateTime >= :now '
+ 'AND startDateTime <= :soon'))
+ .WithBindVariable('status', 'APPROVED')
+ .WithBindVariable('now', now)
+ .WithBindVariable('soon', soon))
+
+ # Retrieve a small amount of orders at a time, paging
+ # through until all orders have been retrieved.
+ while True:
+ response = order_service.getOrdersByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for order in response['results']:
+ # Print out some information for each order.
+ print('Order with ID "%d" and name "%s" was found.\n' % (order['id'],
+ order['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/order_service/update_orders.py b/examples/ad_manager/v202202/order_service/update_orders.py
new file mode 100755
index 00000000..d1dbf700
--- /dev/null
+++ b/examples/ad_manager/v202202/order_service/update_orders.py
@@ -0,0 +1,71 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates the notes of a single order specified by ID.
+
+To determine which orders exist, run get_all_orders.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+ORDER_ID = 'INSERT_ORDER_ID_HERE'
+
+
+def main(client, order_id):
+ # Initialize appropriate service.
+ order_service = client.GetService('OrderService', version='v202202')
+
+ # Create statement object to select a single order by an ID.
+
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('id = :orderId')
+ .WithBindVariable('orderId', int(order_id)))
+
+ # Get orders by statement.
+ response = order_service.getOrdersByStatement(statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ # Update each local order object by changing its notes.
+ updated_orders = []
+ for order in response['results']:
+ # Archived orders cannot be updated.
+ if not order['isArchived']:
+ order['notes'] = 'Spoke to advertiser. All is well.'
+ updated_orders.append(order)
+
+ # Update orders remotely.
+ orders = order_service.updateOrders(updated_orders)
+
+ # Display results.
+ if orders:
+ for order in orders:
+ print('Order with id "%s", name "%s", advertiser id "%s", and '
+ 'notes "%s" was updated.'
+ % (order['id'], order['name'], order['advertiserId'],
+ order['notes']))
+ else:
+ print('No orders were updated.')
+ else:
+ print('No orders found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ORDER_ID)
+
diff --git a/examples/ad_manager/v202202/placement_service/create_placements.py b/examples/ad_manager/v202202/placement_service/create_placements.py
new file mode 100755
index 00000000..6f7ba34f
--- /dev/null
+++ b/examples/ad_manager/v202202/placement_service/create_placements.py
@@ -0,0 +1,108 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new placements for various ad unit sizes.
+
+To determine which placements exist, run get_all_placements.py.
+"""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ placement_service = client.GetService('PlacementService', version='v202202')
+ inventory_service = client.GetService('InventoryService', version='v202202')
+
+ # Create placement object to store medium rectangle ad units.
+ medium_rectangle_ad_unit_placement = {
+ 'name': 'Medium rectangle AdUnit Placement #%s' % uuid.uuid4(),
+ 'description': 'Contains ad units that hold creatives of size 300x250',
+ 'targetedAdUnitIds': []
+ }
+
+ # Create placement object to store skyscraper ad units.
+ skyscraper_ad_unit_placement = {
+ 'name': 'Skyscraper AdUnit Placement #%s' % uuid.uuid4(),
+ 'description': 'Contains ad units that hold creatives of size 120x600',
+ 'targetedAdUnitIds': []
+ }
+
+ # Create placement object to store banner ad units.
+ banner_ad_unit_placement = {
+ 'name': 'Banner AdUnit Placement #%s' % uuid.uuid4(),
+ 'description': 'Contains ad units that hold creatives of size 468x60',
+ 'targetedAdUnitIds': []
+ }
+
+ placement_list = []
+
+ # Create statement to get all the ad units.
+ statement = ad_manager.StatementBuilder(version='v202202')
+
+ while True:
+ response = inventory_service.getAdUnitsByStatement(
+ statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ # Separate the ad units by size.
+ for ad_unit in response['results']:
+ if 'adUnitSizes' in ad_unit:
+ for ad_unit_size in ad_unit['adUnitSizes']:
+ size = ad_unit_size['size']
+ if size['width'] == '300' and size['height'] == '250':
+ medium_rectangle_ad_unit_placement['targetedAdUnitIds'].append(
+ ad_unit['id'])
+ elif size['width'] == '120' and size['height'] == '600':
+ skyscraper_ad_unit_placement['targetedAdUnitIds'].append(
+ ad_unit['id'])
+ elif size['width'] == '468' and size['height'] == '60':
+ banner_ad_unit_placement['targetedAdUnitIds'].append(
+ ad_unit['id'])
+ statement.offset += statement.limit
+ else:
+ break
+
+ # Only create placements with one or more ad unit.
+ if medium_rectangle_ad_unit_placement['targetedAdUnitIds']:
+ placement_list.append(medium_rectangle_ad_unit_placement)
+
+ if skyscraper_ad_unit_placement['targetedAdUnitIds']:
+ placement_list.append(skyscraper_ad_unit_placement)
+
+ if banner_ad_unit_placement['targetedAdUnitIds']:
+ placement_list.append(banner_ad_unit_placement)
+
+ # Add placements.
+ placements = placement_service.createPlacements(placement_list)
+
+ # Display results.
+ for placement in placements:
+ ad_unit_ids = ''
+ if 'targetedAdUnitIds' in placement:
+ ad_unit_ids = ', '.join(placement['targetedAdUnitIds'])
+ print('A Placement with ID "%s", name "%s", and containing ad units '
+ '{%s} was created.' % (placement['id'], placement['name'],
+ ad_unit_ids))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/placement_service/deactivate_placements.py b/examples/ad_manager/v202202/placement_service/deactivate_placements.py
new file mode 100755
index 00000000..f2725cab
--- /dev/null
+++ b/examples/ad_manager/v202202/placement_service/deactivate_placements.py
@@ -0,0 +1,62 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example deactivates all active placements.
+
+To determine which placements exist, run get_all_placements.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+PLACEMENT_ID = 'INSERT_PLACEMENT_ID_HERE'
+
+
+def main(client, placement_id):
+ # Initialize appropriate service.
+ placement_service = client.GetService('PlacementService', version='v202202')
+
+ # Create query.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('id = :placementId')
+ .WithBindVariable('placementId', int(placement_id))
+ .Limit(1))
+
+ # Get placements by statement.
+ placements = placement_service.getPlacementsByStatement(
+ statement.ToStatement())
+
+ for placement in placements:
+ print('Placement with id "%s", name "%s", and status "%s" will be '
+ 'deactivated.' % (placement['id'], placement['name'],
+ placement['status']))
+
+ # Perform action.
+ result = placement_service.performPlacementAction(
+ {'xsi_type': 'DeactivatePlacements'}, statement.ToStatement())
+
+ # Display results.
+ if result and int(result['numChanges']) > 0:
+ print('Number of placements deactivated: %s' % result['numChanges'])
+ else:
+ print('No placements were deactivated.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, PLACEMENT_ID)
diff --git a/examples/ad_manager/v202202/placement_service/get_active_placements.py b/examples/ad_manager/v202202/placement_service/get_active_placements.py
new file mode 100755
index 00000000..364b488a
--- /dev/null
+++ b/examples/ad_manager/v202202/placement_service/get_active_placements.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all active placements.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ placement_service = client.GetService('PlacementService', version='v202202')
+ # Create a statement to select placements.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('status = :status')
+ .WithBindVariable('status', 'ACTIVE'))
+
+ # Retrieve a small amount of placements at a time, paging
+ # through until all placements have been retrieved.
+ while True:
+ response = placement_service.getPlacementsByStatement(statement.ToStatement(
+ ))
+ if 'results' in response and len(response['results']):
+ for placement in response['results']:
+ # Print out some information for each placement.
+ print('Placement with ID "%d" and name "%s" was found.\n' %
+ (placement['id'], placement['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/placement_service/get_all_placements.py b/examples/ad_manager/v202202/placement_service/get_all_placements.py
new file mode 100755
index 00000000..b8c5f3f1
--- /dev/null
+++ b/examples/ad_manager/v202202/placement_service/get_all_placements.py
@@ -0,0 +1,50 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all placements.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ placement_service = client.GetService('PlacementService', version='v202202')
+
+ # Create a statement to select placements.
+ statement = ad_manager.StatementBuilder(version='v202202')
+
+ # Retrieve a small amount of placements at a time, paging
+ # through until all placements have been retrieved.
+ while True:
+ response = placement_service.getPlacementsByStatement(statement.ToStatement(
+ ))
+ if 'results' in response and len(response['results']):
+ for placement in response['results']:
+ # Print out some information for each placement.
+ print('Placement with ID "%d" and name "%s" was found.\n' %
+ (placement['id'], placement['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/placement_service/update_placements.py b/examples/ad_manager/v202202/placement_service/update_placements.py
new file mode 100755
index 00000000..4233e32f
--- /dev/null
+++ b/examples/ad_manager/v202202/placement_service/update_placements.py
@@ -0,0 +1,58 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates a single placement to allow for AdSense targeting.
+
+To determine which placements exist, run get_all_placements.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+PLACEMENT_ID = 'INSERT_PLACEMENT_ID_HERE'
+
+
+def main(client, placement_id):
+ # Initialize appropriate service.
+ placement_service = client.GetService('PlacementService', version='v202202')
+
+ # Create query.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('id = :id')
+ .OrderBy('id', ascending=True)
+ .Limit(1)
+ .WithBindVariable('id', placement_id))
+
+ # Get placements by statement.
+ page = placement_service.getPlacementsByStatement(
+ statement.ToStatement())
+
+ placement = page['results'][0]
+
+ placement['description'] = 'This placement contains all leaderboards.'
+
+ # Update placements remotely.
+ updated_placements = placement_service.updatePlacements([placement])
+
+ for placement in updated_placements:
+ print('Placement with id "%s" and name "%s" was updated.'
+ % (placement['id'], placement['name']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, PLACEMENT_ID)
diff --git a/examples/ad_manager/v202202/proposal_line_item_service/__init__.py b/examples/ad_manager/v202202/proposal_line_item_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202202/proposal_line_item_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202202/proposal_line_item_service/archive_proposal_line_items.py b/examples/ad_manager/v202202/proposal_line_item_service/archive_proposal_line_items.py
new file mode 100755
index 00000000..c9f7a6d3
--- /dev/null
+++ b/examples/ad_manager/v202202/proposal_line_item_service/archive_proposal_line_items.py
@@ -0,0 +1,76 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example archives a proposal line item.
+
+To determine which proposal line items exist, run
+get_all_proposal_line_items.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the id of the proposal line item to archive.
+PROPOSAL_LINE_ITEM_ID = 'INSERT_PROPOSAL_LINE_ITEM_ID_HERE'
+
+
+def main(client, proposal_line_item_id):
+ # Initialize appropriate service.
+ proposal_line_item_service = client.GetService(
+ 'ProposalLineItemService', version='v202202')
+
+ # Create query.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('id = :id')
+ .WithBindVariable('id', int(proposal_line_item_id))
+ .Limit(1))
+
+ proposal_line_items_archived = 0
+
+ # Get proposal line items by statement.
+ while True:
+ response = proposal_line_item_service.getProposalLineItemsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for proposal_line_item in response['results']:
+ print('Proposal line item with id "%s", '
+ 'belonging to proposal id "%s", and '
+ 'name "%s" will be archived.' %
+ (proposal_line_item['id'], proposal_line_item['proposalId'],
+ proposal_line_item['name']))
+
+ # Perform action.
+ result = proposal_line_item_service.performProposalLineItemAction(
+ {'xsi_type': 'ArchiveProposalLineItems'}, statement.ToStatement())
+ if result and int(result['numChanges']) > 0:
+ proposal_line_items_archived += int(result['numChanges'])
+ statement.offset += statement.limit
+ else:
+ break
+
+ # Display results.
+ if proposal_line_items_archived > 0:
+ print('Number of proposal line items '
+ 'archived: %s' % proposal_line_items_archived)
+ else:
+ print('No proposal line items were archived.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, PROPOSAL_LINE_ITEM_ID)
diff --git a/examples/ad_manager/v202202/proposal_line_item_service/create_proposal_line_items.py b/examples/ad_manager/v202202/proposal_line_item_service/create_proposal_line_items.py
new file mode 100755
index 00000000..fe981122
--- /dev/null
+++ b/examples/ad_manager/v202202/proposal_line_item_service/create_proposal_line_items.py
@@ -0,0 +1,108 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Creates a proposal line item."""
+
+
+import datetime
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+import pytz
+
+# Set proposal that the created proposal line item will belong to.
+PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE'
+
+
+def main(client, proposal_id):
+ proposal_line_item_service = client.GetService(
+ 'ProposalLineItemService', version='v202202')
+ network_service = client.GetService('NetworkService', version='v202202')
+
+ start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York'))
+ end_datetime = start_datetime + datetime.timedelta(days=365)
+
+ # Get the root ad unit to target.
+ root_ad_unit_id = (
+ network_service.getCurrentNetwork()['effectiveRootAdUnitId'])
+
+ # Create a single programmatic proposal line item.
+ proposal_line_item = {
+ # Setting common required fields for proposal line items.
+ 'name': 'Proposal line item #%s' % uuid.uuid4(),
+ 'proposalId': proposal_id,
+ 'targeting': {
+ 'inventoryTargeting': {
+ 'targetedAdUnits': {
+ 'adUnitId': root_ad_unit_id
+ }
+ },
+ 'requestPlatformTargeting': {
+ 'targetedRequestPlatforms': ['BROWSER']
+ },
+ # Target Display environment by excluding Mobile Apps.
+ # DeviceCapabilities can be obtained though the Device_Capability PQL
+ # table:
+ # https://developers.google.com/ad-manager/api/reference/latest/PublisherQueryLanguageService
+ 'technologyTargeting': {
+ 'deviceCapabilityTargeting': [{'id': 5005}]
+ }
+ },
+ 'startDateTime': start_datetime,
+ 'endDateTime': end_datetime,
+ 'creativePlaceholders': [
+ {
+ 'size': {
+ 'width': '300',
+ 'height': '250'
+ }
+ },
+ {
+ 'size': {
+ 'width': '120',
+ 'height': '600'
+ }
+ }
+ ],
+ 'goal': {
+ 'units': '1000',
+ 'unitType': 'IMPRESSIONS',
+ },
+ 'netRate': {
+ 'currencyCode': 'USD',
+ 'microAmount': '2000000'
+ },
+ 'rateType': 'CPM',
+ }
+
+ # Add proposal line items.
+ proposal_line_items = proposal_line_item_service.createProposalLineItems(
+ [proposal_line_item])
+
+ # Display results.
+ for proposal_line_item in proposal_line_items:
+ print('Proposal line item with id "%s", belonging to proposal with id "%s",'
+ ' and named "%s" was created.' % (proposal_line_item['id'],
+ proposal_line_item['proposalId'],
+ proposal_line_item['name']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, PROPOSAL_ID)
+
diff --git a/examples/ad_manager/v202202/proposal_line_item_service/get_all_proposal_line_items.py b/examples/ad_manager/v202202/proposal_line_item_service/get_all_proposal_line_items.py
new file mode 100755
index 00000000..f21a3aca
--- /dev/null
+++ b/examples/ad_manager/v202202/proposal_line_item_service/get_all_proposal_line_items.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all proposal line items.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ proposal_line_item_service = client.GetService(
+ 'ProposalLineItemService', version='v202202')
+
+ # Create a statement to select proposal line items.
+ statement = ad_manager.StatementBuilder(version='v202202')
+
+ # Retrieve a small amount of proposal line items at a time, paging
+ # through until all proposal line items have been retrieved.
+ while True:
+ response = proposal_line_item_service.getProposalLineItemsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for proposal_line_item in response['results']:
+ # Print out some information for each proposal line item.
+ print('Proposal line item with ID "%d" and name "%s" was found.\n' %
+ (proposal_line_item['id'], proposal_line_item['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/ad_manager/v202202/proposal_line_item_service/get_proposal_line_items_for_proposal.py
new file mode 100755
index 00000000..8ce81962
--- /dev/null
+++ b/examples/ad_manager/v202202/proposal_line_item_service/get_proposal_line_items_for_proposal.py
@@ -0,0 +1,54 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all proposal line items belonging to a specific proposal.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE'
+
+
+def main(client, proposal_id):
+ # Initialize appropriate service.
+ proposal_line_item_service = client.GetService(
+ 'ProposalLineItemService', version='v202202')
+ # Create a statement to select proposal line items.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('proposalId = :proposalId')
+ .WithBindVariable('proposalId', proposal_id))
+
+ # Retrieve a small amount of proposal line items at a time, paging
+ # through until all proposal line items have been retrieved.
+ while True:
+ response = proposal_line_item_service.getProposalLineItemsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for proposal_line_item in response['results']:
+ # Print out some information for each proposal line item.
+ print('Proposal line item with ID "%d" and name "%s" was found.\n' %
+ (proposal_line_item['id'], proposal_line_item['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, PROPOSAL_ID)
diff --git a/examples/ad_manager/v202202/proposal_line_item_service/update_proposal_line_items.py b/examples/ad_manager/v202202/proposal_line_item_service/update_proposal_line_items.py
new file mode 100755
index 00000000..31e1e669
--- /dev/null
+++ b/examples/ad_manager/v202202/proposal_line_item_service/update_proposal_line_items.py
@@ -0,0 +1,72 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates a proposal line item's notes.
+
+To determine which proposal line items exist,
+run get_all_proposal_line_items.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set id of the proposal line item to update.
+PROPOSAL_LINE_ITEM_ID = 'INSERT_PROPOSAL_LINE_ITEM_ID_HERE'
+
+
+def main(client, proposal_line_item_id):
+ # Initialize appropriate service.
+ proposal_line_item_service = client.GetService(
+ 'ProposalLineItemService', version='v202202')
+
+ # Create statement to select a proposal line item.
+
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('id = :id')
+ .WithBindVariable('id', int(proposal_line_item_id))
+ .Limit(1))
+
+ # Get proposal line items by statement.
+ response = proposal_line_item_service.getProposalLineItemsByStatement(
+ statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ # Update each the proposal line item's notes field.
+ proposal_line_item = response['results'][0]
+ proposal_line_item['internalNotes'] = 'Proposal line is ready to submit.'
+
+ # Update proposal line items remotely.
+ proposal_line_items = proposal_line_item_service.updateProposalLineItems(
+ [proposal_line_item])
+
+ # Display results.
+ if proposal_line_items:
+ for proposal_line_item in proposal_line_items:
+ print('Line item with id "%s", belonging to proposal id "%s" and,'
+ ' named "%s" was updated.' % (
+ proposal_line_item['id'], proposal_line_item['proposalId'],
+ proposal_line_item['name']))
+ else:
+ print('No proposal line items were updated.')
+ else:
+ print('No proposal line items found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, PROPOSAL_LINE_ITEM_ID)
diff --git a/examples/ad_manager/v202202/proposal_service/__init__.py b/examples/ad_manager/v202202/proposal_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202202/proposal_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202202/proposal_service/create_proposals.py b/examples/ad_manager/v202202/proposal_service/create_proposals.py
new file mode 100755
index 00000000..ac639cf8
--- /dev/null
+++ b/examples/ad_manager/v202202/proposal_service/create_proposals.py
@@ -0,0 +1,61 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example creates a proposal."""
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+PROGRAMMATIC_BUYER_ID = 'INSERT_BUYER_ID_FROM_PQL_TABLE_HERE'
+PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE'
+PRIMARY_TRAFFICKER_ID = 'INSERT_PRIMARY_TRAFFICKER_ID_HERE'
+
+
+def main(client, programmatic_buyer_id, primary_salesperson_id,
+ primary_trafficker_id):
+ proposal_service = client.GetService('ProposalService', version='v202202')
+
+ proposal = {
+ # Setting required Marketplace information.
+ 'isProgrammatic': 'true',
+ 'marketplaceInfo': {
+ 'buyerAccountId': programmatic_buyer_id,
+ },
+ # Set common required fields for proposals.
+ 'name': 'Proposal #%s' % uuid.uuid4(),
+ 'primarySalesperson': {
+ 'userId': primary_salesperson_id,
+ 'split': '100000'
+ },
+ 'primaryTraffickerId': primary_trafficker_id,
+ 'probabilityOfClose': '100000',
+ }
+
+ proposals = proposal_service.createProposals([proposal])
+
+ # Display results.
+ for proposal in proposals:
+ print('Proposal with id "%s" and name "%s" was created.' %
+ (proposal['id'], proposal['name']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, PROGRAMMATIC_BUYER_ID, PRIMARY_SALESPERSON_ID,
+ PRIMARY_TRAFFICKER_ID)
diff --git a/examples/ad_manager/v202202/proposal_service/get_all_proposals.py b/examples/ad_manager/v202202/proposal_service/get_all_proposals.py
new file mode 100755
index 00000000..8642ec2a
--- /dev/null
+++ b/examples/ad_manager/v202202/proposal_service/get_all_proposals.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all proposals.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ proposal_service = client.GetService('ProposalService', version='v202202')
+
+ # Create a statement to select proposals.
+ statement = ad_manager.StatementBuilder(version='v202202')
+
+ # Retrieve a small amount of proposals at a time, paging
+ # through until all proposals have been retrieved.
+ while True:
+ response = proposal_service.getProposalsByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for proposal in response['results']:
+ # Print out some information for each proposal.
+ print('Proposal with ID "%d" and name "%s" was found.\n' %
+ (proposal['id'], proposal['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/proposal_service/get_marketplace_comments.py b/examples/ad_manager/v202202/proposal_service/get_marketplace_comments.py
new file mode 100755
index 00000000..293f4c02
--- /dev/null
+++ b/examples/ad_manager/v202202/proposal_service/get_marketplace_comments.py
@@ -0,0 +1,56 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets the Marketplace comments for a programmatic proposal."""
+
+# Import appropriate modules from the client library.
+from datetime import datetime
+
+from googleads import ad_manager
+
+
+PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE'
+
+
+def main(client, proposal_id):
+ # Initialize appropriate service.
+ marketplace_comment_service = client.GetService(
+ 'ProposalService', version='v202202')
+ query = 'WHERE proposalId = %s' % proposal_id
+ # Create a statement to select marketplace comments.
+ statement = {'query': query}
+
+ response = marketplace_comment_service.getMarketplaceCommentsByStatement(
+ statement)
+
+ # Print out some information for each marketplace comment.
+ for marketplace_comment in response['results']:
+ date_time = marketplace_comment['creationTime']
+ date_time_string = datetime(date_time['date']['year'],
+ date_time['date']['month'],
+ date_time['date']['day'], date_time['hour'],
+ date_time['minute'],
+ date_time['second']).isoformat()
+ print('Marketplace comment with creation time "%s"and comment "%s" was '
+ 'found.\n' % (date_time_string, marketplace_comment['comment']))
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, PROPOSAL_ID)
diff --git a/examples/ad_manager/v202202/proposal_service/get_proposals_awaiting_seller_review.py b/examples/ad_manager/v202202/proposal_service/get_proposals_awaiting_seller_review.py
new file mode 100755
index 00000000..c7260db1
--- /dev/null
+++ b/examples/ad_manager/v202202/proposal_service/get_proposals_awaiting_seller_review.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all proposals awaiting seller review."""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ proposal_service = client.GetService('ProposalService', version='v202202')
+ # Create a statement to select proposals.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('negotiationStatus = :negotiationStatus')
+ .WithBindVariable('negotiationStatus', 'AWAITING_SELLER_REVIEW'))
+
+ # Retrieve a small amount of proposals at a time, paging
+ # through until all proposals have been retrieved.
+ while True:
+ response = proposal_service.getProposalsByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for proposal in response['results']:
+ # Print out some information for each proposal.
+ print('Proposal with ID "%d" and name "%s" was found.\n' %
+ (proposal['id'], proposal['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/proposal_service/request_buyers_acceptance.py b/examples/ad_manager/v202202/proposal_service/request_buyers_acceptance.py
new file mode 100755
index 00000000..253c8ed6
--- /dev/null
+++ b/examples/ad_manager/v202202/proposal_service/request_buyers_acceptance.py
@@ -0,0 +1,67 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example requests buyer acceptance for a single proposal.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE'
+
+
+def main(client, proposal_id):
+ # Initialize appropriate service.
+ proposal_service = client.GetService('ProposalService', version='v202202')
+
+ # Create query.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('id = :proposalId')
+ .WithBindVariable('proposalId', proposal_id))
+ proposals_pushed_to_marketplace = 0
+
+ # Get proposals by statement.
+ while True:
+ response = proposal_service.getProposalsByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ # Display results.
+ for proposal in response['results']:
+ print('Programmatic proposal with id "%s", name "%s", and status '
+ '"%s" will be pushed to Marketplace.' % (proposal['id'],
+ proposal['name'],
+ proposal['status']))
+ # Perform action.
+ result = proposal_service.performProposalAction(
+ {'xsi_type': 'RequestBuyerAcceptance'}, statement.ToStatement())
+ if result and int(result['numChanges']) > 0:
+ proposals_pushed_to_marketplace += int(result['numChanges'])
+ statement.offset += statement.limit
+ else:
+ break
+
+ # Display results.
+ if proposals_pushed_to_marketplace > 0:
+ print('\nNumber of programmatic proposals pushed to Marketplace: %s'
+ % proposals_pushed_to_marketplace)
+ else:
+ print('\nNo programmatic proposals were pushed to Marketplace.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, PROPOSAL_ID)
diff --git a/examples/ad_manager/v202202/proposal_service/update_proposals.py b/examples/ad_manager/v202202/proposal_service/update_proposals.py
new file mode 100755
index 00000000..7112fec9
--- /dev/null
+++ b/examples/ad_manager/v202202/proposal_service/update_proposals.py
@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates the notes of a single proposal specified by ID.
+
+To determine which proposals exist, run get_all_proposals.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE'
+
+
+def main(client, proposal_id):
+ # Initialize appropriate service.
+ proposal_service = client.GetService('ProposalService', version='v202202')
+
+ # Create statement object to select a single proposal by an ID.
+
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('id = :proposalId')
+ .WithBindVariable('proposalId', int(proposal_id))
+ .Limit(1))
+
+ # Get proposals by statement.
+ response = proposal_service.getProposalsByStatement(statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ # Update each local proposal object by changing its notes.
+ updated_proposals = []
+ for proposal in response['results']:
+ proposal['internalNotes'] = 'Proposal needs review before approval.'
+ updated_proposals.append(proposal)
+
+ # Update proposals remotely.
+ proposals = proposal_service.updateProposals(updated_proposals)
+
+ # Display results.
+ if proposals:
+ for proposal in proposals:
+ print('Proposal with id "%s", name "%s", and '
+ 'notes "%s" was updated.'
+ % (proposal['id'], proposal['name'], proposal['internalNotes']))
+ else:
+ print('No proposals were updated.')
+ else:
+ print('No proposals found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, PROPOSAL_ID)
diff --git a/examples/ad_manager/v202202/publisher_query_language_service/__init__.py b/examples/ad_manager/v202202/publisher_query_language_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202202/publisher_query_language_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202202/publisher_query_language_service/fetch_match_tables.py b/examples/ad_manager/v202202/publisher_query_language_service/fetch_match_tables.py
new file mode 100755
index 00000000..52fa3bd7
--- /dev/null
+++ b/examples/ad_manager/v202202/publisher_query_language_service/fetch_match_tables.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example fetches data from PQL tables and creates match table files."""
+
+
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize a report downloader.
+ report_downloader = client.GetDataDownloader(version='v202202')
+
+ line_items_file = tempfile.NamedTemporaryFile(
+ prefix='line_items_', suffix='.csv', mode='w', delete=False)
+ ad_units_file = tempfile.NamedTemporaryFile(
+ prefix='ad_units_', suffix='.csv', mode='w', delete=False)
+
+ line_items_pql_query = ('SELECT Name, Id, Status FROM Line_Item ORDER BY Id '
+ 'ASC')
+ ad_units_pql_query = 'SELECT Name, Id FROM Ad_Unit ORDER BY Id ASC'
+
+ # Downloads the response from PQL select statement to the specified file
+ report_downloader.DownloadPqlResultToCsv(
+ line_items_pql_query, line_items_file)
+ report_downloader.DownloadPqlResultToCsv(
+ ad_units_pql_query, ad_units_file)
+
+ line_items_file.close()
+ ad_units_file.close()
+
+ print('Saved line items to... %s' % line_items_file.name)
+ print('Saved ad units to... %s' % ad_units_file.name)
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/publisher_query_language_service/get_all_browsers.py b/examples/ad_manager/v202202/publisher_query_language_service/get_all_browsers.py
new file mode 100755
index 00000000..33b4ed85
--- /dev/null
+++ b/examples/ad_manager/v202202/publisher_query_language_service/get_all_browsers.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all browsers available to target from the Browser table.
+
+Other tables include 'Bandwidth_Group', 'Browser_Language',
+'Device_Capability', 'Operating_System', etc...
+
+A full list of available criteria tables can be found at
+https://developers.google.com/doubleclick-publishers/docs/reference/v201708/PublisherQueryLanguageService
+"""
+
+
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize a report downloader.
+ report_downloader = client.GetDataDownloader(version='v202202')
+
+ with tempfile.NamedTemporaryFile(
+ prefix='browser_data_',
+ suffix='.csv', mode='w', delete=False) as browser_data_file:
+
+ browser_pql_query = ('SELECT Id, BrowserName, MajorVersion, MinorVersion '
+ 'FROM Browser '
+ 'ORDER BY BrowserName ASC')
+
+ # Downloads the response from PQL select statement to the specified file
+ report_downloader.DownloadPqlResultToCsv(
+ browser_pql_query, browser_data_file)
+
+ print('Saved browser data to... %s' % browser_data_file.name)
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/ad_manager/v202202/publisher_query_language_service/get_all_programmatic_buyers.py
new file mode 100755
index 00000000..498c2b22
--- /dev/null
+++ b/examples/ad_manager/v202202/publisher_query_language_service/get_all_programmatic_buyers.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example fetches programmatic buyer information from the PQL table."""
+
+
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize a report downloader.
+ data_downloader = client.GetDataDownloader(version='v202202')
+
+ programmatic_buyers_file = tempfile.NamedTemporaryFile(
+ prefix='programmatic_buyers_', suffix='.csv', mode='w', delete=False)
+
+ programmatic_buyers_query = ('SELECT BuyerAccountId, Name '
+ 'FROM Programmatic_Buyer '
+ 'ORDER BY BuyerAccountId ASC')
+
+ # Downloads the response from PQL select statement to the specified file
+ data_downloader.DownloadPqlResultToCsv(
+ programmatic_buyers_query, programmatic_buyers_file)
+
+ programmatic_buyers_file.close()
+
+ print('Saved programmatic buyers to... %s' % programmatic_buyers_file.name)
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/publisher_query_language_service/get_geo_targets.py b/examples/ad_manager/v202202/publisher_query_language_service/get_geo_targets.py
new file mode 100755
index 00000000..ae3d0ace
--- /dev/null
+++ b/examples/ad_manager/v202202/publisher_query_language_service/get_geo_targets.py
@@ -0,0 +1,53 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example downloads geo targeting constants using PQL."""
+
+
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the type of geo target to query for.
+GEO_TARGET_TYPE = 'City'
+
+
+def main(client):
+ # Initialize a report downloader.
+ report_downloader = client.GetDataDownloader(version='v202202')
+
+ with tempfile.NamedTemporaryFile(
+ prefix='geo_data_',
+ suffix='.csv', mode='w', delete=False) as geo_data_file:
+
+ geo_pql_query = ('SELECT Id, Name, CanonicalParentId, ParentIds, '
+ 'CountryCode, Type '
+ 'FROM Geo_Target '
+ 'WHERE Type = :type AND Targetable = true '
+ 'ORDER BY CountryCode ASC, Name ASC')
+
+ # Downloads the response from PQL select statement to the specified file
+ report_downloader.DownloadPqlResultToCsv(
+ geo_pql_query, geo_data_file, {'type': geo_target_type})
+
+ print('Saved geo data to... %s' % geo_data_file.name)
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, GEO_TARGET_TYPE)
diff --git a/examples/ad_manager/v202202/publisher_query_language_service/get_line_items_named_like.py b/examples/ad_manager/v202202/publisher_query_language_service/get_line_items_named_like.py
new file mode 100755
index 00000000..e72cc87f
--- /dev/null
+++ b/examples/ad_manager/v202202/publisher_query_language_service/get_line_items_named_like.py
@@ -0,0 +1,48 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example fetches line items from the pql table with a LIKE clause."""
+
+
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize a report downloader.
+ report_downloader = client.GetDataDownloader(version='v202202')
+
+ with tempfile.NamedTemporaryFile(
+ prefix='line_items_',
+ suffix='.csv', mode='w', delete=False) as line_items_file:
+
+ line_items_pql_query = ("SELECT Id, Name, Status FROM Line_Item "
+ "WHERE Name LIKE 'line item%' "
+ "ORDER BY Id ASC")
+
+ # Downloads the response from PQL select statement to the specified file
+ report_downloader.DownloadPqlResultToCsv(
+ line_items_pql_query, line_items_file)
+
+ print('Saved line items to... %s' % line_items_file.name)
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/publisher_query_language_service/get_mcm_earnings.py b/examples/ad_manager/v202202/publisher_query_language_service/get_mcm_earnings.py
new file mode 100755
index 00000000..ed393c7a
--- /dev/null
+++ b/examples/ad_manager/v202202/publisher_query_language_service/get_mcm_earnings.py
@@ -0,0 +1,58 @@
+#!/usr/bin/env python
+#
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets Multiple Customer Management earnings for the prior month.
+"""
+
+import datetime
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize a report downloader.
+ data_downloader = client.GetDataDownloader(version='v202202')
+
+ with tempfile.NamedTemporaryFile(
+ prefix='mcm_earnings_',
+ suffix='.csv', mode='w', delete=False) as mcm_earnings_file:
+
+ this_month_start = datetime.date.today().replace(day=1)
+ last_month_end = this_month_start - datetime.timedelta(days=1)
+ last_month_start = last_month_end.replace(day=1)
+
+ mcm_earnings_query = ('SELECT Month, ChildName, ChildNetworkCode, '
+ 'TotalEarningsCurrencyCode, TotalEarningsMicros, '
+ 'ParentPaymentCurrencyCode, ParentPaymentMicros, '
+ 'ChildPaymentCurrencyCode, ChildPaymentMicros, '
+ 'DeductionsMicros '
+ 'FROM Mcm_Earnings '
+ 'WHERE Month = :month '
+ 'ORDER BY ChildNetworkCode')
+
+ # Downloads the response from PQL select statement to the specified file
+ data_downloader.DownloadPqlResultToCsv(
+ mcm_earnings_query, mcm_earnings_file, {'month': last_month_start})
+
+ print('Saved MCM earnings to... %s' % mcm_earnings_file.name)
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/publisher_query_language_service/get_recent_changes.py b/examples/ad_manager/v202202/publisher_query_language_service/get_recent_changes.py
new file mode 100755
index 00000000..0dfdf202
--- /dev/null
+++ b/examples/ad_manager/v202202/publisher_query_language_service/get_recent_changes.py
@@ -0,0 +1,156 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Gets recent changes in your network using the Change_History table.
+
+A full list of available tables can be found at:
+https://developers.google.com/doubleclick-publishers/docs/reference/latest/PublisherQueryLanguageService
+"""
+
+from datetime import date
+from datetime import datetime
+from datetime import timedelta
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+import pytz
+
+
+def main(client):
+ # Initialize appropriate service.
+ pql_service = client.GetService('PublisherQueryLanguageService', 'v202202')
+
+ end_date = datetime.now(tz=pytz.timezone('America/New_York'))
+ start_date = end_date - timedelta(days=1)
+ initial_query = ('ChangeDateTime > :startDateTime '
+ 'AND ChangeDateTime < :endDateTime')
+ pagination_query = 'Id < :id AND ' + initial_query
+
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Select(('Id, ChangeDateTime, EntityId, EntityType, '
+ 'Operation, UserId'))
+ .From('Change_History')
+ .Where(initial_query)
+ .OrderBy('ChangeDateTime', ascending=False)
+ .WithBindVariable('startDateTime', start_date)
+ .WithBindVariable('endDateTime', end_date))
+
+ keep_iterating = True
+ i = 0
+ total_rows = []
+
+ while keep_iterating:
+ response = pql_service.select(statement.ToStatement())
+ column_types = ([column_type['labelName']
+ for column_type in response['columnTypes']])
+ rows = response['rows']
+ rows_length = len(rows)
+ total_rows.extend(rows)
+
+ if rows and rows_length > 0:
+ # Get the earliest change ID in the result set.
+ last_row = rows[-1]
+ last_id = last_row['values'][0]['value']
+ i += 1
+
+ # Update the statement using the earliest row in the previous result.
+ statement.Where(pagination_query)
+ statement.WithBindVariable('id', last_id)
+
+ print('%d) %d changes prior to ID "%s" were found.\n'
+ % (i, rows_length, last_id))
+
+ keep_iterating = rows and len(rows) == statement.limit
+
+ # Print out columns header
+ print(','.join(column_types))
+
+ # Print out every row
+ for row in total_rows:
+ print(ConvertValueForCsv(row))
+
+
+def ConvertValueForCsv(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.
+ """
+ if 'value' in pql_value:
+ field = pql_value['value']
+ elif 'values' in pql_value:
+ field = pql_value['values']
+ else:
+ field = None
+
+ if field:
+ if isinstance(field, list):
+ return ','.join(['"%s"' % str(ConvertValueForCsv(single_field))
+ for single_field in field])
+ else:
+ class_type = ad_manager.AdManagerClassType(pql_value)
+
+ if class_type == 'TextValue':
+ return field.replace('"', '""').encode('UTF8')
+ elif class_type == 'NumberValue':
+ return float(field) if '.' in field else int(field)
+ elif class_type == 'DateTimeValue':
+ return ConvertDateTimeToOffset(field)
+ elif class_type == 'DateValue':
+ return date(int(field['date']['year']),
+ int(field['date']['month']),
+ int(field['date']['day'])).isoformat()
+ else:
+ return field
+ else:
+ return '-'
+
+
+def ConvertDateTimeToOffset(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 of the date time value uniform to
+ ReportService.
+ """
+ date_time_obj = datetime(int(date_time_value['date']['year']),
+ int(date_time_value['date']['month']),
+ int(date_time_value['date']['day']),
+ int(date_time_value['hour']),
+ int(date_time_value['minute']),
+ int(date_time_value['second']))
+ date_time_str = pytz.timezone(
+ date_time_value['timeZoneId']).localize(date_time_obj).isoformat()
+
+ if date_time_str[-5:] == '00:00':
+ return date_time_str[:-6] + 'Z'
+ else:
+ return date_time_str
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/report_service/__init__.py b/examples/ad_manager/v202202/report_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202202/report_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202202/report_service/run_ad_exchange_report.py b/examples/ad_manager/v202202/report_service/run_ad_exchange_report.py
new file mode 100755
index 00000000..e1d8267d
--- /dev/null
+++ b/examples/ad_manager/v202202/report_service/run_ad_exchange_report.py
@@ -0,0 +1,66 @@
+#!/usr/bin/env python
+#
+# Copyright 2018 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Runs a report on Ad Exchange data via the Ad Manager API."""
+
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+from googleads import errors
+
+
+def main(client):
+ # Initialize a DataDownloader.
+ report_downloader = client.GetDataDownloader(version='v202202')
+
+ # Create report job.
+ report_job = {
+ 'reportQuery': {
+ 'dimensions': ['AD_EXCHANGE_DATE', 'AD_EXCHANGE_COUNTRY_NAME'],
+ 'columns': ['AD_EXCHANGE_AD_REQUESTS', 'AD_EXCHANGE_IMPRESSIONS',
+ 'AD_EXCHANGE_ESTIMATED_REVENUE'],
+ 'dateRangeType': 'LAST_WEEK',
+ 'timeZoneType': 'AD_EXCHANGE', # Run in pacific time
+ 'adxReportCurrency': 'EUR'
+ }
+ }
+
+ try:
+ # Run the report and wait for it to finish.
+ report_job_id = report_downloader.WaitForReport(report_job)
+ except errors.AdManagerReportError as e:
+ print('Failed to generate report. Error was: %s' % e)
+
+ # Change to your preferred export format.
+ export_format = 'CSV_DUMP'
+
+ report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
+
+ # Download report data.
+ report_downloader.DownloadReportToFile(
+ report_job_id, export_format, report_file)
+
+ report_file.close()
+
+ # Display results.
+ print('Report job with id "%s" downloaded to:\n%s' % (
+ report_job_id, report_file.name))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/report_service/run_delivery_report.py b/examples/ad_manager/v202202/report_service/run_delivery_report.py
new file mode 100755
index 00000000..e09560cf
--- /dev/null
+++ b/examples/ad_manager/v202202/report_service/run_delivery_report.py
@@ -0,0 +1,88 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Runs a report similar to the "Orders report" on the Ad Manager website.
+
+Includes additional attributes and can filter to include just one order.
+"""
+
+from datetime import datetime
+from datetime import timedelta
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+from googleads import errors
+
+ORDER_ID = 'INSERT_ORDER_ID_HERE'
+
+
+def main(client, order_id):
+ # Create statement object to filter for an order.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('ORDER_ID = :id')
+ .WithBindVariable('id', int(order_id))
+ .Limit(None) # No limit or offset for reports
+ .Offset(None))
+
+ # Set the start and end dates of the report to run (past 8 days).
+ end_date = datetime.now().date()
+ start_date = end_date - timedelta(days=8)
+
+ # Create report job.
+ report_job = {
+ 'reportQuery': {
+ 'dimensions': ['ORDER_ID', 'ORDER_NAME'],
+ 'dimensionAttributes': ['ORDER_TRAFFICKER', 'ORDER_START_DATE_TIME',
+ 'ORDER_END_DATE_TIME'],
+ 'statement': statement.ToStatement(),
+ 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS',
+ 'AD_SERVER_CTR', 'AD_SERVER_CPM_AND_CPC_REVENUE',
+ 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'],
+ 'dateRangeType': 'CUSTOM_DATE',
+ 'startDate': start_date,
+ 'endDate': end_date
+ }
+ }
+
+ # Initialize a DataDownloader.
+ report_downloader = client.GetDataDownloader(version='v202202')
+
+ try:
+ # Run the report and wait for it to finish.
+ report_job_id = report_downloader.WaitForReport(report_job)
+ except errors.AdManagerReportError as e:
+ print('Failed to generate report. Error was: %s' % e)
+
+ # Change to your preferred export format.
+ export_format = 'CSV_DUMP'
+
+ report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
+
+ # Download report data.
+ report_downloader.DownloadReportToFile(
+ report_job_id, export_format, report_file)
+
+ report_file.close()
+
+ # Display results.
+ print('Report job with id "%s" downloaded to:\n%s' % (
+ report_job_id, report_file.name))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ORDER_ID)
diff --git a/examples/ad_manager/v202202/report_service/run_inventory_report.py b/examples/ad_manager/v202202/report_service/run_inventory_report.py
new file mode 100755
index 00000000..25fd0eb2
--- /dev/null
+++ b/examples/ad_manager/v202202/report_service/run_inventory_report.py
@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example runs a typical daily inventory report."""
+
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+from googleads import errors
+
+
+def main(client):
+ # Initialize a DataDownloader.
+ report_downloader = client.GetDataDownloader(version='v202202')
+
+ # Create report job.
+ report_job = {
+ 'reportQuery': {
+ 'dimensions': ['DATE', 'AD_UNIT_NAME'],
+ 'adUnitView': 'HIERARCHICAL',
+ 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS',
+ 'ADSENSE_LINE_ITEM_LEVEL_IMPRESSIONS',
+ 'ADSENSE_LINE_ITEM_LEVEL_CLICKS',
+ 'TOTAL_LINE_ITEM_LEVEL_IMPRESSIONS',
+ 'TOTAL_LINE_ITEM_LEVEL_CPM_AND_CPC_REVENUE'],
+ 'dateRangeType': 'LAST_WEEK'
+ }
+ }
+
+ try:
+ # Run the report and wait for it to finish.
+ report_job_id = report_downloader.WaitForReport(report_job)
+ except errors.AdManagerReportError as e:
+ print('Failed to generate report. Error was: %s' % e)
+
+ # Change to your preferred export format.
+ export_format = 'CSV_DUMP'
+
+ report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
+
+ # Download report data.
+ report_downloader.DownloadReportToFile(
+ report_job_id, export_format, report_file)
+
+ report_file.close()
+
+ # Display results.
+ print('Report job with id "%s" downloaded to:\n%s' % (
+ report_job_id, report_file.name))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/report_service/run_reach_report.py b/examples/ad_manager/v202202/report_service/run_reach_report.py
new file mode 100755
index 00000000..02fbfc3f
--- /dev/null
+++ b/examples/ad_manager/v202202/report_service/run_reach_report.py
@@ -0,0 +1,65 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example runs a reach report."""
+
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+from googleads import errors
+
+
+def main(client):
+ # Initialize a DataDownloader.
+ report_downloader = client.GetDataDownloader(version='v202202')
+
+ # Create report job.
+ report_job = {
+ 'reportQuery': {
+ 'dimensions': ['COUNTRY_NAME', 'LINE_ITEM_ID', 'LINE_ITEM_NAME'],
+ 'columns': ['UNIQUE_REACH_FREQUENCY', 'UNIQUE_REACH_IMPRESSIONS',
+ 'UNIQUE_REACH'],
+ 'dateRangeType': 'REACH_LIFETIME'
+ }
+ }
+
+ try:
+ # Run the report and wait for it to finish.
+ report_job_id = report_downloader.WaitForReport(report_job)
+ except errors.AdManagerReportError as e:
+ print('Failed to generate report. Error was: %s' % e)
+
+ # Change to your preferred export format.
+ export_format = 'CSV_DUMP'
+
+ report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
+
+ # Download report data.
+ report_downloader.DownloadReportToFile(
+ report_job_id, export_format, report_file)
+
+ report_file.close()
+
+ # Display results.
+ print('Report job with id "%s" downloaded to:\n%s' % (
+ report_job_id, report_file.name))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/report_service/run_reach_report_with_ad_unit_dimensions.py b/examples/ad_manager/v202202/report_service/run_reach_report_with_ad_unit_dimensions.py
new file mode 100755
index 00000000..84585602
--- /dev/null
+++ b/examples/ad_manager/v202202/report_service/run_reach_report_with_ad_unit_dimensions.py
@@ -0,0 +1,69 @@
+#!/usr/bin/env python
+#
+# Copyright 2021 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example runs a reach report."""
+
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+from googleads import errors
+
+
+def main(client):
+ # Initialize a DataDownloader.
+ report_downloader = client.GetDataDownloader(version='v202202')
+
+ # Create report job.
+ report_job = {
+ 'reportQuery': {
+ # For Reach reports with AD_UNIT_ID or AD_UNIT_NAME in the dimensions
+ # list, adUnitView must be set to 'FLAT' or 'HIERARCHICAL'.
+ 'adUnitView': 'FLAT',
+ 'dimensions': ['MONTH_AND_YEAR', 'COUNTRY_NAME', 'AD_UNIT_ID',
+ 'AD_UNIT_NAME'],
+ 'columns': ['UNIQUE_REACH_FREQUENCY', 'UNIQUE_REACH_IMPRESSIONS',
+ 'UNIQUE_REACH'],
+ 'dateRangeType': 'LAST_MONTH'
+ }
+ }
+
+ try:
+ # Run the report and wait for it to finish.
+ report_job_id = report_downloader.WaitForReport(report_job)
+ except errors.AdManagerReportError as e:
+ print('Failed to generate report. Error was: %s' % e)
+
+ # Change to your preferred export format.
+ export_format = 'CSV_DUMP'
+
+ report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
+
+ # Download report data.
+ report_downloader.DownloadReportToFile(
+ report_job_id, export_format, report_file)
+
+ report_file.close()
+
+ # Display results.
+ print('Report job with id "%s" downloaded to:\n%s' % (
+ report_job_id, report_file.name))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/report_service/run_report_and_create_match_table.py b/examples/ad_manager/v202202/report_service/run_report_and_create_match_table.py
new file mode 100755
index 00000000..9210795c
--- /dev/null
+++ b/examples/ad_manager/v202202/report_service/run_report_and_create_match_table.py
@@ -0,0 +1,88 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Runs a report for LineItems with additional data from a PQL table.
+
+Fetches a basic report over a network's LineItems and then adds some
+extra columns which might be useful for future analysis, such as
+LineItemType, from the PQL Line_Item table, creating a match table.
+"""
+
+from datetime import date
+from datetime import timedelta
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+from googleads import errors
+
+try:
+ import pandas
+except ImportError:
+ raise ImportError('This example requires the pandas library to be installed.')
+
+
+def main(client):
+ # Set the start and end dates of the report to run (past 8 days).
+ end_date = date.today()
+ start_date = end_date - timedelta(days=8)
+
+ # Create report job.
+ report_job = {
+ 'reportQuery': {
+ 'dimensions': ['LINE_ITEM_ID', 'LINE_ITEM_NAME'],
+ 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS',
+ 'AD_SERVER_CTR', 'AD_SERVER_CPM_AND_CPC_REVENUE',
+ 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'],
+ 'dateRangeType': 'CUSTOM_DATE',
+ 'startDate': start_date,
+ 'endDate': end_date
+ }
+ }
+
+ # Initialize a DataDownloader.
+ report_downloader = client.GetDataDownloader(version='v202202')
+
+ try:
+ # Run the report and wait for it to finish.
+ report_job_id = report_downloader.WaitForReport(report_job)
+ except errors.AdManagerReportError as e:
+ print('Failed to generate report. Error was: %s' % e)
+
+ with tempfile.NamedTemporaryFile(
+ suffix='.csv.gz', mode='wb', delete=False) as report_file:
+ # Download report data.
+ report_downloader.DownloadReportToFile(
+ report_job_id, 'CSV_DUMP', report_file)
+
+ # Create a PQL query to fetch the line item data
+ line_items_pql_query = ('SELECT Id, LineItemType, Status FROM LineItem')
+
+ # Download the response from PQL select statement
+ line_items = report_downloader.DownloadPqlResultToList(line_items_pql_query)
+
+ # Use pandas to join the two csv files into a match table
+ report = pandas.read_csv(report_file.name)
+ line_items = pandas.DataFrame(data=line_items[1:], columns=line_items[0])
+ merged_result = pandas.merge(report, line_items,
+ left_on='Dimension.LINE_ITEM_ID', right_on='id')
+ merged_result.to_csv('~/complete_line_items_report.csv', index=False)
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/report_service/run_report_with_custom_fields.py b/examples/ad_manager/v202202/report_service/run_report_with_custom_fields.py
new file mode 100755
index 00000000..2416c0c8
--- /dev/null
+++ b/examples/ad_manager/v202202/report_service/run_report_with_custom_fields.py
@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Runs a report with custom fields found in the line items of an order."""
+
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+from googleads import errors
+
+CUSTOM_FIELD_ID = 'INSERT_CUSTOM_FIELD_ID'
+CUSTOM_DIMENSION_KEY_ID = 'INSERT_CUSTOM_DIMENSION_KEY_ID'
+
+
+def main(client, custom_field_id, custom_dimension_key_id):
+ # Initialize a DataDownloader.
+ report_downloader = client.GetDataDownloader(version='v202202')
+
+ # Create report job.
+ report_job = {
+ 'reportQuery': {
+ 'dimensions': ['CUSTOM_DIMENSION', 'LINE_ITEM_ID', 'LINE_ITEM_NAME'],
+ 'columns': ['AD_SERVER_IMPRESSIONS'],
+ 'dateRangeType': 'LAST_MONTH',
+ 'customFieldIds': [custom_field_id],
+ 'customDimensionKeyIds': [custom_dimension_key_id]
+ }
+ }
+
+ try:
+ # Run the report and wait for it to finish.
+ report_job_id = report_downloader.WaitForReport(report_job)
+ except errors.AdManagerReportError as e:
+ print('Failed to generate report. Error was: %s' % e)
+
+ # Change to your preferred export format.
+ export_format = 'CSV_DUMP'
+
+ report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
+
+ # Download report data.
+ report_downloader.DownloadReportToFile(
+ report_job_id, export_format, report_file)
+
+ report_file.close()
+
+ # Display results.
+ print('Report job with id "%s" downloaded to:\n%s' % (
+ report_job_id, report_file.name))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CUSTOM_FIELD_ID, CUSTOM_DIMENSION_KEY_ID)
diff --git a/examples/ad_manager/v202202/report_service/run_sales_report.py b/examples/ad_manager/v202202/report_service/run_sales_report.py
new file mode 100755
index 00000000..c601f7c3
--- /dev/null
+++ b/examples/ad_manager/v202202/report_service/run_sales_report.py
@@ -0,0 +1,64 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Runs a report equal to the 'Sales by salespersons report'."""
+
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+from googleads import errors
+
+
+def main(client):
+ # Initialize a DataDownloader.
+ report_downloader = client.GetDataDownloader(version='v202202')
+
+ # Create report job.
+ report_job = {
+ 'reportQuery': {
+ 'dimensions': ['SALESPERSON_ID', 'SALESPERSON_NAME'],
+ 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CPM_AND_CPC_REVENUE',
+ 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'],
+ 'dateRangeType': 'LAST_MONTH'
+ }
+ }
+
+ try:
+ # Run the report and wait for it to finish.
+ report_job_id = report_downloader.WaitForReport(report_job)
+ except errors.AdManagerReportError as e:
+ print('Failed to generate report. Error was: %s' % e)
+
+ # Change to your preferred export format.
+ export_format = 'CSV_DUMP'
+
+ report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
+
+ # Download report data.
+ report_downloader.DownloadReportToFile(
+ report_job_id, export_format, report_file)
+
+ report_file.close()
+
+ # Display results.
+ print('Report job with id "%s" downloaded to:\n%s' % (
+ report_job_id, report_file.name))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/report_service/run_saved_query.py b/examples/ad_manager/v202202/report_service/run_saved_query.py
new file mode 100755
index 00000000..66a8d4ce
--- /dev/null
+++ b/examples/ad_manager/v202202/report_service/run_saved_query.py
@@ -0,0 +1,80 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example runs a report from a saved query.
+"""
+
+# Import appropriate modules from the client library.
+import tempfile
+
+from googleads import ad_manager
+from googleads import errors
+
+SAVED_QUERY_ID = 'INSERT_SAVED_QUERY_ID_HERE'
+
+
+def main(client, saved_query_id):
+ # Initialize appropriate service.
+ report_service = client.GetService('ReportService', version='v202202')
+
+ # Initialize a DataDownloader.
+ report_downloader = client.GetDataDownloader(version='v202202')
+
+ # Create statement object to filter for an order.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('id = :id')
+ .WithBindVariable('id', int(saved_query_id))
+ .Limit(1))
+
+ response = report_service.getSavedQueriesByStatement(
+ statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ saved_query = response['results'][0]
+
+ if saved_query['isCompatibleWithApiVersion']:
+ report_job = {}
+
+ # Set report query and optionally modify it.
+ report_job['reportQuery'] = saved_query['reportQuery']
+
+ try:
+ # Run the report and wait for it to finish.
+ report_job_id = report_downloader.WaitForReport(report_job)
+ except errors.AdManagerReportError as e:
+ print('Failed to generate report. Error was: %s' % e)
+ # Change to your preferred export format.
+ export_format = 'CSV_DUMP'
+
+ report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
+
+ # Download report data.
+ report_downloader.DownloadReportToFile(
+ report_job_id, export_format, report_file)
+
+ report_file.close()
+
+ # Display results.
+ print('Report job with id "%s" downloaded to:\n%s' % (
+ report_job_id, report_file.name))
+ else:
+ print('The query specified is not compatible with the API version.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, SAVED_QUERY_ID)
diff --git a/examples/ad_manager/v202202/site_service/create_sites.py b/examples/ad_manager/v202202/site_service/create_sites.py
new file mode 100755
index 00000000..15093841
--- /dev/null
+++ b/examples/ad_manager/v202202/site_service/create_sites.py
@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+#
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example creates a Site for Multiple Customer Management."""
+
+# Import appropriate modules from the client library.
+import sys
+from googleads import ad_manager
+
+# Set the URL and child network code for the Site.
+URL = 'INSERT_URL_HERE'
+CHILD_NETWORK_CODE = 'INSERT_CHILD_NETWORK_CODE_HERE'
+
+
+def main(client, url, child_network_code):
+ # Initialize appropriate services.
+ network_service = client.GetService('NetworkService', version='v202202')
+ site_service = client.GetService('SiteService', version='v202202')
+
+ # Check that the child network code is approved for MANAGE_INVENTORY by this
+ # network.
+ current_network = network_service.getCurrentNetwork()
+ child_network = None
+ for child in current_network['childPublishers']:
+ if child['childNetworkCode'] == child_network_code:
+ child_network = child
+
+ if child_network is None:
+ print(('Child network %s not found on the current network (%s). Cannot '
+ 'create site.') % (child_network_code,
+ current_network['networkCode']))
+ sys.exit(1)
+
+ if child_network['approvedDelegationType'] != 'MANAGE_INVENTORY':
+ print(('Child network %s has not approved for the current network (%s) '
+ 'to manage its inventory. Cannot create site.') % (
+ child_network_code, current_network['networkCode']))
+ sys.exit(1)
+
+ # Create site object.
+ site = {'url': url, 'childNetworkCode': child_network_code}
+
+ # Create the site on the server.
+ created_sites = site_service.createSites([site])
+
+ # Display results.
+ for site in created_sites:
+ print('Site with id %d and URL "%s" was created for child network %s.' % (
+ site['id'], site['url'], site['childNetworkCode']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, URL, CHILD_NETWORK_CODE)
diff --git a/examples/ad_manager/v202202/site_service/get_all_sites.py b/examples/ad_manager/v202202/site_service/get_all_sites.py
new file mode 100755
index 00000000..6bd3a073
--- /dev/null
+++ b/examples/ad_manager/v202202/site_service/get_all_sites.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+#
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all Sites."""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ site_service = client.GetService('SiteService', version='v202202')
+
+ # Create a statement to select Sites.
+ statement = ad_manager.StatementBuilder(version='v202202')
+
+ # Retrieve a small number of sites at a time, paging through until all sites
+ # have been retrieved.
+ while True:
+ response = site_service.getSitesByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for site in response['results']:
+ # Print out some information for each site.
+ print('Site with Id %d and URL "%s" was found.' %
+ (site['id'], site['url']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/site_service/get_sites_requiring_approval.py b/examples/ad_manager/v202202/site_service/get_sites_requiring_approval.py
new file mode 100755
index 00000000..e865f0ec
--- /dev/null
+++ b/examples/ad_manager/v202202/site_service/get_sites_requiring_approval.py
@@ -0,0 +1,50 @@
+#!/usr/bin/env python
+#
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets Sites under MCM requiring review."""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ site_service = client.GetService('SiteService', version='v202202')
+
+ # Create a statement to select Sites needing approval.
+ statement = ad_manager.StatementBuilder(version='v202202').Where(
+ "approvalStatus = 'REQUIRES_REVIEW'")
+
+ # Retrieve a small number of sites at a time, paging through until all sites
+ # have been retrieved.
+ while True:
+ response = site_service.getSitesByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for site in response['results']:
+ # Print out some information for each site.
+ print('Site with Id %d and URL "%s" was found.' %
+ (site['id'], site['url']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/site_service/submit_sites_for_approval.py b/examples/ad_manager/v202202/site_service/submit_sites_for_approval.py
new file mode 100755
index 00000000..0d0c5a9f
--- /dev/null
+++ b/examples/ad_manager/v202202/site_service/submit_sites_for_approval.py
@@ -0,0 +1,44 @@
+#!/usr/bin/env python
+#
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example submits a Site for approval."""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the id of the site to submit for approval.
+SITE_ID = 'INSERT_SITE_ID_HERE'
+
+
+def main(client):
+ # Initialize appropriate service.
+ site_service = client.GetService('SiteService', version='v202202')
+
+ # Create a statement to select Site.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('id = :id')
+ .WithBindVariable('id', SITE_ID))
+
+ response = site_service.performSiteAction(
+ {'xsi_type': 'SubmitSiteForApproval'}, statement.ToStatement())
+
+ print('\nNumber of sites changed: %s' % response['numChanges'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/suggested_ad_unit_service/__init__.py b/examples/ad_manager/v202202/suggested_ad_unit_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202202/suggested_ad_unit_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202202/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/ad_manager/v202202/suggested_ad_unit_service/approve_all_suggested_ad_units.py
new file mode 100755
index 00000000..cde42642
--- /dev/null
+++ b/examples/ad_manager/v202202/suggested_ad_unit_service/approve_all_suggested_ad_units.py
@@ -0,0 +1,70 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example approves all suggested ad units with 50 or more requests.
+
+This feature is only available to Ad Manager 360 solution networks.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+THRESHOLD_NUMBER_OF_REQUESTS = '50'
+
+
+def main(client):
+ # Initialize appropriate service.
+ suggested_ad_unit_service = client.GetService(
+ 'SuggestedAdUnitService', version='v202202')
+
+ # Create a filter statement.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('numRequests > :numRequests')
+ .WithBindVariable('numRequests', THRESHOLD_NUMBER_OF_REQUESTS))
+ num_approved_suggested_ad_units = 0
+
+ # Get suggested ad units by statement.
+ while True:
+ response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ # Print suggested ad units that will be approved.
+ for suggested_ad_unit in response['results']:
+ print('Suggested ad unit with id "%s", and number of requests "%s"'
+ ' will be approved.' % (suggested_ad_unit['id'],
+ suggested_ad_unit['numRequests']))
+
+ # Approve suggested ad units.
+ result = suggested_ad_unit_service.performSuggestedAdUnitAction(
+ {'xsi_type': 'ApproveSuggestedAdUnits'},
+ statement.ToStatement())
+ if result and int(result['numChanges']) > 0:
+ num_approved_suggested_ad_units += int(result['numChanges'])
+ else:
+ break
+
+ if num_approved_suggested_ad_units > 0:
+ print('Number of suggested ad units approved: %s' %
+ num_approved_suggested_ad_units)
+ else:
+ print('No suggested ad units were approved.')
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
+
diff --git a/examples/ad_manager/v202202/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/ad_manager/v202202/suggested_ad_unit_service/get_all_suggested_ad_units.py
new file mode 100755
index 00000000..88519bf4
--- /dev/null
+++ b/examples/ad_manager/v202202/suggested_ad_unit_service/get_all_suggested_ad_units.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all suggested ad units.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ suggested_ad_unit_service = client.GetService(
+ 'SuggestedAdUnitService', version='v202202')
+
+ # Create a statement to select suggested ad units.
+ statement = ad_manager.StatementBuilder(version='v202202')
+
+ # Retrieve a small amount of suggested ad units at a time, paging
+ # through until all suggested ad units have been retrieved.
+ while True:
+ response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for suggested_ad_unit in response['results']:
+ # Print out some information for each suggested ad unit.
+ print(
+ 'Suggested ad unit with ID "%s" and num requests "%d" was found.\n'
+ % (suggested_ad_unit['id'], suggested_ad_unit['numRequests']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/ad_manager/v202202/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py
new file mode 100755
index 00000000..03fb97d1
--- /dev/null
+++ b/examples/ad_manager/v202202/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all highly requested suggested ad units.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+NUM_REQUESTS = 'INSERT_NUM_REQUESTS_HERE'
+
+
+def main(client, num_requests):
+ # Initialize appropriate service.
+ suggested_ad_unit_service = client.GetService(
+ 'SuggestedAdUnitService', version='v202202')
+ # Create a statement to select suggested ad units.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('numRequests >= :numRequests')
+ .WithBindVariable('numRequests', int(num_requests)))
+
+ # Retrieve a small amount of suggested ad units at a time, paging
+ # through until all suggested ad units have been retrieved.
+ while True:
+ response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for suggested_ad_unit in response['results']:
+ # Print out some information for each suggested ad unit.
+ print(
+ 'Suggested ad unit with ID "%s" and num requests "%d" was found.\n'
+ % (suggested_ad_unit['id'], suggested_ad_unit['numRequests']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, NUM_REQUESTS)
diff --git a/examples/ad_manager/v202202/targeting_preset_service/__init__.py b/examples/ad_manager/v202202/targeting_preset_service/__init__.py
new file mode 100755
index 00000000..6d126cce
--- /dev/null
+++ b/examples/ad_manager/v202202/targeting_preset_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2019 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202202/targeting_preset_service/get_all_targeting_presets.py b/examples/ad_manager/v202202/targeting_preset_service/get_all_targeting_presets.py
new file mode 100755
index 00000000..0a9cf814
--- /dev/null
+++ b/examples/ad_manager/v202202/targeting_preset_service/get_all_targeting_presets.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2019 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all targeting presets.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ targeting_preset_service = client.GetService(
+ 'TargetingPresetService', version='v202202')
+
+ # Create a statement to select suggested ad units.
+ statement = ad_manager.StatementBuilder(version='v202202')
+
+ # Retrieve a small number of targeting presets at a time, paging
+ # through until all targeting presets have been retrieved.
+ while True:
+ response = targeting_preset_service.getTargetingPresetsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for targeting_preset in response['results']:
+ # Print out some information for each targeting preset.
+ print(
+ 'Targeting preset with ID "%d" and name "%s" was found.\n'
+ % (targeting_preset['id'], targeting_preset['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/team_service/__init__.py b/examples/ad_manager/v202202/team_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202202/team_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202202/team_service/create_teams.py b/examples/ad_manager/v202202/team_service/create_teams.py
new file mode 100755
index 00000000..84e7c0d2
--- /dev/null
+++ b/examples/ad_manager/v202202/team_service/create_teams.py
@@ -0,0 +1,60 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example creates new teams.
+
+To determine which teams exist, run get_all_teams.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+"""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ team_service = client.GetService('TeamService', version='v202202')
+
+ # Create team objects.
+ teams = []
+ for _ in range(5):
+ team = {
+ 'name': 'Team %s' % uuid.uuid4(),
+ 'hasAllCompanies': 'false',
+ 'hasAllInventory': 'false',
+ 'teamAccessType': 'READ_WRITE'
+ }
+ teams.append(team)
+
+ # Add Teams.
+ teams = team_service.createTeams(teams)
+
+ # Display results.
+ for team in teams:
+ print('Team with ID "%s" and name "%s" was created.'
+ % (team['id'], team['name']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/team_service/get_all_teams.py b/examples/ad_manager/v202202/team_service/get_all_teams.py
new file mode 100755
index 00000000..458f6373
--- /dev/null
+++ b/examples/ad_manager/v202202/team_service/get_all_teams.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all teams.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ team_service = client.GetService('TeamService', version='v202202')
+
+ # Create a statement to select teams.
+ statement = ad_manager.StatementBuilder(version='v202202')
+
+ # Retrieve a small amount of teams at a time, paging
+ # through until all teams have been retrieved.
+ while True:
+ response = team_service.getTeamsByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for team in response['results']:
+ # Print out some information for each team.
+ print('Team with ID "%d" and name "%s" was found.\n' % (team['id'],
+ team['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/team_service/update_teams.py b/examples/ad_manager/v202202/team_service/update_teams.py
new file mode 100755
index 00000000..d00645dd
--- /dev/null
+++ b/examples/ad_manager/v202202/team_service/update_teams.py
@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example updates teams by changing its description.
+
+To determine which teams exist, run get_all_teams.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+TEAM_ID = 'INSERT_TEAM_ID_HERE'
+
+
+def main(client, team_id):
+ # Initialize appropriate service.
+ team_service = client.GetService('TeamService', version='v202202')
+
+ # Create a filter statement to select a single team by ID.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('id = :teamId')
+ .WithBindVariable('teamId', int(team_id)))
+
+ # Get teams by statement.
+ response = team_service.getTeamsByStatement(statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ updated_teams = []
+ # Update each local team object by changing its description.
+ for team in response['results']:
+ team['description'] = 'this team is great!'
+ updated_teams.append(team)
+
+ # Update teams on the server.
+ teams = team_service.updateTeams(updated_teams)
+
+ # Display results.
+ for team in teams:
+ print('Team with id "%s" and name "%s" was updated.'
+ % (team['id'], team['name']))
+ else:
+ print('No teams found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, TEAM_ID)
diff --git a/examples/ad_manager/v202202/user_service/__init__.py b/examples/ad_manager/v202202/user_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202202/user_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202202/user_service/create_users.py b/examples/ad_manager/v202202/user_service/create_users.py
new file mode 100755
index 00000000..ea80af61
--- /dev/null
+++ b/examples/ad_manager/v202202/user_service/create_users.py
@@ -0,0 +1,57 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new users.
+
+To determine which users exist, run get_all_users.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+NEW_USER_EMAIL_ADDRESS = 'INSERT_EMAIL_ADDRESS_HERE'
+NEW_USER_NAME = 'INSERT_NAME_HERE'
+
+
+def main(client, email, name):
+ # Initialize appropriate service.
+ user_service = client.GetService('UserService', version='v202202')
+
+ # Create user objects.
+ users = [
+ {
+ 'email': email,
+ 'name': name,
+ }
+ ]
+ for user in users:
+ # Set the system defined ID of the trafficker role.
+ # To determine what other roles exist, run get_all_roles.py.
+ user['roleId'] = '-7'
+
+ # Add users.
+ users = user_service.createUsers(users)
+
+ # Display results.
+ for user in users:
+ print('User with id "%s", email "%s", and role "%s" was created.'
+ % (user['id'], user['email'], user['roleName']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, NEW_USER_EMAIL_ADDRESS, NEW_USER_NAME)
diff --git a/examples/ad_manager/v202202/user_service/deactivate_users.py b/examples/ad_manager/v202202/user_service/deactivate_users.py
new file mode 100755
index 00000000..7a17027d
--- /dev/null
+++ b/examples/ad_manager/v202202/user_service/deactivate_users.py
@@ -0,0 +1,65 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example deactivates a user.
+
+Deactivated users can no longer make requests to the API. The user making the
+request cannot deactivate itself. To determine which users exist, run
+get_all_users.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+USER_ID = 'INSERT_USER_ID_TO_DEACTIVATE_HERE'
+
+
+def main(client, user_id):
+ # Initialize appropriate service.
+ user_service = client.GetService('UserService', version='v202202')
+
+ # Create query.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('id = :userId')
+ .WithBindVariable('userId', int(user_id)))
+
+ # Get users by statement.
+ response = user_service.getUsersByStatement(statement.ToStatement())
+ users = response['results'] if 'results' in response else []
+
+ for user in users:
+ print('User with id "%s", email "%s", and status "%s" will be '
+ 'deactivated.'
+ % (user['id'], user['email'],
+ {'true': 'ACTIVE', 'false': 'INACTIVE'}[user['isActive']]))
+ print('Number of users to be deactivated: %s' % len(users))
+
+ # Perform action.
+ result = user_service.performUserAction({'xsi_type': 'DeactivateUsers'},
+ statement.ToStatement())
+
+ # Display results.
+ if result and int(result['numChanges']) > 0:
+ print('Number of users deactivated: %s' % result['numChanges'])
+ else:
+ print('No users were deactivated.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, USER_ID)
diff --git a/examples/ad_manager/v202202/user_service/get_all_roles.py b/examples/ad_manager/v202202/user_service/get_all_roles.py
new file mode 100755
index 00000000..f92f8b77
--- /dev/null
+++ b/examples/ad_manager/v202202/user_service/get_all_roles.py
@@ -0,0 +1,40 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all roles.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ user_service = client.GetService('UserService', version='v202202')
+
+ roles = user_service.getAllRoles()
+
+ # Print out some information for each role.
+ for role in roles:
+ print('Role with id "%s" and name "%s" was found.' %
+ (role['id'], role['name']))
+
+ print('\nNumber of results found: %s' % len(roles))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/user_service/get_all_users.py b/examples/ad_manager/v202202/user_service/get_all_users.py
new file mode 100755
index 00000000..955c2ea0
--- /dev/null
+++ b/examples/ad_manager/v202202/user_service/get_all_users.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all users.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ user_service = client.GetService('UserService', version='v202202')
+
+ # Create a statement to select users.
+ statement = ad_manager.StatementBuilder(version='v202202')
+
+ # Retrieve a small amount of users at a time, paging
+ # through until all users have been retrieved.
+ while True:
+ response = user_service.getUsersByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for user in response['results']:
+ # Print out some information for each user.
+ print('User with ID "%d" and name "%s" was found.\n' % (user['id'],
+ user['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/user_service/get_current_user.py b/examples/ad_manager/v202202/user_service/get_current_user.py
new file mode 100755
index 00000000..3be4fb9a
--- /dev/null
+++ b/examples/ad_manager/v202202/user_service/get_current_user.py
@@ -0,0 +1,38 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets the current user."""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ user_service = client.GetService('UserService', version='v202202')
+
+ # Get current user.
+ user = user_service.getCurrentUser()
+
+ print('User with ID %d, name "%s", email "%s", and role "%s" '
+ 'is the current user.' % (
+ user.id, user.name, user.email, user.roleName))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/user_service/get_user_by_email_address.py b/examples/ad_manager/v202202/user_service/get_user_by_email_address.py
new file mode 100755
index 00000000..1e4739d8
--- /dev/null
+++ b/examples/ad_manager/v202202/user_service/get_user_by_email_address.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets users by email.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+EMAIL_ADDRESS = 'INSERT_EMAIL_ADDRESS_HERE'
+
+
+def main(client, email_address):
+ # Initialize appropriate service.
+ user_service = client.GetService('UserService', version='v202202')
+ # Create a statement to select users.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('email = :email')
+ .WithBindVariable('email', email_address))
+
+ # Retrieve a small amount of users at a time, paging
+ # through until all users have been retrieved.
+ while True:
+ response = user_service.getUsersByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for user in response['results']:
+ # Print out some information for each user.
+ print('User with ID "%d" and name "%s" was found.\n' % (user['id'],
+ user['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, EMAIL_ADDRESS)
diff --git a/examples/ad_manager/v202202/user_service/update_users.py b/examples/ad_manager/v202202/user_service/update_users.py
new file mode 100755
index 00000000..9df04db0
--- /dev/null
+++ b/examples/ad_manager/v202202/user_service/update_users.py
@@ -0,0 +1,58 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates a user by adding " Sr." to the end of their name.
+
+To determine which users exist, run get_all_users.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+USER_ID = 'INSERT_USER_ID_TO_UPDATE_HERE'
+
+
+def main(client, user_id):
+ # Initialize appropriate service.
+ user_service = client.GetService('UserService', version='v202202')
+
+ # Create query.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('id = :userId')
+ .WithBindVariable('userId', int(user_id)))
+
+ # Get users by statement.
+ response = user_service.getUsersByStatement(statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ users = response['results']
+ for user in users:
+ user['name'] += ' Sr.'
+
+ # Update users on server.
+ users = user_service.updateUsers(users)
+ for user in users:
+ print('User with id "%s" and name "%s" was updated.'
+ % (user['id'], user['name']))
+ else:
+ print('No users found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, USER_ID)
diff --git a/examples/ad_manager/v202202/user_team_association_service/__init__.py b/examples/ad_manager/v202202/user_team_association_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202202/user_team_association_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202202/user_team_association_service/create_user_team_associations.py b/examples/ad_manager/v202202/user_team_association_service/create_user_team_associations.py
new file mode 100755
index 00000000..36f4788b
--- /dev/null
+++ b/examples/ad_manager/v202202/user_team_association_service/create_user_team_associations.py
@@ -0,0 +1,67 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example adds a user to a team by creating an association between them.
+
+To determine which teams exists, run get_all_teams.py. To determine which
+users exist, run get_all_users.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+TEAM_ID = 'INSERT_TEAM_ID_HERE'
+USER_IDS = ['INSERT_USER_IDS_TO_ASSOCIATE_TO_TEAM_HERE']
+
+
+def main(client, team_id, user_ids):
+ # Initialize appropriate service.
+ user_team_association_service = client.GetService(
+ 'UserTeamAssociationService', version='v202202')
+
+ user_team_associations = []
+ for user_id in user_ids:
+ user_team_associations.append(
+ {
+ 'teamId': team_id,
+ 'userId': user_id
+ })
+
+ # Create the user team association on the server.
+ user_team_associations = (
+ user_team_association_service.createUserTeamAssociations(
+ user_team_associations))
+
+ # Display results.
+ if user_team_associations:
+ for user_team_association in user_team_associations:
+ print('A user team association between user with ID "%s" and team with'
+ ' ID "%s"was created.' % (user_team_association['userId'],
+ user_team_association['teamId']))
+ else:
+ print('No user team associations created.')
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, TEAM_ID, USER_IDS)
diff --git a/examples/ad_manager/v202202/user_team_association_service/delete_user_team_associations.py b/examples/ad_manager/v202202/user_team_association_service/delete_user_team_associations.py
new file mode 100755
index 00000000..668ec58f
--- /dev/null
+++ b/examples/ad_manager/v202202/user_team_association_service/delete_user_team_associations.py
@@ -0,0 +1,77 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example removes the user from all its teams.
+
+To determine which users exist, run get_all_users.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+USER_ID = 'INSERT_USER_ID_HERE'
+
+
+def main(client, user_id):
+ # Initialize appropriate service.
+ user_team_association_service = client.GetService(
+ 'UserTeamAssociationService', version='v202202')
+
+ # Create filter text to select user team associations by the user ID.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('userId = :userId')
+ .WithBindVariable('userId', int(user_id)))
+
+ # Get user team associations by statement.
+ response = user_team_association_service.getUserTeamAssociationsByStatement(
+ statement.ToStatement())
+ user_team_associations = response['results'] if 'results' in response else []
+
+ for user_team_association in user_team_associations:
+ print('User team association between user with ID "%s" and team with '
+ 'ID "%s" will be deleted.' % (user_team_association['userId'],
+ user_team_association['teamId']))
+ print('Number of teams that the user will be removed from: %s' %
+ len(user_team_associations))
+
+ # Action doesn't require limit/offset
+ statement.limit = None
+ statement.offset = None
+
+ # Perform action.
+ result = user_team_association_service.performUserTeamAssociationAction(
+ {'xsi_type': 'DeleteUserTeamAssociations'},
+ statement.ToStatement())
+
+ # Display results.
+ if result and int(result['numChanges']) > 0:
+ print('Number of teams that the user was removed from: %s'
+ % result['numChanges'])
+ else:
+ print('No user team associations were deleted.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, USER_ID)
diff --git a/examples/ad_manager/v202202/user_team_association_service/get_all_user_team_associations.py b/examples/ad_manager/v202202/user_team_association_service/get_all_user_team_associations.py
new file mode 100755
index 00000000..3614a0a6
--- /dev/null
+++ b/examples/ad_manager/v202202/user_team_association_service/get_all_user_team_associations.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all user team associations.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ user_team_association_service = client.GetService(
+ 'UserTeamAssociationService', version='v202202')
+
+ # Create a statement to select user team associations.
+ statement = ad_manager.StatementBuilder(version='v202202')
+
+ # Retrieve a small amount of user team associations at a time, paging
+ # through until all user team associations have been retrieved.
+ while True:
+ response = user_team_association_service.getUserTeamAssociationsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for user_team_association in response['results']:
+ # Print out some information for each user team association.
+ print('User team association with team id "%d" and user id "%d" was '
+ 'found.\n' % (user_team_association['teamId'],
+ user_team_association['userId']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202202/user_team_association_service/get_user_team_associations_for_user.py b/examples/ad_manager/v202202/user_team_association_service/get_user_team_associations_for_user.py
new file mode 100755
index 00000000..ac84f634
--- /dev/null
+++ b/examples/ad_manager/v202202/user_team_association_service/get_user_team_associations_for_user.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all user team associations (i.e. teams) for a given user.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+USER_ID = 'INSERT_USER_ID_HERE'
+
+
+def main(client, user_id):
+ # Initialize appropriate service.
+ user_team_association_service = client.GetService(
+ 'UserTeamAssociationService', version='v202202')
+ # Create a statement to select user team associations.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('userId = :userId')
+ .WithBindVariable('userId', int(user_id)))
+
+ # Retrieve a small amount of user team associations at a time, paging
+ # through until all user team associations have been retrieved.
+ while True:
+ response = user_team_association_service.getUserTeamAssociationsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for user_team_association in response['results']:
+ # Print out some information for each user team association.
+ print('User team association with user ID "%d" and team ID "%d" was '
+ 'found.\n' % (user_team_association['userId'],
+ user_team_association['teamId']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, USER_ID)
diff --git a/examples/ad_manager/v202202/user_team_association_service/update_user_team_associations.py b/examples/ad_manager/v202202/user_team_association_service/update_user_team_associations.py
new file mode 100755
index 00000000..31266fe6
--- /dev/null
+++ b/examples/ad_manager/v202202/user_team_association_service/update_user_team_associations.py
@@ -0,0 +1,78 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example updates user team associations.
+
+It updates a user team association by setting the overridden access type to read
+only for all teams that the user belongs to. To determine which users exists,
+run get_all_users.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+USER_ID = 'INSERT_USER_ID_TO_UPDATE_HERE'
+
+
+def main(client, user_id):
+ # Initialize appropriate service.
+ user_team_association_service = client.GetService(
+ 'UserTeamAssociationService', version='v202202')
+
+ # Create filter text to select user team associations by the user ID.
+ statement = (ad_manager.StatementBuilder(version='v202202')
+ .Where('userId = :userId')
+ .WithBindVariable('userId', int(user_id)))
+
+ # Get user team associations by statement.
+ response = user_team_association_service.getUserTeamAssociationsByStatement(
+ statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ updated_user_team_associations = []
+ # Update each local user team association to read only access.
+ for user_team_association in response['results']:
+ user_team_association['overriddenTeamAccessType'] = 'READ_ONLY'
+ updated_user_team_associations.append(user_team_association)
+
+ # Update user team associations on the server.
+ user_team_associations = (
+ user_team_association_service.updateUserTeamAssociations(
+ updated_user_team_associations))
+
+ # Display results.
+ if user_team_associations:
+ for user_team_association in user_team_associations:
+ print('User team association between user with ID "%s" and team with'
+ ' ID "%s" was updated.' % (user_team_association['userId'],
+ user_team_association['teamId']))
+ else:
+ print('No user team associations were updated.')
+ else:
+ print('No user team associations found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, USER_ID)
diff --git a/examples/ad_manager/v202205/activity_group_service/__init__.py b/examples/ad_manager/v202205/activity_group_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202205/activity_group_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202205/activity_group_service/create_activity_groups.py b/examples/ad_manager/v202205/activity_group_service/create_activity_groups.py
new file mode 100755
index 00000000..f5e08b60
--- /dev/null
+++ b/examples/ad_manager/v202205/activity_group_service/create_activity_groups.py
@@ -0,0 +1,71 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new activity groups.
+
+To determine which activity groups exist, run get_all_activity_groups.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the advertiser company this activity group is associated with.
+ADVERTISER_COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
+
+
+def main(client, advertiser_company_id):
+ # Initialize appropriate service.
+ activity_group_service = client.GetService('ActivityGroupService',
+ version='v202205')
+
+ # Create a short-term activity group.
+ short_term_activity_group = {
+ 'name': 'Short-term activity group #%s' % uuid.uuid4(),
+ 'companyIds': [advertiser_company_id],
+ 'clicksLookback': '1',
+ 'impressionsLookback': '1'
+ }
+
+ # Create a long-term activity group.
+ long_term_activity_group = {
+ 'name': 'Long-term activity group #%s' % uuid.uuid4(),
+ 'companyIds': [advertiser_company_id],
+ 'clicksLookback': '30',
+ 'impressionsLookback': '30'
+ }
+
+ # Create the activity groups on the server.
+ activity_groups = activity_group_service.createActivityGroups([
+ short_term_activity_group, long_term_activity_group])
+
+ # Display results.
+ for activity_group in activity_groups:
+ print('Activity group with ID "%s" and name "%s" was created.'
+ % (activity_group['id'], activity_group['name']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ADVERTISER_COMPANY_ID)
diff --git a/examples/ad_manager/v202205/activity_group_service/get_active_activity_groups.py b/examples/ad_manager/v202205/activity_group_service/get_active_activity_groups.py
new file mode 100755
index 00000000..0705f70f
--- /dev/null
+++ b/examples/ad_manager/v202205/activity_group_service/get_active_activity_groups.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all active activity groups.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ activity_group_service = client.GetService(
+ 'ActivityGroupService', version='v202205')
+ # Create a statement to select activity groups.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('status = :status')
+ .WithBindVariable('status', 'ACTIVE'))
+
+ # Retrieve a small amount of activity groups at a time, paging
+ # through until all activity groups have been retrieved.
+ while True:
+ response = activity_group_service.getActivityGroupsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for activity_group in response['results']:
+ # Print out some information for each activity group.
+ print('Activity group with ID "%d" and name "%s" was found.\n' %
+ (activity_group['id'], activity_group['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/activity_group_service/get_all_activity_groups.py b/examples/ad_manager/v202205/activity_group_service/get_all_activity_groups.py
new file mode 100755
index 00000000..6a033e12
--- /dev/null
+++ b/examples/ad_manager/v202205/activity_group_service/get_all_activity_groups.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all activity groups.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ activity_group_service = client.GetService(
+ 'ActivityGroupService', version='v202205')
+
+ # Create a statement to select activity groups.
+ statement = ad_manager.StatementBuilder(version='v202205')
+
+ # Retrieve a small amount of activity groups at a time, paging
+ # through until all activity groups have been retrieved.
+ while True:
+ response = activity_group_service.getActivityGroupsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for activity_group in response['results']:
+ # Print out some information for each activity group.
+ print('Activity group with ID "%d" and name "%s" was found.\n' %
+ (activity_group['id'], activity_group['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/activity_group_service/update_activity_groups.py b/examples/ad_manager/v202205/activity_group_service/update_activity_groups.py
new file mode 100755
index 00000000..2683f535
--- /dev/null
+++ b/examples/ad_manager/v202205/activity_group_service/update_activity_groups.py
@@ -0,0 +1,70 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates activity groups.
+
+To determine which activity groups exist, run get_all_activity_groups.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the activity group and the company to update it with.
+ACTIVITY_GROUP_ID = 'INSERT_ACTIVITY_GROUP_ID_HERE'
+ADVERTISER_COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
+
+
+def main(client, activity_group_id, advertiser_company_id):
+ # Initialize appropriate service.
+ activity_group_service = client.GetService('ActivityGroupService',
+ version='v202205')
+
+ # Create statement object to select a single activity groups by ID.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('id = :activityGroupId')
+ .WithBindVariable('activityGroupId', int(activity_group_id))
+ .Limit(1))
+
+ # Get activity groups by statement.
+ response = activity_group_service.getActivityGroupsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ updated_activity_groups = []
+ for activity_group in response['results']:
+ activity_group['companyIds'].append(advertiser_company_id)
+ updated_activity_groups.append(activity_group)
+ # Update the activity groups on the server.
+ activity_groups = activity_group_service.updateActivityGroups(
+ updated_activity_groups)
+
+ for activity_group in activity_groups:
+ print(('Activity group with ID "%s" and name "%s" was updated.')
+ % (activity_group['id'], activity_group['name']))
+ else:
+ print('No activity groups found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ACTIVITY_GROUP_ID, ADVERTISER_COMPANY_ID)
diff --git a/examples/ad_manager/v202205/activity_service/__init__.py b/examples/ad_manager/v202205/activity_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202205/activity_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202205/activity_service/create_activities.py b/examples/ad_manager/v202205/activity_service/create_activities.py
new file mode 100755
index 00000000..f2eb54e5
--- /dev/null
+++ b/examples/ad_manager/v202205/activity_service/create_activities.py
@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new activities.
+
+To determine which activities groups exist, run get_all_activities.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the activity group this activity is associated with.
+ACTIVITY_GROUP_ID = 'INSERT_ACTIVITY_GROUP_ID_HERE'
+
+
+def main(client, activity_group_id):
+ # Initialize appropriate service.
+ activity_service = client.GetService('ActivityService', version='v202205')
+
+ # Create a daily visits activity.
+ daily_visits_activity = {
+ 'name': 'Activity #%s' % uuid.uuid4(),
+ 'activityGroupId': activity_group_id,
+ 'type': 'DAILY_VISITS'
+ }
+
+ # Create a custom activity.
+ custom_activity = {
+ 'name': 'Activity #%s' % uuid.uuid4(),
+ 'activityGroupId': activity_group_id,
+ 'type': 'CUSTOM'
+ }
+
+ # Create the activities on the server.
+ activities = activity_service.createActivities([
+ daily_visits_activity, custom_activity])
+
+ # Display results.
+ for activity in activities:
+ print('An activity with ID "%s", name "%s", and type "%s" was '
+ 'created.' % (activity['id'], activity['name'], activity['type']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ACTIVITY_GROUP_ID)
diff --git a/examples/ad_manager/v202205/activity_service/get_active_activities.py b/examples/ad_manager/v202205/activity_service/get_active_activities.py
new file mode 100755
index 00000000..2f02a758
--- /dev/null
+++ b/examples/ad_manager/v202205/activity_service/get_active_activities.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all active activities.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ activity_service = client.GetService('ActivityService', version='v202205')
+ # Create a statement to select activities.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('status = :status')
+ .WithBindVariable('status', 'ACTIVE'))
+
+ # Retrieve a small amount of activities at a time, paging
+ # through until all activities have been retrieved.
+ while True:
+ response = activity_service.getActivitiesByStatement(statement.ToStatement(
+ ))
+ if 'results' in response and len(response['results']):
+ for activity in response['results']:
+ # Print out some information for each activity.
+ print('Activity with ID "%d", name "%s", and type "%s" was found.\n' %
+ (activity['id'], activity['name'], activity['type']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/activity_service/get_all_activities.py b/examples/ad_manager/v202205/activity_service/get_all_activities.py
new file mode 100755
index 00000000..36135425
--- /dev/null
+++ b/examples/ad_manager/v202205/activity_service/get_all_activities.py
@@ -0,0 +1,50 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all activities.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ activity_service = client.GetService('ActivityService', version='v202205')
+
+ # Create a statement to select activities.
+ statement = ad_manager.StatementBuilder(version='v202205')
+
+ # Retrieve a small amount of activities at a time, paging
+ # through until all activities have been retrieved.
+ while True:
+ response = activity_service.getActivitiesByStatement(statement.ToStatement(
+ ))
+ if 'results' in response and len(response['results']):
+ for activity in response['results']:
+ # Print out some information for each activity.
+ print('Activity with ID "%d" and name "%s" was found.\n' %
+ (activity['id'], activity['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/activity_service/update_activities.py b/examples/ad_manager/v202205/activity_service/update_activities.py
new file mode 100755
index 00000000..f4a74f44
--- /dev/null
+++ b/examples/ad_manager/v202205/activity_service/update_activities.py
@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates activities.
+
+To determine which activities exist, run get_all_activities.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the activity to update.
+ACTIVITY_ID = 'INSERT_ACTIVITY_ID_HERE'
+
+
+def main(client, activity_id):
+ # Initialize appropriate service.
+ activity_service = client.GetService('ActivityService', version='v202205')
+
+ # Create statement object to select one activity by ID to update.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('id = :activityId')
+ .WithBindVariable('activityId', int(activity_id))
+ .Limit(1))
+
+ # Get activities by statement.
+ response = activity_service.getActivitiesByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ updated_activities = []
+ for activity in response['results']:
+ # Update the expected URL.
+ activity['expectedURL'] = 'https://google.com'
+ updated_activities.append(activity)
+ # Update the activity on the server.
+ activities = activity_service.updateActivities(updated_activities)
+
+ for updated_activity in activities:
+ print(('Activity with ID "%s" and name "%s" was updated.')
+ % (updated_activity['id'], updated_activity['name']))
+ else:
+ print('No activities found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ACTIVITY_ID)
diff --git a/examples/ad_manager/v202205/adjustment_service/create_forecast_adjustments.py b/examples/ad_manager/v202205/adjustment_service/create_forecast_adjustments.py
new file mode 100755
index 00000000..49d7faf0
--- /dev/null
+++ b/examples/ad_manager/v202205/adjustment_service/create_forecast_adjustments.py
@@ -0,0 +1,65 @@
+#!/usr/bin/env python
+#
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example creates a forecast adjustment for New Year's Day traffic."""
+
+import datetime
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+TRAFFIC_FORECAST_SEGMENT_ID = 'INSERT_TRAFFIC_FORECAST_SEGMENT_ID_HERE'
+
+
+def main(client, traffic_forecast_segment_id):
+ # Initialize the adjustment service.
+ adjustment_service = client.GetService('AdjustmentService', version='v202205')
+
+ # Create a new forecast adjustment for New Year's Day traffic.
+ this_new_years = datetime.date(datetime.date.today().year, 1, 1)
+ next_new_years = datetime.date(datetime.date.today().year + 1, 1, 1)
+
+ forecast = {
+ 'name': 'Forecast adjustment #%s' % uuid.uuid4(),
+ 'trafficForecastSegmentId': traffic_forecast_segment_id,
+ 'dateRange': {
+ 'startDate': next_new_years,
+ 'endDate': next_new_years
+ },
+ 'status': 'ACTIVE',
+ 'volumeType': 'HISTORICAL_BASIS_VOLUME',
+ 'historicalBasisVolumeSettings': {
+ 'useParentTrafficForecastSegmentTargeting': True,
+ 'historicalDateRange': {
+ 'startDate': this_new_years,
+ 'endDate': this_new_years
+ },
+ 'multiplierMilliPercent': 110000
+ }
+ }
+
+ forecasts = adjustment_service.createForecastAdjustments([forecast])
+
+ for forecast in forecasts:
+ print('Forecast adjustment with id %d and name "%s" was created.' % (
+ forecast['id'], forecast['name']
+ ))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, TRAFFIC_FORECAST_SEGMENT_ID)
diff --git a/examples/ad_manager/v202205/adjustment_service/create_traffic_forecast_segments.py b/examples/ad_manager/v202205/adjustment_service/create_traffic_forecast_segments.py
new file mode 100755
index 00000000..e5d96d95
--- /dev/null
+++ b/examples/ad_manager/v202205/adjustment_service/create_traffic_forecast_segments.py
@@ -0,0 +1,72 @@
+#!/usr/bin/env python
+#
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example creates a traffic forecast segment for all ad units in the U.S.
+"""
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize the adjustment service and the network service.
+ adjustment_service = client.GetService('AdjustmentService', version='v202205')
+ network_service = client.GetService('NetworkService', version='v202205')
+
+ # Get the root ad unit id to target the whole site.
+ current_network = network_service.getCurrentNetwork()
+ root_ad_unit_id = current_network['effectiveRootAdUnitId']
+
+ # Create inventory targeting.
+ inventory_targeting = {
+ 'targetedAdUnits': [{
+ 'includeDescendants': True,
+ 'adUnitId': root_ad_unit_id
+ }]
+ }
+
+ # Create targeting for United States traffic.
+ geo_targeting = {
+ 'targetedLocations': [{
+ 'id': 2840
+ }]
+ }
+
+ # Create traffic forecast segment object.
+ segment = {
+ 'name': 'Forecast segment #%s' % uuid.uuid4(),
+ 'targeting': {
+ 'inventoryTargeting': inventory_targeting,
+ 'geoTargeting': geo_targeting
+ }
+ }
+
+ # Create the traffic forecast segment on the server.
+ segments = adjustment_service.createTrafficForecastSegments([segment])
+
+ # Display the results.
+ for segment in segments:
+ print('Traffic forecast segment with id %d and %d forecast adjustments was '
+ 'created.' % (segment['id'],
+ segment['forecastAdjustmentCount']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/adjustment_service/get_all_forecast_adjustments.py b/examples/ad_manager/v202205/adjustment_service/get_all_forecast_adjustments.py
new file mode 100755
index 00000000..f2b0d001
--- /dev/null
+++ b/examples/ad_manager/v202205/adjustment_service/get_all_forecast_adjustments.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all forecast adjustments."""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize the adjustment service.
+ adjustment_service = client.GetService('AdjustmentService', version='v202205')
+
+ # Create a statement to get all forecast adjustments.
+ statement = ad_manager.StatementBuilder(version='v202205')
+
+ # Retrieve a small number of forecast adjustments at a time, paging
+ # through until all forecast adjustments have been retrieved.
+ while True:
+ response = adjustment_service.getForecastAdjustmentsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for adjustment in response['results']:
+ # Print out some information for each forecast adjustment.
+ print('Forecast adjustment with id %d and name "%s" belonging to '
+ 'forecast segment %d was found.' %
+ (adjustment['id'], adjustment['name'],
+ adjustment['trafficForecastSegmentId']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/adjustment_service/get_all_traffic_forecast_segments.py b/examples/ad_manager/v202205/adjustment_service/get_all_traffic_forecast_segments.py
new file mode 100755
index 00000000..6f9952e0
--- /dev/null
+++ b/examples/ad_manager/v202205/adjustment_service/get_all_traffic_forecast_segments.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+#
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all traffic forecast segments."""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize the adjustment service.
+ adjustment_service = client.GetService('AdjustmentService', version='v202205')
+
+ # Create a statement to get all traffic forecast segments.
+ statement = ad_manager.StatementBuilder(version='v202205')
+
+ # Retrieve a small number of segments at a time, paging through until all
+ # segments have been retrieved.
+ while True:
+ response = adjustment_service.getTrafficForecastSegmentsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for segment in response['results']:
+ # Print out some information for each traffic forecast segment.
+ print('Traffic forecast segment with id %d and name "%s" was found ' % (
+ segment['id'], segment['name'],
+ ))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py b/examples/ad_manager/v202205/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py
new file mode 100755
index 00000000..178666e2
--- /dev/null
+++ b/examples/ad_manager/v202205/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py
@@ -0,0 +1,57 @@
+#!/usr/bin/env python
+#
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all forecast adjustments for a traffic forecast segment."""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+TRAFFIC_FORECAST_SEGMENT_ID = 'INSERT_FORECAST_SEGMENT_ID_HERE'
+
+
+def main(client, traffic_forecast_segment_id):
+ # Initialize the adjustment service.
+ adjustment_service = client.GetService('AdjustmentService', version='v202205')
+
+ # Create a statement to get forecast adjustments for a given traffic forecast
+ # segment id.
+ statement = ad_manager.StatementBuilder(version='v202205').Where(
+ 'trafficForecastSegmentId = :segmentId').WithBindVariable(
+ 'segmentId', traffic_forecast_segment_id)
+
+ # Retrieve a small number of forecast adjustments at a time, paging
+ # through until all forecast adjustments have been retrieved.
+ while True:
+ response = adjustment_service.getForecastAdjustmentsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for adjustment in response['results']:
+ # Print out some information for each traffic adjustment.
+ print('Forecast adjustment with id %d and name "%s" belonging to '
+ 'forecast segment %d was found.' %
+ (adjustment['id'], adjustment['name'],
+ adjustment['trafficForecastSegmentId']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, int(TRAFFIC_FORECAST_SEGMENT_ID))
diff --git a/examples/ad_manager/v202205/adjustment_service/update_forecast_adjustments.py b/examples/ad_manager/v202205/adjustment_service/update_forecast_adjustments.py
new file mode 100755
index 00000000..b50b2957
--- /dev/null
+++ b/examples/ad_manager/v202205/adjustment_service/update_forecast_adjustments.py
@@ -0,0 +1,64 @@
+#!/usr/bin/env python
+#
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example updates a forecast adjustment's name."""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+ADJUSTMENT_ID = 'INSERT_ADJUSTMENT_ID_HERE'
+
+
+def main(client, adjustment_id):
+ # Initialize the adjustment service.
+ adjustment_service = client.GetService('AdjustmentService', version='v202205')
+
+ # Create a statement to select a single forecast adjustment by id.
+ statement = (
+ ad_manager.StatementBuilder(
+ version='v202205').Where('id = :id').WithBindVariable(
+ 'id', adjustment_id))
+
+ # Get the forecast adjustment.
+ response = adjustment_service.getForecastAdjustmentsByStatement(
+ statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ # Update each local forecast adjustment's name.
+ updated_adjustments = []
+ for adjustment in response['results']:
+ adjustment['name'] += ' (updated)'
+ updated_adjustments.append(adjustment)
+
+ # Update the forecast adjustment on the server.
+ adjustments = adjustment_service.updateForecastAdjustments(
+ updated_adjustments)
+
+ # Display the results.
+ if adjustments:
+ for adjustment in adjustments:
+ print('Forecast adjustment with id %d and name "%s" was updated' % (
+ adjustment['id'], adjustment['name']))
+ else:
+ print('No forecast adjustments were updated.')
+ else:
+ print('No forecast adjustments found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ADJUSTMENT_ID)
diff --git a/examples/ad_manager/v202205/audience_segment_service/__init__.py b/examples/ad_manager/v202205/audience_segment_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202205/audience_segment_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202205/audience_segment_service/create_audience_segments.py b/examples/ad_manager/v202205/audience_segment_service/create_audience_segments.py
new file mode 100755
index 00000000..fdaa687d
--- /dev/null
+++ b/examples/ad_manager/v202205/audience_segment_service/create_audience_segments.py
@@ -0,0 +1,96 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example creates a new rule based first party audience segment."""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the IDs of the custom criteria to be used in the segment rule.
+CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'
+CUSTOM_TARGETING_VALUE_ID = 'INSERT_CUSTOM_TARGETING_VALUE_ID_HERE'
+
+
+def main(client, custom_targeting_key_id, custom_targeting_value_id):
+ # Initialize appropriate services.
+ audience_segment_service = client.GetService(
+ 'AudienceSegmentService', version='v202205')
+ network_service = client.GetService('NetworkService', version='v202205')
+
+ # Get the root ad unit ID used to target the entire network.
+ root_ad_unit_id = (
+ network_service.getCurrentNetwork()['effectiveRootAdUnitId'])
+
+ # Create inventory targeting (pointed at root ad unit i.e. the whole network)
+ inventory_targeting = {
+ 'targetedAdUnits': [
+ {'adUnitId': root_ad_unit_id}
+ ]
+ }
+
+ # Create custom criteria.
+ custom_criteria = [
+ {
+ 'xsi_type': 'CustomCriteria',
+ 'keyId': custom_targeting_key_id,
+ 'valueIds': [custom_targeting_value_id],
+ 'operator': 'IS'
+ }
+ ]
+
+ # Create the custom criteria set.
+ top_custom_criteria_set = {
+ 'logicalOperator': 'AND',
+ 'children': custom_criteria
+ }
+
+ # Create the audience segment rule.
+ rule = {
+ 'inventoryRule': inventory_targeting,
+ 'customCriteriaRule': top_custom_criteria_set
+ }
+
+ # Create an audience segment.
+ audience_segment = [
+ {
+ 'xsi_type': 'RuleBasedFirstPartyAudienceSegment',
+ 'name': ('Sports enthusiasts audience segment %s' %
+ uuid.uuid4()),
+ 'description': 'Sports enthusiasts between the ages of 20 and 30',
+ 'pageViews': '6',
+ 'recencyDays': '6',
+ 'membershipExpirationDays': '88',
+ 'rule': rule
+ }
+ ]
+
+ audience_segments = (
+ audience_segment_service.createAudienceSegments(audience_segment))
+
+ for created_audience_segment in audience_segments:
+ print('An audience segment with ID "%s", name "%s", and type "%s" '
+ 'was created.' % (created_audience_segment['id'],
+ created_audience_segment['name'],
+ created_audience_segment['type']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CUSTOM_TARGETING_KEY_ID, CUSTOM_TARGETING_VALUE_ID)
diff --git a/examples/ad_manager/v202205/audience_segment_service/get_all_audience_segments.py b/examples/ad_manager/v202205/audience_segment_service/get_all_audience_segments.py
new file mode 100755
index 00000000..2e86bb89
--- /dev/null
+++ b/examples/ad_manager/v202205/audience_segment_service/get_all_audience_segments.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all audience segments.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ audience_segment_service = client.GetService(
+ 'AudienceSegmentService', version='v202205')
+
+ # Create a statement to select audience segments.
+ statement = ad_manager.StatementBuilder(version='v202205')
+
+ # Retrieve a small amount of audience segments at a time, paging
+ # through until all audience segments have been retrieved.
+ while True:
+ response = audience_segment_service.getAudienceSegmentsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for audience_segment in response['results']:
+ # Print out some information for each audience segment.
+ print('Audience segment with ID "%d", name "%s", and size "%d" was '
+ 'found.\n' % (audience_segment['id'], audience_segment['name'],
+ audience_segment['size']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/audience_segment_service/get_first_party_audience_segments.py b/examples/ad_manager/v202205/audience_segment_service/get_first_party_audience_segments.py
new file mode 100755
index 00000000..64c42a37
--- /dev/null
+++ b/examples/ad_manager/v202205/audience_segment_service/get_first_party_audience_segments.py
@@ -0,0 +1,53 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all first party audience segments.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ audience_segment_service = client.GetService(
+ 'AudienceSegmentService', version='v202205')
+ # Create a statement to select audience segments.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('type = :type')
+ .WithBindVariable('type', 'FIRST_PARTY'))
+
+ # Retrieve a small amount of audience segments at a time, paging
+ # through until all audience segments have been retrieved.
+ while True:
+ response = audience_segment_service.getAudienceSegmentsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for audience_segment in response['results']:
+ # Print out some information for each audience segment.
+ print('Audience segment with ID "%d", name "%s", and size "%d" was '
+ 'found.\n' % (audience_segment['id'], audience_segment['name'],
+ audience_segment['size']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/audience_segment_service/populate_first_party_audience_segments.py b/examples/ad_manager/v202205/audience_segment_service/populate_first_party_audience_segments.py
new file mode 100755
index 00000000..9621b62b
--- /dev/null
+++ b/examples/ad_manager/v202205/audience_segment_service/populate_first_party_audience_segments.py
@@ -0,0 +1,71 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example populates a specific first party audience segment.
+
+To determine which first party audience segments exist, run
+get_first_party_audience_segments.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+AUDIENCE_SEGMENT_ID = 'INSERT_AUDIENCE_SEGMENT_ID_HERE'
+
+
+def main(client, audience_segment_id):
+ # Initialize appropriate service.
+ audience_segment_service = client.GetService(
+ 'AudienceSegmentService', version='v202205')
+
+ # Create statement object to get the specified first party audience segment.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('Type = :type AND Id = :audience_segment_id')
+ .WithBindVariable('audience_segment_id',
+ int(audience_segment_id))
+ .WithBindVariable('type', 'FIRST_PARTY')
+ .Limit(1))
+
+ response = audience_segment_service.getAudienceSegmentsByStatement(
+ statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ segments = response['results']
+
+ for segment in segments:
+ print(
+ 'Audience segment with id "%s" and name "%s" will be populated.'
+ % (segment['id'], segment['name']))
+
+ action = {
+ 'xsi_type': 'PopulateAudienceSegments'
+ }
+
+ populated_audience_segments = (
+ audience_segment_service.performAudienceSegmentAction(
+ action, statement.ToStatement()))
+
+ print('%s audience segment populated' %
+ populated_audience_segments['numChanges'])
+ else:
+ print('No Results Found')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, AUDIENCE_SEGMENT_ID)
diff --git a/examples/ad_manager/v202205/audience_segment_service/update_audience_segments.py b/examples/ad_manager/v202205/audience_segment_service/update_audience_segments.py
new file mode 100755
index 00000000..e704f5ea
--- /dev/null
+++ b/examples/ad_manager/v202205/audience_segment_service/update_audience_segments.py
@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example updates rule based first party audience segments.
+
+To determine which audience segments exist, run get_all_audience_segments.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+AUDIENCE_SEGMENT_ID = 'INSERT_AUDIENCE_SEGMENT_ID_HERE'
+
+
+def main(client, audience_segment_id):
+ # Initialize appropriate service.
+ audience_segment_service = client.GetService(
+ 'AudienceSegmentService', version='v202205')
+
+ # Create statement object to get the specified first party audience segment.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('Type = :type AND Id = :audience_segment_id')
+ .WithBindVariable('audience_segment_id',
+ int(audience_segment_id))
+ .WithBindVariable('type', 'FIRST_PARTY')
+ .Limit(1))
+
+ # Get audience segments by statement.
+ response = audience_segment_service.getAudienceSegmentsByStatement(
+ statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ updated_audience_segments = []
+ for audience_segment in response['results']:
+ print('Audience segment with id "%s" and name "%s" will be updated.'
+ % (audience_segment['id'], audience_segment['name']))
+
+ audience_segment['membershipExpirationDays'] = '180'
+ updated_audience_segments.append(audience_segment)
+
+ audience_segments = audience_segment_service.updateAudienceSegments(
+ updated_audience_segments)
+
+ for audience_segment in audience_segments:
+ print('Audience segment with id "%s" and name "%s" was updated' %
+ (audience_segment['id'], audience_segment['name']))
+ else:
+ print('No audience segment found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, AUDIENCE_SEGMENT_ID)
diff --git a/examples/ad_manager/v202205/cdn_configuration_service/__init__.py b/examples/ad_manager/v202205/cdn_configuration_service/__init__.py
new file mode 100755
index 00000000..473ddba1
--- /dev/null
+++ b/examples/ad_manager/v202205/cdn_configuration_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202205/cdn_configuration_service/create_cdn_configurations.py b/examples/ad_manager/v202205/cdn_configuration_service/create_cdn_configurations.py
new file mode 100755
index 00000000..5fbd535b
--- /dev/null
+++ b/examples/ad_manager/v202205/cdn_configuration_service/create_cdn_configurations.py
@@ -0,0 +1,89 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new cdn configurations.
+
+To determine which configurations exist, run get_all_cdn_configurations.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ cdn_config_service = client.GetService('CdnConfigurationService',
+ version='v202205')
+
+ # Create cdn config objects.
+ # Only LIVE_STREAM_SOURCE_CONTENT is currently supported by the API.
+ configs = [{
+ # Basic example with no security policies.
+ 'name': 'ApiConfig1',
+ 'cdnConfigurationType': 'LIVE_STREAM_SOURCE_CONTENT',
+ 'sourceContentConfiguration': {
+ 'ingestSettings': {
+ 'urlPrefix': 'ingest1.com',
+ 'securityPolicy': {
+ 'securityPolicyType': 'NONE'
+ }
+ },
+ 'defaultDeliverySettings': {
+ 'urlPrefix': 'delivery1.com',
+ 'securityPolicy': {
+ 'securityPolicyType': 'NONE'
+ }
+ }
+ }
+ }, {
+ # Complex example with security policies.
+ 'name': 'ApiConfig2',
+ 'cdnConfigurationType': 'LIVE_STREAM_SOURCE_CONTENT',
+ 'sourceContentConfiguration': {
+ 'ingestSettings': {
+ 'urlPrefix': 'ingest1.com',
+ 'securityPolicy': {
+ 'securityPolicyType': 'AKAMAI',
+ 'disableServerSideUrlSigning': False,
+ 'tokenAuthenticationKey': 'abc123',
+ }
+ },
+ 'defaultDeliverySettings': {
+ 'urlPrefix': 'delivery1.com',
+ 'securityPolicy': {
+ 'securityPolicyType': 'AKAMAI',
+ 'disableServerSideUrlSigning': True,
+ 'originForwardingType': 'CONVENTIONAL',
+ 'originPathPrefix': '/path/to/my/origin'
+ }
+ }
+ }
+ }]
+
+ # Add configs.
+ configs = cdn_config_service.createCdnConfigurations(configs)
+
+ # Display results.
+ for config in configs:
+ print('Created CDN configuration with type "%s" and name "%s".'
+ % (config['cdnConfigurationType'], config['name']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/cdn_configuration_service/get_all_cdn_configurations.py b/examples/ad_manager/v202205/cdn_configuration_service/get_all_cdn_configurations.py
new file mode 100755
index 00000000..cfa1d576
--- /dev/null
+++ b/examples/ad_manager/v202205/cdn_configuration_service/get_all_cdn_configurations.py
@@ -0,0 +1,54 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all CDN configuration objects.
+
+Currently only configurations of type LIVE_STREAM_SOURCE_CONTENT will be
+returned.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ cdn_config_service = client.GetService('CdnConfigurationService',
+ version='v202205')
+
+ # Create a statement to select cdn configurations.
+ statement = ad_manager.StatementBuilder(version='v202205')
+
+ # Retrieve a small number of configs at a time, paging
+ # through until all have been retrieved.
+ while True:
+ response = (cdn_config_service
+ .getCdnConfigurationsByStatement(statement.ToStatement()))
+ if 'results' in response and len(response['results']):
+ for cdn in response['results']:
+ # Print out some information for each company.
+ print('Found CDN configuration with type "%s" and name "%s".'
+ % (cdn['cdnConfigurationType'], cdn['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/cms_metadata_service/activate_cms_metadata_values.py b/examples/ad_manager/v202205/cms_metadata_service/activate_cms_metadata_values.py
new file mode 100755
index 00000000..53742fe1
--- /dev/null
+++ b/examples/ad_manager/v202205/cms_metadata_service/activate_cms_metadata_values.py
@@ -0,0 +1,70 @@
+#!/usr/bin/env python
+#
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example activates CMS Metadata Values for a particular CMS Metadata Key.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the id of the CMS Metadata Key on which to activate the CMS Metadata
+# Values.
+CMS_METADATA_KEY_ID = 'INSERT_CMS_METADATA_KEY_ID_HERE'
+
+
+def main(client, cms_metadata_key_id):
+ # Initialize appropriate service.
+ cms_metadata_service = client.GetService('CmsMetadataService',
+ version='v202205')
+
+ # Create query.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('cmsKeyId = :cmsKeyId AND status = :status')
+ .WithBindVariable('status', 'INACTIVE')
+ .WithBindVariable('cmsKeyId', int(cms_metadata_key_id)))
+
+ values_activated = 0
+
+ # Get CMS Metadata Values by statement.
+ while True:
+ response = cms_metadata_service.getCmsMetadataValuesByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for cms_metadata_value in response['results']:
+ print('CMS Metadata Value with id "%s" and name "%s" will be '
+ 'activated.' % (cms_metadata_value['cmsMetadataValueId'],
+ cms_metadata_value['valueName']))
+
+ # Perform action.
+ result = cms_metadata_service.performCmsMetadataValueAction(
+ {'xsi_type': 'ActivateCmsMetadataValues'}, statement.ToStatement())
+ if result and int(result['numChanges']) > 0:
+ values_activated += int(result['numChanges'])
+ statement.offset += statement.limit
+ else:
+ break
+
+ # Display results.
+ if values_activated > 0:
+ print('Number of CMS Metadata Values activated: %s' % values_activated)
+ else:
+ print('No CMS Metadata Values were activated.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CMS_METADATA_KEY_ID)
diff --git a/examples/ad_manager/v202205/cms_metadata_service/get_all_cms_metadata_keys.py b/examples/ad_manager/v202205/cms_metadata_service/get_all_cms_metadata_keys.py
new file mode 100755
index 00000000..6b590392
--- /dev/null
+++ b/examples/ad_manager/v202205/cms_metadata_service/get_all_cms_metadata_keys.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2019 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all CmsMetadataKeys."""
+
+# Import appropriate modules from the client library.
+from __future__ import print_function
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ cms_metadata_service = client.GetService(
+ 'CmsMetadataService', version='v202205')
+
+ # Create a statement to select CmsMetadataKeys.
+ statement = ad_manager.StatementBuilder(version='v202205')
+
+ # Retrieve a small amount of keys at a time, paging
+ # through until all keys have been retrieved.
+ while True:
+ response = cms_metadata_service.getCmsMetadataKeysByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for cms_metadata_key in response['results']:
+ # Print out some information for each key.
+ print('CMS metadata key with Id %d and name "%s" was found.\n' %
+ (cms_metadata_key['id'], cms_metadata_key['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/cms_metadata_service/get_all_cms_metadata_values.py b/examples/ad_manager/v202205/cms_metadata_service/get_all_cms_metadata_values.py
new file mode 100755
index 00000000..902ad645
--- /dev/null
+++ b/examples/ad_manager/v202205/cms_metadata_service/get_all_cms_metadata_values.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python
+#
+# Copyright 2019 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all CmsMetadataValues."""
+
+# Import appropriate modules from the client library.
+from __future__ import print_function
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ cms_metadata_service = client.GetService(
+ 'CmsMetadataService', version='v202205')
+
+ # Create a statement to select CmsMetadataValues.
+ statement = ad_manager.StatementBuilder(version='v202205')
+
+ # Retrieve a small amount of values at a time, paging
+ # through until all values have been retrieved.
+ while True:
+ response = cms_metadata_service.getCmsMetadataValuesByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for cms_metadata_value in response['results']:
+ # Print out some information for each value.
+ print(('CMS metadata value with Id %d and name "%s", associated with '
+ 'the CmsMetadataKey with id %d and name "%s", was found.\n') %
+ (cms_metadata_value['cmsMetadataValueId'],
+ cms_metadata_value['valueName'], cms_metadata_value['key']['id'],
+ cms_metadata_value['key']['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/cms_metadata_service/get_cms_metadata_values_for_key.py b/examples/ad_manager/v202205/cms_metadata_service/get_cms_metadata_values_for_key.py
new file mode 100755
index 00000000..d265c5c2
--- /dev/null
+++ b/examples/ad_manager/v202205/cms_metadata_service/get_cms_metadata_values_for_key.py
@@ -0,0 +1,60 @@
+#!/usr/bin/env python
+#
+# Copyright 2019 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all CmsMetadataValues for a particular CmsMetadataKey."""
+
+# Import appropriate modules from the client library.
+from __future__ import print_function
+from googleads import ad_manager
+
+CMS_METADATA_KEY_NAME = 'INSERT_CMS_METADATA_KEY_NAME_HERE'
+
+
+def main(client, cms_metadata_key_name):
+ # Initialize appropriate service.
+ cms_metadata_service = client.GetService(
+ 'CmsMetadataService', version='v202205')
+
+ # Create a statement to select CmsMetadataValues for a particular key.
+ statement = (
+ ad_manager.StatementBuilder(version='v202205').Where(
+ 'cmsKey = :cmsMetadataKeyName').WithBindVariable(
+ 'cmsMetadataKeyName', cms_metadata_key_name))
+
+ # Retrieve a small amount of values at a time, paging
+ # through until all values have been retrieved.
+ while True:
+ response = cms_metadata_service.getCmsMetadataValuesByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for cms_metadata_value in response['results']:
+ # Print out some information for each value.
+ print(('CMS metadata value with Id %d and name "%s", associated with '
+ 'the CmsMetadataKey with id %d and name "%s", was found.\n') %
+ (cms_metadata_value['cmsMetadataValueId'],
+ cms_metadata_value['valueName'], cms_metadata_value['key']['id'],
+ cms_metadata_value['key']['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CMS_METADATA_KEY_NAME)
diff --git a/examples/ad_manager/v202205/company_service/__init__.py b/examples/ad_manager/v202205/company_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202205/company_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202205/company_service/create_companies.py b/examples/ad_manager/v202205/company_service/create_companies.py
new file mode 100755
index 00000000..33cb1132
--- /dev/null
+++ b/examples/ad_manager/v202205/company_service/create_companies.py
@@ -0,0 +1,62 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new companies.
+
+To determine which companies exist, run get_all_companies.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ company_service = client.GetService('CompanyService', version='v202205')
+
+ # Create company objects.
+ companies = [
+ {
+ 'name': 'Advertiser #%s' % uuid.uuid4(),
+ 'type': 'ADVERTISER'
+ },
+ {
+ 'name': 'Agency #%s' % uuid.uuid4(),
+ 'type': 'AGENCY'
+ }
+ ]
+
+ # Add companies.
+ companies = company_service.createCompanies(companies)
+
+ # Display results.
+ for company in companies:
+ print('Company with ID "%s", name "%s", and type "%s" was created.'
+ % (company['id'], company['name'], company['type']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/company_service/get_advertisers.py b/examples/ad_manager/v202205/company_service/get_advertisers.py
new file mode 100755
index 00000000..1e65c638
--- /dev/null
+++ b/examples/ad_manager/v202205/company_service/get_advertisers.py
@@ -0,0 +1,50 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all companies that are advertisers.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ company_service = client.GetService('CompanyService', version='v202205')
+ # Create a statement to select companies.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('type = :type')
+ .WithBindVariable('type', 'ADVERTISER'))
+
+ # Retrieve a small amount of companies at a time, paging
+ # through until all companies have been retrieved.
+ while True:
+ response = company_service.getCompaniesByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for company in response['results']:
+ # Print out some information for each company.
+ print('Company with ID "%d", name "%s", and type "%s" was found.\n' %
+ (company['id'], company['name'], company['type']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/company_service/get_all_companies.py b/examples/ad_manager/v202205/company_service/get_all_companies.py
new file mode 100755
index 00000000..bc0a5c9c
--- /dev/null
+++ b/examples/ad_manager/v202205/company_service/get_all_companies.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all companies.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ company_service = client.GetService('CompanyService', version='v202205')
+
+ # Create a statement to select companies.
+ statement = ad_manager.StatementBuilder(version='v202205')
+
+ # Retrieve a small amount of companies at a time, paging
+ # through until all companies have been retrieved.
+ while True:
+ response = company_service.getCompaniesByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for company in response['results']:
+ # Print out some information for each company.
+ print('Company with ID "%d", name "%s", and type "%s" was found.\n' %
+ (company['id'], company['name'], company['type']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/company_service/update_companies.py b/examples/ad_manager/v202205/company_service/update_companies.py
new file mode 100755
index 00000000..4854ad2f
--- /dev/null
+++ b/examples/ad_manager/v202205/company_service/update_companies.py
@@ -0,0 +1,70 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates company comments.
+
+To determine which companies exist, run get_all_companies.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the company to update.
+COMPANY_ID = 'INSERT_COMPANY_ID_HERE'
+
+
+def main(client, company_id):
+ # Initialize appropriate service.
+ company_service = client.GetService('CompanyService', version='v202205')
+
+ # Create statement object to only select a single company by ID.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('id = :id')
+ .WithBindVariable('id', int(company_id))
+ .Limit(1))
+
+ # Get companies by statement.
+ response = company_service.getCompaniesByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ updated_companies = []
+ for company in response['results']:
+ company['comment'] += ' Updated.'
+ updated_companies.append(company)
+
+ # Update the companies on the server.
+ companies = company_service.updateCompanies(updated_companies)
+
+ # Display results.
+ for company in companies:
+ print(('Company with ID "%s", name "%s", and comment "%s"'
+ ' was updated.')
+ % (company['id'], company['name'], company['comment']))
+ else:
+ print('No companies found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, COMPANY_ID)
diff --git a/examples/ad_manager/v202205/contact_service/__init__.py b/examples/ad_manager/v202205/contact_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202205/contact_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202205/contact_service/create_contacts.py b/examples/ad_manager/v202205/contact_service/create_contacts.py
new file mode 100755
index 00000000..c01935a5
--- /dev/null
+++ b/examples/ad_manager/v202205/contact_service/create_contacts.py
@@ -0,0 +1,71 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new contacts.
+
+To determine which contacts exist, run get_all_contacts.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the advertiser company this contact is associated with.
+ADVERTISER_COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
+
+# Set the ID of the agency company this contact is associated with.
+AGENCY_COMPANY_ID = 'INSERT_AGENCY_COMPANY_ID_HERE'
+
+
+def main(client, advertiser_company_id, agency_company_id):
+ # Initialize appropriate service.
+ contact_service = client.GetService('ContactService', version='v202205')
+
+ # Create an advertiser contact.
+ advertiser_contact = {
+ 'name': 'Mr. Advertiser #%s' % uuid.uuid4(),
+ 'email': 'advertiser@advertising.com',
+ 'companyId': advertiser_company_id
+ }
+
+ # Create an agency contact.
+ agency_contact = {
+ 'name': 'Ms. Agency #%s' % uuid.uuid4(),
+ 'email': 'agency@agencies.com',
+ 'companyId': agency_company_id
+ }
+
+ # Create the contacts on the server.
+ contacts = contact_service.createContacts([advertiser_contact,
+ agency_contact])
+
+ # Display results.
+ for contact in contacts:
+ print('Contact with ID "%s" name "%s" was created.'
+ % (contact['id'], contact['name']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ADVERTISER_COMPANY_ID, AGENCY_COMPANY_ID)
diff --git a/examples/ad_manager/v202205/contact_service/get_all_contacts.py b/examples/ad_manager/v202205/contact_service/get_all_contacts.py
new file mode 100755
index 00000000..05c1a277
--- /dev/null
+++ b/examples/ad_manager/v202205/contact_service/get_all_contacts.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all contacts.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ contact_service = client.GetService('ContactService', version='v202205')
+
+ # Create a statement to select contacts.
+ statement = ad_manager.StatementBuilder(version='v202205')
+
+ # Retrieve a small amount of contacts at a time, paging
+ # through until all contacts have been retrieved.
+ while True:
+ response = contact_service.getContactsByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for contact in response['results']:
+ # Print out some information for each contact.
+ print('Contact with ID "%d" and name "%s" was found.\n' %
+ (contact['id'], contact['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/contact_service/get_uninvited_contacts.py b/examples/ad_manager/v202205/contact_service/get_uninvited_contacts.py
new file mode 100755
index 00000000..3e338d4b
--- /dev/null
+++ b/examples/ad_manager/v202205/contact_service/get_uninvited_contacts.py
@@ -0,0 +1,50 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all contacts that aren't invited yet.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ contact_service = client.GetService('ContactService', version='v202205')
+ # Create a statement to select contacts.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('status = :status')
+ .WithBindVariable('status', 'UNINVITED'))
+
+ # Retrieve a small amount of contacts at a time, paging
+ # through until all contacts have been retrieved.
+ while True:
+ response = contact_service.getContactsByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for contact in response['results']:
+ # Print out some information for each contact.
+ print('Contact with ID "%d" and name "%s" was found.\n' %
+ (contact['id'], contact['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/contact_service/update_contacts.py b/examples/ad_manager/v202205/contact_service/update_contacts.py
new file mode 100755
index 00000000..8c1ecacf
--- /dev/null
+++ b/examples/ad_manager/v202205/contact_service/update_contacts.py
@@ -0,0 +1,71 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates contact addresses.
+
+To determine which contacts exist, run get_all_contacts.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the contact to update.
+CONTACT_ID = 'INSERT_CONTACT_ID_HERE'
+
+
+def main(client, contact_id):
+ # Initialize appropriate service.
+ contact_service = client.GetService('ContactService', version='v202205')
+
+ # Create statement object to select the single contact by ID.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('id = :id')
+ .WithBindVariable('id', int(contact_id))
+ .Limit(1))
+
+ # Get contacts by statement.
+ response = contact_service.getContactsByStatement(
+ statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ updated_contacts = []
+ for contact in response['results']:
+ contact['address'] = '123 New Street, New York, NY, 10011'
+ updated_contacts.append(contact)
+
+ # Update the contact on the server.
+ contacts = contact_service.updateContacts(updated_contacts)
+
+ # Display results.
+ for contact in contacts:
+ print(('Contact with ID "%s", name "%s", and address "%s" '
+ 'was updated.')
+ % (contact['id'], contact['name'], contact['address']))
+ else:
+ print('No contacts found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CONTACT_ID)
diff --git a/examples/ad_manager/v202205/content_service/__init__.py b/examples/ad_manager/v202205/content_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202205/content_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202205/content_service/get_all_content.py b/examples/ad_manager/v202205/content_service/get_all_content.py
new file mode 100755
index 00000000..884179e8
--- /dev/null
+++ b/examples/ad_manager/v202205/content_service/get_all_content.py
@@ -0,0 +1,54 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all content."""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ content_service = client.GetService('ContentService', version='v202205')
+
+ # Create a statement to select content.
+ statement = ad_manager.StatementBuilder(version='v202205')
+
+ # Retrieve a small amount of content at a time, paging
+ # through until all content have been retrieved.
+ while True:
+ response = content_service.getContentByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for content in response['results']:
+ # Print out some information for each content.
+ content_description = ('Content with ID "%d" and name "%s"' %
+ (content['id'], content['name'].encode('utf-8')))
+ if content['contentBundleIds']:
+ content_description += (' belonging to bundle IDs %s' %
+ content['contentBundleIds'])
+ content_description += ' was found.'
+ print(content_description)
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/content_service/get_recently_modified_content.py b/examples/ad_manager/v202205/content_service/get_recently_modified_content.py
new file mode 100755
index 00000000..6a429395
--- /dev/null
+++ b/examples/ad_manager/v202205/content_service/get_recently_modified_content.py
@@ -0,0 +1,66 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets recently modified content."""
+
+# Import appropriate modules from the client library.
+from datetime import datetime
+from datetime import timedelta
+
+from googleads import ad_manager
+import pytz
+
+
+def main(client):
+ # Initialize appropriate service.
+ content_service = client.GetService('ContentService', version='v202205')
+
+ last_modified = (datetime.now(tz=pytz.timezone('America/New_York'))
+ - timedelta(days=1))
+
+ # Create a statement to get recently modified content based on
+ # lastModifiedDateTime. Changes to content bundle associations will update
+ # the lastModifiedDateTime, but CMS metadata changes may not change the
+ # lastModifiedDateTime.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('lastModifiedDateTime >= :lastModifiedDateTime')
+ .WithBindVariable('lastModifiedDateTime', last_modified))
+
+ # Retrieve a small amount of content at a time, paging
+ # through until all content have been retrieved.
+ while True:
+ response = content_service.getContentByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for content in response['results']:
+ # Print out some information for each content.
+ content_description = ('Content with ID "%d" and name "%s"' %
+ (content['id'], content['name'].encode('utf-8')))
+ if content['contentBundleIds']:
+ content_description += (' belonging to bundle IDs %s' %
+ content['contentBundleIds'])
+ content_description += ' was found.'
+ print(content_description)
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/creative_service/__init__.py b/examples/ad_manager/v202205/creative_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202205/creative_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202205/creative_service/copy_image_creatives.py b/examples/ad_manager/v202205/creative_service/copy_image_creatives.py
new file mode 100755
index 00000000..cf627ba0
--- /dev/null
+++ b/examples/ad_manager/v202205/creative_service/copy_image_creatives.py
@@ -0,0 +1,60 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example creates a copy of an image creative.
+
+To determine which image creatives exist, run get_image_creatives.py
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the line item to pause.
+CREATIVE_ID = 'INSERT_CREATIVE_ID_HERE'
+
+
+def main(client):
+ # Initialize appropriate service.
+ creative_service = client.GetService('CreativeService', version='v202205')
+
+ # Create a statement to get the image creative.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('id = :id')
+ .OrderBy('id', ascending=True)
+ .WithBindVariable('id', CREATIVE_ID))
+
+ # Get the creative.
+ query_result = creative_service.getCreativesByStatement(
+ statement.ToStatement())
+
+ image_creative = query_result['results'][0]
+
+ # Build the new creative, set id to None to create a copy.
+ image_creative['id'] = None
+ image_creative['name'] = 'Copy of %s' % image_creative['name']
+
+ result = creative_service.createCreatives([image_creative])[0]
+ print('A creative with ID %d, name "%s", and type "%s" was created and '
+ 'can be previewed at: %s' % (result['id'],
+ result['name'],
+ ad_manager.AdManagerClassType(result),
+ result['previewUrl']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/creative_service/create_creative_from_template.py b/examples/ad_manager/v202205/creative_service/create_creative_from_template.py
new file mode 100755
index 00000000..fe5146f4
--- /dev/null
+++ b/examples/ad_manager/v202205/creative_service/create_creative_from_template.py
@@ -0,0 +1,111 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates a new template creative for a given advertiser.
+
+To determine which companies are advertisers, run get_advertisers.py.
+To determine which creative templates exist, run
+get_all_creative_templates.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import os
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set id of the advertiser (company) that the creative will be assigned to.
+ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
+
+
+def main(client, advertiser_id):
+ # Initialize appropriate service.
+ creative_service = client.GetService('CreativeService', version='v202205')
+
+ # Use the image banner with optional third party tracking template.
+ creative_template_id = '10000680'
+
+ # Create image asset.
+ file_name = 'image%s.jpg' % uuid.uuid4()
+ image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data',
+ 'medium_rectangle.jpg'), 'r').read()
+ size = {
+ 'width': '300',
+ 'height': '250'
+ }
+ asset = {
+ 'xsi_type': 'CreativeAsset',
+ 'fileName': file_name,
+ 'assetByteArray': image_data,
+ 'size': size
+ }
+
+ # Create creative from templates.
+ creative = {
+ 'xsi_type': 'TemplateCreative',
+ 'name': 'Template Creative #%s' % uuid.uuid4(),
+ 'advertiserId': advertiser_id,
+ 'size': size,
+ 'creativeTemplateId': creative_template_id,
+ 'creativeTemplateVariableValues': [
+ {
+ 'xsi_type': 'AssetCreativeTemplateVariableValue',
+ 'uniqueName': 'Imagefile',
+ 'asset': asset
+ },
+ {
+ 'xsi_type': 'LongCreativeTemplateVariableValue',
+ 'uniqueName': 'Imagewidth',
+ 'value': '300'
+ },
+ {
+ 'xsi_type': 'LongCreativeTemplateVariableValue',
+ 'uniqueName': 'Imageheight',
+ 'value': '250'
+ },
+ {
+ 'xsi_type': 'UrlCreativeTemplateVariableValue',
+ 'uniqueName': 'ClickthroughURL',
+ 'value': 'www.google.com'
+ },
+ {
+ 'xsi_type': 'StringCreativeTemplateVariableValue',
+ 'uniqueName': 'Targetwindow',
+ 'value': '_blank'
+ }
+ ]
+ }
+
+ # Call service to create the creative.
+ creative = creative_service.createCreatives([creative])[0]
+
+ # Display results.
+ print('Template creative with id "%s", name "%s", and type "%s" was '
+ 'created and can be previewed at %s.'
+ % (creative['id'], creative['name'],
+ ad_manager.AdManagerClassType(creative), creative['previewUrl']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ADVERTISER_ID)
diff --git a/examples/ad_manager/v202205/creative_service/create_creatives.py b/examples/ad_manager/v202205/creative_service/create_creatives.py
new file mode 100755
index 00000000..184b4611
--- /dev/null
+++ b/examples/ad_manager/v202205/creative_service/create_creatives.py
@@ -0,0 +1,93 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new image creatives for a given advertiser.
+
+To determine which companies are advertisers, run get_advertisers.py.
+To determine which creatives already exist, run get_all_creatives.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import os
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set id of the advertiser (company) that all creatives will be assigned to.
+ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
+
+
+def main(client, advertiser_id):
+ # Initialize appropriate service.
+ creative_service = client.GetService('CreativeService', version='v202205')
+
+ # Create creative objects.
+ creatives = []
+ with open(
+ os.path.join(
+ os.path.split(__file__)[0], '..', '..', 'data',
+ 'medium_rectangle.jpg'), 'rb') as image:
+ image_data = image.read()
+
+ for _ in range(5):
+ # Create creative size.
+ size = {
+ 'width': '300',
+ 'height': '250'
+ }
+
+ # Create image asset.
+ creative_asset = {
+ 'xsi_type': 'CreativeAsset',
+ 'fileName': 'image.jpg',
+ 'assetByteArray': image_data,
+ 'size': size
+ }
+
+ # Create an image creative.
+ creative = {
+ 'xsi_type': 'ImageCreative',
+ 'name': 'Image Creative #%s' % uuid.uuid4(),
+ 'advertiserId': advertiser_id,
+ 'destinationUrl': 'http://google.com',
+ 'size': size,
+ 'primaryImageAsset': creative_asset
+ }
+
+ creatives.append(creative)
+
+ # Add creatives.
+ creatives = creative_service.createCreatives(creatives)
+
+ # Display results.
+ for creative in creatives:
+ print('Image creative with id "%s", name "%s", and type "%s" was '
+ 'created and can be previewed at %s.' %
+ (creative['id'], creative['name'],
+ ad_manager.AdManagerClassType(creative), creative['previewUrl']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ADVERTISER_ID)
diff --git a/examples/ad_manager/v202205/creative_service/create_custom_creative.py b/examples/ad_manager/v202205/creative_service/create_custom_creative.py
new file mode 100755
index 00000000..7a6161dc
--- /dev/null
+++ b/examples/ad_manager/v202205/creative_service/create_custom_creative.py
@@ -0,0 +1,88 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example creates a custom creative for a given advertiser.
+
+This feature is only available to Ad Manager 360 solution networks. To determine
+which companies are advertisers, run get_advertisers.py. To determine
+which creative templates exist, run get_all_creative_templates.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import os
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set id of the advertiser (company) that the creative will be assigned to.
+ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
+
+
+def main(client, advertiser_id):
+ # Initialize appropriate service.
+ creative_service = client.GetService('CreativeService', version='v202205')
+
+ # Get the image data for the creative.
+ image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data',
+ 'medium_rectangle.jpg'), 'r').read()
+
+ # Create the HTML snippet used in the custom creative.
+ html_snippet = (' Click above for '
+ 'great deals!') % ('%%CLICK_URL_UNESC%%', '%%DEST_URL%%',
+ '%%FILE:IMAGE_ASSET%%')
+
+ # Create custom creative.
+ creative = {
+ 'xsi_type': 'CustomCreative',
+ 'name': 'Custom Creative #%s' % uuid.uuid4(),
+ 'advertiserId': advertiser_id,
+ 'size': {'width': '300', 'height': '250'},
+ 'destinationUrl': 'http://google.com',
+ 'customCreativeAssets': [
+ {
+ 'xsi_type': 'CustomCreativeAsset',
+ 'macroName': 'IMAGE_ASSET',
+ 'asset': {
+ 'assetByteArray': image_data,
+ 'fileName': 'image%s.jpg' % uuid.uuid4()
+ }
+ }
+ ],
+ 'htmlSnippet': html_snippet
+ }
+
+ # Call service to create the creative.
+ creatives = creative_service.createCreatives([creative])
+
+ # Display results.
+ if creatives:
+ creative = creatives[0]
+ print('Template creative with id "%s", name "%s", and type "%s" was '
+ 'created and can be previewed at %s.'
+ % (creative['id'], creative['name'],
+ ad_manager.AdManagerClassType(creative), creative['previewUrl']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ADVERTISER_ID)
diff --git a/examples/ad_manager/v202205/creative_service/create_native_creative.py b/examples/ad_manager/v202205/creative_service/create_native_creative.py
new file mode 100755
index 00000000..ff65cb25
--- /dev/null
+++ b/examples/ad_manager/v202205/creative_service/create_native_creative.py
@@ -0,0 +1,132 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates a new native creative for a given advertiser.
+
+To determine which companies are advertisers, run get_advertisers.py.
+
+The code in this example will use app data from the Google sample app
+'Pie Noon':
+
+https://play.google.com/store/apps/details?id=com.google.fpl.pie_noon&hl=en
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+"""
+
+import uuid
+from urllib.request import urlopen
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set id of the advertiser (company) that the creative will be assigned to.
+ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE'
+ICON_URL = ('https://lh4.ggpht.com/GIGNKdGHMEHFDw6TM2bgAUDKPQQRIReKZPqEpMeEhZO'
+ 'PYnTdOQGaSpGSEZflIFs0iw=h300')
+APP_ICON_SMALL = ('https://lh6.ggpht.com/Jzvjne5CLs6fJ1MHF-XeuUfpABzl0YNMlp4Rp'
+ 'HnvPRCIj4--eTDwtyouwUDzVVekXw=w300')
+
+
+def main(client, advertiser_id):
+ # Initialize appropriate service.
+ creative_service = client.GetService('CreativeService', version='v202205')
+
+ # Use the system defined native app install creative template.
+ creative_template_id = '10004400'
+
+ image_data = urlopen(ICON_URL).read()
+
+ app_icon_data = urlopen(APP_ICON_SMALL).read()
+
+ # Create creative from templates.
+ creative = {
+ 'xsi_type': 'TemplateCreative',
+ 'name': 'Native Creative #%s' % uuid.uuid4(),
+ 'advertiserId': advertiser_id,
+ 'size': {'width': '1', 'height': '1', 'isAspectRatio': False},
+ 'creativeTemplateId': creative_template_id,
+ 'destinationUrl': ('https://play.google.com/store/apps/details?id='
+ 'com.google.fpl.pie_noon'),
+ 'creativeTemplateVariableValues': [
+ {
+ 'xsi_type': 'AssetCreativeTemplateVariableValue',
+ 'uniqueName': 'Image',
+ 'asset': {
+ 'assetByteArray': image_data,
+ 'fileName': 'file%s.png' % uuid.uuid4()
+ }
+ },
+ {
+ 'xsi_type': 'AssetCreativeTemplateVariableValue',
+ 'uniqueName': 'Appicon',
+ 'asset': {
+ 'assetByteArray': app_icon_data,
+ 'fileName': 'appicon%s.png' % uuid.uuid4()
+ }
+ },
+ {
+ 'xsi_type': 'StringCreativeTemplateVariableValue',
+ 'uniqueName': 'Price',
+ 'value': 'Free'
+ },
+ {
+ 'xsi_type': 'StringCreativeTemplateVariableValue',
+ 'uniqueName': 'Calltoaction',
+ 'value': 'Install'
+ },
+ {
+ 'xsi_type': 'StringCreativeTemplateVariableValue',
+ 'uniqueName': 'Starrating',
+ 'value': '4'
+ },
+ {
+ 'xsi_type': 'StringCreativeTemplateVariableValue',
+ 'uniqueName': 'Store',
+ 'value': 'Google Play'
+ },
+ {
+ 'xsi_type': 'UrlCreativeTemplateVariableValue',
+ 'uniqueName': 'DeeplinkclickactionURL',
+ 'value': 'market://details?id=com.google.fpl.pie_noon'
+ },
+ {
+ 'xsi_type': 'StringCreativeTemplateVariableValue',
+ 'uniqueName': 'Body',
+ 'value': 'Try multi-screen mode!'
+ },
+ {
+ 'xsi_type': 'StringCreativeTemplateVariableValue',
+ 'uniqueName': 'Headline',
+ 'value': 'Pie Noon'
+ }
+ ]
+ }
+
+ # Call service to create the creative.
+ creative = creative_service.createCreatives([creative])[0]
+
+ # Display results.
+ print('Native creative with id "%s" and name "%s" was '
+ 'created and can be previewed at %s.'
+ % (creative['id'], creative['name'], creative['previewUrl']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ADVERTISER_ID)
diff --git a/examples/ad_manager/v202205/creative_service/create_video_creatives.py b/examples/ad_manager/v202205/creative_service/create_video_creatives.py
new file mode 100755
index 00000000..4718f45e
--- /dev/null
+++ b/examples/ad_manager/v202205/creative_service/create_video_creatives.py
@@ -0,0 +1,66 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates a new video creative for a given advertiser.
+
+To determine which companies are advertisers, run get_advertisers.py.
+To determine which creatives already exist, run get_all_creatives.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+"""
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set id of the advertiser (company) that the creative will be assigned to.
+ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE'
+
+
+def main(client, advertiser_id):
+ # Initialize appropriate service.
+ creative_service = client.GetService('CreativeService', version='v202205')
+
+ # Create a video creative.
+ creative = {
+ 'xsi_type': 'VideoCreative',
+ 'name': 'Video Creative #%s' % uuid.uuid4(),
+ 'advertiserId': advertiser_id,
+ 'size': {'width': '640', 'height': '360', 'isAspectRatio': False},
+ 'destinationUrl': 'https://google.com',
+ 'duration': '115000',
+ 'videoSourceUrl': (
+ 'https://storage.googleapis.com/interactive-media-ads/media/'
+ 'android.mp4')
+ }
+
+ # Call service to create the creative.
+ creative = creative_service.createCreatives([creative])[0]
+
+ # Display results.
+ print('Video creative with id "%s" and name "%s" was created and can be '
+ 'previewed at:\n%s.'
+ % (creative['id'], creative['name'], creative['vastPreviewUrl']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ADVERTISER_ID)
diff --git a/examples/ad_manager/v202205/creative_service/get_all_creatives.py b/examples/ad_manager/v202205/creative_service/get_all_creatives.py
new file mode 100755
index 00000000..fa1ba2d2
--- /dev/null
+++ b/examples/ad_manager/v202205/creative_service/get_all_creatives.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all creatives.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ creative_service = client.GetService('CreativeService', version='v202205')
+
+ # Create a statement to select creatives.
+ statement = ad_manager.StatementBuilder(version='v202205')
+
+ # Retrieve a small amount of creatives at a time, paging
+ # through until all creatives have been retrieved.
+ while True:
+ response = creative_service.getCreativesByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for creative in response['results']:
+ # Print out some information for each creative.
+ print('Creative with ID "%d" and name "%s" was found.\n' %
+ (creative['id'], creative['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/creative_service/get_image_creatives.py b/examples/ad_manager/v202205/creative_service/get_image_creatives.py
new file mode 100755
index 00000000..7c85bfef
--- /dev/null
+++ b/examples/ad_manager/v202205/creative_service/get_image_creatives.py
@@ -0,0 +1,50 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all image creatives.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ creative_service = client.GetService('CreativeService', version='v202205')
+ # Create a statement to select creatives.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('creativeType = :creativeType')
+ .WithBindVariable('creativeType', 'ImageCreative'))
+
+ # Retrieve a small amount of creatives at a time, paging
+ # through until all creatives have been retrieved.
+ while True:
+ response = creative_service.getCreativesByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for creative in response['results']:
+ # Print out some information for each creative.
+ print('Creative with ID "%d" and name "%s" was found.\n' %
+ (creative['id'], creative['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/creative_service/update_creatives.py b/examples/ad_manager/v202205/creative_service/update_creatives.py
new file mode 100755
index 00000000..8284c6ac
--- /dev/null
+++ b/examples/ad_manager/v202205/creative_service/update_creatives.py
@@ -0,0 +1,71 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates the destination URL of a single image creative.
+
+To determine which image creatives exist, run get_all_creatives.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+IMAGE_CREATIVE_ID = 'INSERT_IMAGE_CREATIVE_ID_HERE'
+
+
+def main(client, image_creative_id):
+ # Initialize appropriate service.
+ creative_service = client.GetService('CreativeService', version='v202205')
+
+ # Create statement object to get the creative by ID.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('creativeType = :type AND id = :id')
+ .WithBindVariable('type', 'ImageCreative')
+ .WithBindVariable('id', int(image_creative_id))
+ .Limit(1))
+
+ # Get creatives by statement.
+ response = creative_service.getCreativesByStatement(
+ statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ # Update each local creative object by changing its destination URL.
+ updated_creatives = []
+ for creative in response['results']:
+ creative['destinationUrl'] = 'http://news.google.com'
+ updated_creatives.append(creative)
+
+ # Update creatives remotely.
+ creatives = creative_service.updateCreatives(updated_creatives)
+
+ # Display results.
+ for creative in creatives:
+ print('Image creative with id "%s" and destination URL "%s" was '
+ 'updated.' % (creative['id'], creative['destinationUrl']))
+ else:
+ print('No creatives found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, IMAGE_CREATIVE_ID)
diff --git a/examples/ad_manager/v202205/creative_set_service/__init__.py b/examples/ad_manager/v202205/creative_set_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202205/creative_set_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202205/creative_set_service/associate_creative_set_to_line_item.py b/examples/ad_manager/v202205/creative_set_service/associate_creative_set_to_line_item.py
new file mode 100755
index 00000000..cdac941e
--- /dev/null
+++ b/examples/ad_manager/v202205/creative_set_service/associate_creative_set_to_line_item.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Creates a line item creative association for a creative set.
+
+To create creative sets, run create_creative_set.py. To create creatives, run
+create_creatives.py. To determine which LICAs exist, run get_all_licas.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+CREATIVE_SET_ID = 'INSERT_CREATIVE_SET_ID_HERE'
+LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
+
+
+def main(client, creative_set_id, line_item_id):
+ # Initialize appropriate service.
+ lica_service = client.GetService(
+ 'LineItemCreativeAssociationService', version='v202205')
+
+ # Create LICA for a creative set.
+ lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id}
+
+ # Add LICA.
+ lica = lica_service.createLineItemCreativeAssociations([lica])
+
+ # Display results.
+ print(('LICA with line item ID "%s" and creative set ID "%s" was '
+ 'created.') % (lica['lineItemId'], lica['creativeSetId']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CREATIVE_SET_ID, LINE_ITEM_ID)
diff --git a/examples/ad_manager/v202205/creative_set_service/create_creative_set.py b/examples/ad_manager/v202205/creative_set_service/create_creative_set.py
new file mode 100755
index 00000000..98965200
--- /dev/null
+++ b/examples/ad_manager/v202205/creative_set_service/create_creative_set.py
@@ -0,0 +1,62 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new creative sets.
+
+To determine which creative sets exist, run get_all_creative_sets.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+MASTER_CREATIVE_ID = 'INSERT_MASTER_CREATIVE_ID_HERE'
+COMPANION_CREATIVE_ID = 'INSERT_COMPANION_CREATIVE_ID_HERE'
+
+
+def main(client, master_creative_id, companion_creative_id):
+ # Initialize appropriate service.
+ creative_set_service = client.GetService('CreativeSetService',
+ version='v202205')
+
+ # Create creative set objects.
+ creative_set = {'name': 'Creative set #%s' % uuid.uuid4(),
+ 'masterCreativeId': master_creative_id,
+ 'companionCreativeIds': [companion_creative_id]}
+
+ # Add creative sets.
+ creative_set = creative_set_service.createCreativeSet(creative_set)
+
+ # Display results.
+ if creative_set:
+ print(('Creative set with ID "%s", master creative ID "%s", and '
+ 'companion creative IDs "%s" was created.') %
+ (creative_set['id'], creative_set['masterCreativeId'], ','.join(
+ str(v) for v in creative_set['companionCreativeIds'])))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, MASTER_CREATIVE_ID, COMPANION_CREATIVE_ID)
diff --git a/examples/ad_manager/v202205/creative_set_service/get_all_creative_sets.py b/examples/ad_manager/v202205/creative_set_service/get_all_creative_sets.py
new file mode 100755
index 00000000..b190ab5b
--- /dev/null
+++ b/examples/ad_manager/v202205/creative_set_service/get_all_creative_sets.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all creative sets.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ creative_set_service = client.GetService(
+ 'CreativeSetService', version='v202205')
+
+ # Create a statement to select creative sets.
+ statement = ad_manager.StatementBuilder(version='v202205')
+
+ # Retrieve a small amount of creative sets at a time, paging
+ # through until all creative sets have been retrieved.
+ while True:
+ response = creative_set_service.getCreativeSetsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for creative_set in response['results']:
+ # Print out some information for each creative set.
+ print('Creative set with ID "%d" and name "%s" was found.\n' %
+ (creative_set['id'], creative_set['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/creative_set_service/get_creative_sets_for_master_creative.py b/examples/ad_manager/v202205/creative_set_service/get_creative_sets_for_master_creative.py
new file mode 100755
index 00000000..7a7d42fe
--- /dev/null
+++ b/examples/ad_manager/v202205/creative_set_service/get_creative_sets_for_master_creative.py
@@ -0,0 +1,54 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all creative sets for a master creative.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+MASTER_CREATIVE_ID = 'INSERT_MASTER_CREATIVE_ID_HERE'
+
+
+def main(client, master_creative_id):
+ # Initialize appropriate service.
+ creative_set_service = client.GetService(
+ 'CreativeSetService', version='v202205')
+ # Create a statement to select creative sets.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('masterCreativeId = :masterCreativeId')
+ .WithBindVariable('masterCreativeId', master_creative_id))
+
+ # Retrieve a small amount of creative sets at a time, paging
+ # through until all creative sets have been retrieved.
+ while True:
+ response = creative_set_service.getCreativeSetsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for creative_set in response['results']:
+ # Print out some information for each creative set.
+ print('Creative set with ID "%d" and name "%s" was found.\n' %
+ (creative_set['id'], creative_set['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, MASTER_CREATIVE_ID)
diff --git a/examples/ad_manager/v202205/creative_set_service/update_creative_set.py b/examples/ad_manager/v202205/creative_set_service/update_creative_set.py
new file mode 100755
index 00000000..20a8728d
--- /dev/null
+++ b/examples/ad_manager/v202205/creative_set_service/update_creative_set.py
@@ -0,0 +1,73 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates a creative set by adding a companion creative.
+
+To determine which creative sets exist, run get_all_creative_sets.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the creative set to update.
+CREATIVE_SET_ID = 'INSERT_CREATIVE_SET_ID_HERE'
+COMPANION_CREATIVE_ID = 'INSERT_COMPANION_CREATIVE_ID_HERE'
+
+
+def main(client, creative_set_id, companion_creative_id):
+ # Initialize appropriate service.
+ creative_set_service = client.GetService('CreativeSetService',
+ version='v202205')
+
+ # Create statement to select a single creative set by ID.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('id = :creativeSetId')
+ .WithBindVariable('creativeSetId', int(creative_set_id)))
+
+ # Get creative set.
+ response = creative_set_service.getCreativeSetsByStatement(
+ statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ updated_created_sets = []
+ for creative_set in response['results']:
+ creative_set['companionCreativeIds'].append(companion_creative_id)
+ updated_created_sets.append(creative_set)
+
+ # Update the creative sets on the server.
+ creative_sets = creative_set_service.updateCreativeSet(updated_created_sets)
+
+ # Display results.
+ for creative_set in creative_sets:
+ print(('Creative set with ID "%s", master creative ID "%s", and '
+ 'companion creative IDs {%s} was updated.')
+ % (creative_set['id'], creative_set['masterCreativeId'],
+ ','.join(creative_set['companionCreativeIds'])))
+ else:
+ print('No creative sets found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CREATIVE_SET_ID, COMPANION_CREATIVE_ID)
diff --git a/examples/ad_manager/v202205/creative_template_service/__init__.py b/examples/ad_manager/v202205/creative_template_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202205/creative_template_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202205/creative_template_service/get_all_creative_templates.py b/examples/ad_manager/v202205/creative_template_service/get_all_creative_templates.py
new file mode 100755
index 00000000..f1f4eb82
--- /dev/null
+++ b/examples/ad_manager/v202205/creative_template_service/get_all_creative_templates.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all creative templates.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ creative_template_service = client.GetService(
+ 'CreativeTemplateService', version='v202205')
+
+ # Create a statement to select creative templates.
+ statement = ad_manager.StatementBuilder(version='v202205')
+
+ # Retrieve a small amount of creative templates at a time, paging
+ # through until all creative templates have been retrieved.
+ while True:
+ response = creative_template_service.getCreativeTemplatesByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for creative_template in response['results']:
+ # Print out some information for each creative template.
+ print('Creative template with ID "%d" and name "%s" was found.\n' %
+ (creative_template['id'], creative_template['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/creative_template_service/get_system_defined_creative_templates.py b/examples/ad_manager/v202205/creative_template_service/get_system_defined_creative_templates.py
new file mode 100755
index 00000000..8ec43452
--- /dev/null
+++ b/examples/ad_manager/v202205/creative_template_service/get_system_defined_creative_templates.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all system defined creative templates.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ creative_template_service = client.GetService(
+ 'CreativeTemplateService', version='v202205')
+ # Create a statement to select creative templates.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('type = :type')
+ .WithBindVariable('type', 'SYSTEM_DEFINED'))
+
+ # Retrieve a small amount of creative templates at a time, paging
+ # through until all creative templates have been retrieved.
+ while True:
+ response = creative_template_service.getCreativeTemplatesByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for creative_template in response['results']:
+ # Print out some information for each creative template.
+ print('Creative template with ID "%d" and name "%s" was found.\n' %
+ (creative_template['id'], creative_template['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/creative_wrapper_service/create_creative_wrappers.py b/examples/ad_manager/v202205/creative_wrapper_service/create_creative_wrappers.py
new file mode 100755
index 00000000..dca07888
--- /dev/null
+++ b/examples/ad_manager/v202205/creative_wrapper_service/create_creative_wrappers.py
@@ -0,0 +1,63 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates a new creative wrapper.
+
+Creative wrappers must be associated with a LabelType.CREATIVE_WRAPPER label and
+applied to ad units by AdUnit.appliedLabels. To determine which creative
+wrappers exist, run get_all_creative_wrappers.py
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+LABEL_ID = 'INSERT_CREATIVE_WRAPPER_LABEL_ID_HERE'
+
+
+def main(client, label_id):
+ # Initialize appropriate service.
+ creative_wrapper_service = client.GetService('CreativeWrapperService',
+ version='v202205')
+
+ # Create creative wrapper objects.
+ creative_wrapper = {
+ # A label can only be associated with one creative wrapper.
+ 'labelId': label_id,
+ 'ordering': 'INNER',
+ 'htmlHeader': 'My creative wrapper header',
+ 'htmlFooter': 'My creative wrapper footer'
+ }
+
+ # Add creative wrapper.
+ creative_wrappers = creative_wrapper_service.createCreativeWrappers(
+ [creative_wrapper])
+
+ # Display results.
+ for creative_wrapper in creative_wrappers:
+ print('Creative wrapper with ID "%s" applying to label "%s" was '
+ 'created.' % (creative_wrapper['id'], creative_wrapper['labelId']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, LABEL_ID)
diff --git a/examples/ad_manager/v202205/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/ad_manager/v202205/creative_wrapper_service/deactivate_creative_wrapper.py
new file mode 100755
index 00000000..c79cab5b
--- /dev/null
+++ b/examples/ad_manager/v202205/creative_wrapper_service/deactivate_creative_wrapper.py
@@ -0,0 +1,78 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example deactivates a creative wrapper belonging to a label.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+LABEL_ID = 'INSERT_LABEL_ID_HERE'
+
+
+def main(client, label_id):
+ # Initialize appropriate service.
+ creative_wrapper_service = client.GetService('CreativeWrapperService',
+ version='v202205')
+
+ # Create a query to select the active creative wrappers for the given label.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('status = :status AND labelId = :labelId')
+ .WithBindVariable('status', 'ACTIVE')
+ .WithBindVariable('labelId', int(label_id)))
+
+ creative_wrappers_deactivated = 0
+
+ # Get creative wrappers by statement.
+ while True:
+ response = creative_wrapper_service.getCreativeWrappersByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ # Display results.
+ for creative_wrapper in response['results']:
+ print('Creative wrapper with ID "%s" applying to label "%s" with '
+ 'status "%s" will be deactivated.' %
+ (creative_wrapper['id'],
+ creative_wrapper['labelId'],
+ creative_wrapper['status']))
+ # Perform action.
+ result = creative_wrapper_service.performCreativeWrapperAction(
+ {'xsi_type': 'DeactivateCreativeWrappers'}, statement.ToStatement())
+ if result and int(result['numChanges']) > 0:
+ creative_wrappers_deactivated += int(result['numChanges'])
+ statement.offset += statement.limit
+ else:
+ break
+
+ # Display results.
+ if creative_wrappers_deactivated > 0:
+ print('Number of creative wrappers deactivated: %s' %
+ creative_wrappers_deactivated)
+ else:
+ print('No creative wrappers were deactivated.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, LABEL_ID)
diff --git a/examples/ad_manager/v202205/creative_wrapper_service/get_active_creative_wrappers.py b/examples/ad_manager/v202205/creative_wrapper_service/get_active_creative_wrappers.py
new file mode 100755
index 00000000..8c8ea32c
--- /dev/null
+++ b/examples/ad_manager/v202205/creative_wrapper_service/get_active_creative_wrappers.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all active creative wrappers.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ creative_wrapper_service = client.GetService(
+ 'CreativeWrapperService', version='v202205')
+ # Create a statement to select creative wrappers.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('status = :status')
+ .WithBindVariable('status', 'ACTIVE'))
+
+ # Retrieve a small amount of creative wrappers at a time, paging
+ # through until all creative wrappers have been retrieved.
+ while True:
+ response = creative_wrapper_service.getCreativeWrappersByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for creative_wrapper in response['results']:
+ # Print out some information for each creative wrapper.
+ print('Creative wrapper with ID "%d" and label ID "%d" was found.\n' %
+ (creative_wrapper['id'], creative_wrapper['labelId']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/creative_wrapper_service/get_all_creative_wrappers.py b/examples/ad_manager/v202205/creative_wrapper_service/get_all_creative_wrappers.py
new file mode 100755
index 00000000..cec9eab3
--- /dev/null
+++ b/examples/ad_manager/v202205/creative_wrapper_service/get_all_creative_wrappers.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all creative wrappers.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ creative_wrapper_service = client.GetService(
+ 'CreativeWrapperService', version='v202205')
+
+ # Create a statement to select creative wrappers.
+ statement = ad_manager.StatementBuilder(version='v202205')
+
+ # Retrieve a small amount of creative wrappers at a time, paging
+ # through until all creative wrappers have been retrieved.
+ while True:
+ response = creative_wrapper_service.getCreativeWrappersByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for creative_wrapper in response['results']:
+ # Print out some information for each creative wrapper.
+ print('Creative wrapper with ID "%d" and label id "%d" was found.\n' %
+ (creative_wrapper['id'], creative_wrapper['labelId']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/creative_wrapper_service/update_creative_wrappers.py b/examples/ad_manager/v202205/creative_wrapper_service/update_creative_wrappers.py
new file mode 100755
index 00000000..fec33eb1
--- /dev/null
+++ b/examples/ad_manager/v202205/creative_wrapper_service/update_creative_wrappers.py
@@ -0,0 +1,73 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates a creative wrapper to the 'OUTER' wrapping order.
+
+To determine which creative wrappers exist, run get_all_creative_wrappers.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the creative wrapper to update.
+CREATIVE_WRAPPER_ID = 'INSERT_CREATIVE_WRAPPER_ID_HERE'
+
+
+def main(client, creative_wrapper_id):
+ # Initialize appropriate service.
+ creative_wrapper_service = client.GetService('CreativeWrapperService',
+ version='v202205')
+
+ # Create statement to get a creative wrapper by ID.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('id = :creativeWrapperId')
+ .WithBindVariable('creativeWrapperId',
+ int(creative_wrapper_id)))
+
+ # Get creative wrappers.
+ response = creative_wrapper_service.getCreativeWrappersByStatement(
+ statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ updated_creative_wrappers = []
+ for creative_wrapper in response['results']:
+ creative_wrapper['ordering'] = 'OUTER'
+ updated_creative_wrappers.append(creative_wrapper)
+
+ # Update the creative wrappers on the server.
+ creative_wrappers = creative_wrapper_service.updateCreativeWrappers(
+ updated_creative_wrappers)
+
+ # Display results.
+ for creative_wrapper in creative_wrappers:
+ print(('Creative wrapper with ID "%s" and wrapping order "%s" '
+ 'was updated.') % (creative_wrapper['id'],
+ creative_wrapper['ordering']))
+ else:
+ print('No creative wrappers found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CREATIVE_WRAPPER_ID)
diff --git a/examples/ad_manager/v202205/custom_field_service/__init__.py b/examples/ad_manager/v202205/custom_field_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202205/custom_field_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202205/custom_field_service/create_custom_field_options.py b/examples/ad_manager/v202205/custom_field_service/create_custom_field_options.py
new file mode 100755
index 00000000..dfa7f7e7
--- /dev/null
+++ b/examples/ad_manager/v202205/custom_field_service/create_custom_field_options.py
@@ -0,0 +1,67 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example creates custom field options for a drop-down custom field.
+
+Once created, custom field options can be found under the options fields of the
+drop-down custom field and they cannot be deleted. To determine which custom
+fields exist, run get_all_custom_fields.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the drop-down custom field to create options for.
+CUSTOM_FIELD_ID = 'INSERT_DROP_DOWN_CUSTOM_FIELD_ID_HERE'
+
+
+def main(client, custom_field_id):
+ # Initialize appropriate service.
+ custom_field_service = client.GetService(
+ 'CustomFieldService', version='v202205')
+
+ # Create custom field options.
+ custom_field_options = [
+ {
+ 'displayName': 'Approved',
+ 'customFieldId': custom_field_id
+ },
+ {
+ 'displayName': 'Unapproved',
+ 'customFieldId': custom_field_id
+ }
+ ]
+
+ # Add custom field options.
+ custom_field_options = custom_field_service.createCustomFieldOptions(
+ custom_field_options)
+
+ # Display results.
+ for custom_field_option in custom_field_options:
+ print('Custom field option with ID "%s" and name "%s" was created.'
+ % (custom_field_option['id'], custom_field_option['displayName']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CUSTOM_FIELD_ID)
diff --git a/examples/ad_manager/v202205/custom_field_service/create_custom_fields.py b/examples/ad_manager/v202205/custom_field_service/create_custom_fields.py
new file mode 100755
index 00000000..5139287d
--- /dev/null
+++ b/examples/ad_manager/v202205/custom_field_service/create_custom_fields.py
@@ -0,0 +1,66 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example creates custom fields.
+
+To determine which custom fields exist, run get_all_custom_fields.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ custom_field_service = client.GetService(
+ 'CustomFieldService', version='v202205')
+
+ # Create custom field objects.
+ custom_fields = [
+ {
+ 'name': 'Customer comments #%s' % uuid.uuid4(),
+ 'entityType': 'LINE_ITEM',
+ 'dataType': 'STRING',
+ 'visibility': 'FULL'
+ }, {
+ 'name': 'Internal approval status #%s' % uuid.uuid4(),
+ 'entityType': 'LINE_ITEM',
+ 'dataType': 'DROP_DOWN',
+ 'visibility': 'FULL'
+ }
+ ]
+
+ # Add custom fields.
+ custom_fields = custom_field_service.createCustomFields(custom_fields)
+
+ # Display results.
+ for custom_field in custom_fields:
+ print('Custom field with ID "%s" and name "%s" was created.'
+ % (custom_field['id'], custom_field['name']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/ad_manager/v202205/custom_field_service/deactivate_all_line_item_custom_fields.py
new file mode 100755
index 00000000..1d561444
--- /dev/null
+++ b/examples/ad_manager/v202205/custom_field_service/deactivate_all_line_item_custom_fields.py
@@ -0,0 +1,73 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example deactivates all active line items custom fields.
+
+To determine which custom fields exist, run get_all_custom_fields.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ custom_field_service = client.GetService(
+ 'CustomFieldService', version='v202205')
+
+ # Create statement to select only active custom fields that apply to
+ # line items.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('entityType = :entityType and isActive = :isActive')
+ .WithBindVariable('entityType', 'LINE_ITEM')
+ .WithBindVariable('isActive', True))
+
+ custom_fields_deactivated = 0
+
+ # Get custom fields by statement.
+ while True:
+ response = custom_field_service.getCustomFieldsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ # Display results.
+ for custom_field in response['results']:
+ print('Custom field with ID "%s" and name "%s" will'
+ ' be deactivated.' % (custom_field['id'], custom_field['name']))
+ result = custom_field_service.performCustomFieldAction(
+ {'xsi_type': 'DeactivateCustomFields'}, statement.ToStatement())
+ if result and int(result['numChanges']) > 0:
+ custom_fields_deactivated += int(result['numChanges'])
+ statement.offset += statement.limit
+ else:
+ break
+
+ if custom_fields_deactivated > 0:
+ print('Number of custom fields deactivated: %s' % custom_fields_deactivated)
+ else:
+ print('No custom fields were deactivated.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/custom_field_service/get_all_custom_fields.py b/examples/ad_manager/v202205/custom_field_service/get_all_custom_fields.py
new file mode 100755
index 00000000..f94f36d5
--- /dev/null
+++ b/examples/ad_manager/v202205/custom_field_service/get_all_custom_fields.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all custom fields.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ custom_field_service = client.GetService(
+ 'CustomFieldService', version='v202205')
+
+ # Create a statement to select custom fields.
+ statement = ad_manager.StatementBuilder(version='v202205')
+
+ # Retrieve a small amount of custom fields at a time, paging
+ # through until all custom fields have been retrieved.
+ while True:
+ response = custom_field_service.getCustomFieldsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for custom_field in response['results']:
+ # Print out some information for each custom field.
+ print('Custom field with ID "%d" and name "%s" was found.\n' %
+ (custom_field['id'], custom_field['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/custom_field_service/get_custom_fields_for_line_items.py b/examples/ad_manager/v202205/custom_field_service/get_custom_fields_for_line_items.py
new file mode 100755
index 00000000..04eb5921
--- /dev/null
+++ b/examples/ad_manager/v202205/custom_field_service/get_custom_fields_for_line_items.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all custom fields that can be applied to line items.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ custom_field_service = client.GetService(
+ 'CustomFieldService', version='v202205')
+ # Create a statement to select custom fields.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('entityType = :entityType')
+ .WithBindVariable('entityType', 'LINE_ITEM'))
+
+ # Retrieve a small amount of custom fields at a time, paging
+ # through until all custom fields have been retrieved.
+ while True:
+ response = custom_field_service.getCustomFieldsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for custom_field in response['results']:
+ # Print out some information for each custom field.
+ print('Custom field with ID "%d" and name "%s" was found.\n' %
+ (custom_field['id'], custom_field['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/custom_field_service/set_line_item_custom_field_value.py b/examples/ad_manager/v202205/custom_field_service/set_line_item_custom_field_value.py
new file mode 100755
index 00000000..198c8632
--- /dev/null
+++ b/examples/ad_manager/v202205/custom_field_service/set_line_item_custom_field_value.py
@@ -0,0 +1,139 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example sets custom field values on a line item.
+
+To determine which custom fields exist, run get_all_custom_fields.py.
+To determine which line item exist, run get_all_line_items.py.
+To create custom field options, run create_custom_field_options.py
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the custom fields, custom field option, and line item.
+CUSTOM_FIELD_ID = 'INSERT_CUSTOM_FIELD_ID_HERE'
+DROP_DOWN_CUSTOM_FIELD_ID = 'INSERT_DROP_DOWN_CUSTOM_FIELD_ID_HERE'
+CUSTOM_FIELD_OPTION_ID = 'INSERT_CUSTOM_FIELD_OPTION_ID_HERE'
+LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
+
+
+def main(client, custom_field_id, drop_down_custom_field_id,
+ custom_field_option_id, line_item_id):
+ # Initialize appropriate services.
+ custom_field_service = client.GetService(
+ 'CustomFieldService', version='v202205')
+
+ line_item_service = client.GetService('LineItemService', version='v202205')
+
+ # Create statement to get a custom field.
+ custom_field_statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('id = :customFieldId')
+ .WithBindVariable('customFieldId', custom_field_id)
+ .Limit(1))
+
+ # Get custom field.
+ custom_field = custom_field_service.getCustomFieldsByStatement(
+ custom_field_statement.ToStatement())['results'][0]
+
+ # Create statement to get a drop down custom field.
+ drop_down_custom_field_statement = (
+ ad_manager.StatementBuilder(version='v202205')
+ .Where('id = :dropDownCustomFieldId')
+ .WithBindVariable('dropDownCustomFieldId', drop_down_custom_field_id)
+ .Limit(1))
+
+ # Get drop-down custom field.
+ drop_down_custom_field = custom_field_service.getCustomFieldsByStatement(
+ drop_down_custom_field_statement.ToStatement())['results'][0]
+
+ # Create statement to get a line item.
+ line_item_statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('id = :lineItemId')
+ .WithBindVariable('lineItemId', line_item_id)
+ .Limit(1))
+
+ # Get line item.
+ line_item = line_item_service.getLineItemsByStatement(
+ line_item_statement.ToStatement())['results'][0]
+
+ if custom_field and line_item:
+ # Create custom field values.
+ custom_field_value = {
+ 'customFieldId': custom_field['id'],
+ 'xsi_type': 'CustomFieldValue',
+ 'value': {
+ 'xsi_type': 'TextValue',
+ 'value': 'Custom field value'
+ }
+ }
+
+ drop_down_custom_field_value = {
+ 'customFieldId': drop_down_custom_field['id'],
+ 'xsi_type': 'DropDownCustomFieldValue',
+ 'customFieldOptionId': custom_field_option_id,
+ }
+
+ custom_field_values = [custom_field_value, drop_down_custom_field_value]
+
+ old_custom_field_values = []
+ if 'customFieldValues' in line_item:
+ old_custom_field_values = line_item['customFieldValues']
+
+ # Only add existing custom field values for different custom fields than the
+ # ones you are setting.
+ for old_custom_field_value in old_custom_field_values:
+ if (old_custom_field_value['customFieldId'] !=
+ custom_field_value['customFieldId']
+ and old_custom_field_value['customFieldId'] !=
+ drop_down_custom_field_value['customFieldId']):
+ custom_field_values.append(old_custom_field_value)
+
+ line_item['customFieldValues'] = custom_field_values
+
+ # Update the line item on the server.
+ line_items = line_item_service.updateLineItems([line_item])
+
+ # Display results.
+ for line_item in line_items:
+ custom_field_value_strings = []
+ for value in line_item['customFieldValues']:
+ if ad_manager.AdManagerClassType(value) == 'CustomFieldValue':
+ custom_field_value_string = (
+ '{ID: "%s", value: "%s"}'
+ % (value['customFieldId'], value['value']['value']))
+ elif ad_manager.AdManagerClassType(value) == 'DropDownCustomFieldValue':
+ custom_field_value_string = (
+ '{ID: "%s", custom field option ID: "%s"}'
+ % (value['customFieldId'], value['customFieldOptionId']))
+ custom_field_value_strings.append(custom_field_value_string)
+ print('Line item with ID "%s" set with custom field values %s.'
+ % (line_item['id'], ','.join(custom_field_value_strings)))
+ else:
+ print('Line item or custom field not found.')
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CUSTOM_FIELD_ID, DROP_DOWN_CUSTOM_FIELD_ID,
+ CUSTOM_FIELD_OPTION_ID, LINE_ITEM_ID)
diff --git a/examples/ad_manager/v202205/custom_field_service/update_custom_fields.py b/examples/ad_manager/v202205/custom_field_service/update_custom_fields.py
new file mode 100755
index 00000000..53ae0f36
--- /dev/null
+++ b/examples/ad_manager/v202205/custom_field_service/update_custom_fields.py
@@ -0,0 +1,70 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example updates custom field descriptions.
+
+To determine which custom fields exist, run get_all_custom_fields.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the custom field to update.
+CUSTOM_FIELD_ID = 'INSERT_CUSTOM_FIELD_ID_HERE'
+
+
+def main(client, custom_field_id):
+ # Initialize appropriate service.
+ custom_field_service = client.GetService(
+ 'CustomFieldService', version='v202205')
+
+ # Create statement to get a custom field.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('id = :customFieldId')
+ .WithBindVariable('customFieldId', int(custom_field_id)))
+
+ # Get custom field.
+ custom_fields = custom_field_service.getCustomsFieldByStatement(
+ statement.ToStatement())
+
+ if custom_fields:
+ for custom_field in custom_fields:
+ custom_field['description'] += ' Updated.'
+
+ # Update the custom field on the server.
+ custom_fields = custom_field_service.updateCustomFields(custom_fields)
+
+ # Display results.
+ for custom_field in custom_fields:
+ print(('Custom field with ID "%s", name "%s", and '
+ 'description "%s" was updated.')
+ % (custom_field['id'], custom_field['name'],
+ custom_field['description']))
+ else:
+ print('No custom fields found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CUSTOM_FIELD_ID)
diff --git a/examples/ad_manager/v202205/custom_targeting_service/__init__.py b/examples/ad_manager/v202205/custom_targeting_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202205/custom_targeting_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202205/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/ad_manager/v202205/custom_targeting_service/create_custom_targeting_keys_and_values.py
new file mode 100755
index 00000000..66ba8312
--- /dev/null
+++ b/examples/ad_manager/v202205/custom_targeting_service/create_custom_targeting_keys_and_values.py
@@ -0,0 +1,132 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example creates new custom targeting keys and values.
+
+To determine which custom targeting keys and values exist, run
+get_all_custom_targeting_keys_and_values.py. To target these custom targeting
+keys and values, run target_custom_criteria_example.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ custom_targeting_service = client.GetService(
+ 'CustomTargetingService', version='v202205')
+
+ # Create custom targeting key objects.
+ keys = [
+ {
+ 'displayName': 'gender',
+ 'name': 'g',
+ 'type': 'PREDEFINED'
+ },
+ {
+ 'displayName': 'car model',
+ 'name': 'c',
+ 'type': 'FREEFORM'
+ },
+ # Add predefined key that may be use for content targeting.
+ {
+ 'displayName': 'genre',
+ 'name': 'genre',
+ 'type': 'PREDEFINED'
+ }
+ ]
+
+ # Add custom targeting keys.
+ keys = custom_targeting_service.createCustomTargetingKeys(keys)
+
+ # Display results.
+ if keys:
+ for key in keys:
+ print('A custom targeting key with id "%s", name "%s", and display '
+ 'name "%s" was created.' % (key['id'], key['name'],
+ key['displayName']))
+ else:
+ print('No keys were created.')
+
+ # Create custom targeting value objects.
+ values = [
+ {
+ 'customTargetingKeyId': keys[0]['id'],
+ 'displayName': 'male',
+ # Name is set to 1 so that the actual name can be hidden from website
+ # users.
+ 'name': '1',
+ 'matchType': 'EXACT'
+ },
+ {
+ 'customTargetingKeyId': keys[0]['id'],
+ 'displayName': 'female',
+ # Name is set to 2 so that the actual name can be hidden from website
+ # users.
+ 'name': '2',
+ 'matchType': 'EXACT'
+ },
+ {
+ 'customTargetingKeyId': keys[1]['id'],
+ 'displayName': 'honda civic',
+ 'name': 'honda civic',
+ 'matchType': 'EXACT'
+ },
+ {
+ 'customTargetingKeyId': keys[1]['id'],
+ 'displayName': 'toyota',
+ 'name': 'toyota',
+ 'matchType': 'EXACT'
+ },
+ {
+ 'customTargetingKeyId': keys[2]['id'],
+ 'displayName': 'comedy',
+ 'name': 'comedy',
+ 'matchType': 'EXACT'
+ },
+ {
+ 'customTargetingKeyId': keys[2]['id'],
+ 'displayName': 'drama',
+ 'name': 'drama',
+ 'matchType': 'EXACT'
+ }
+ ]
+
+ # Add custom targeting values.
+ values = custom_targeting_service.createCustomTargetingValues(values)
+
+ # Display results.
+ if values:
+ for value in values:
+ print('A custom targeting value with id "%s", belonging to key with id'
+ ' "%s", name "%s", and display name "%s" was created.'
+ % (value['id'], value['customTargetingKeyId'], value['name'],
+ value['displayName']))
+ else:
+ print('No values were created.')
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/custom_targeting_service/delete_custom_targeting_keys.py b/examples/ad_manager/v202205/custom_targeting_service/delete_custom_targeting_keys.py
new file mode 100755
index 00000000..7bc74043
--- /dev/null
+++ b/examples/ad_manager/v202205/custom_targeting_service/delete_custom_targeting_keys.py
@@ -0,0 +1,77 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example deletes a custom targeting key by its name.
+
+To determine which custom targeting keys exist, run
+get_all_custom_targeting_keys_and_values.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+KEY_NAME = 'INSERT_CUSTOM_TARGETING_KEY_NAME_HERE'
+
+
+def main(client, key_name):
+ # Initialize appropriate service.
+ custom_targeting_service = client.GetService(
+ 'CustomTargetingService', version='v202205')
+
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('name = :name')
+ .WithBindVariable('name', key_name))
+
+ deleted_custom_targeting_keys = 0
+
+ # Get custom targeting keys.
+ while True:
+ response = custom_targeting_service.getCustomTargetingKeysByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ key_ids = [str(key['id']) for key in response['results']]
+ action = {'xsi_type': 'DeleteCustomTargetingKeys'}
+ key_statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('id IN (%s)' % ', '.join(key_ids)))
+
+ # Delete custom targeting keys.
+ result = custom_targeting_service.performCustomTargetingKeyAction(
+ action, key_statement.ToStatement())
+
+ if result and int(result['numChanges']) > 0:
+ deleted_custom_targeting_keys += int(result['numChanges'])
+ statement.offset += statement.limit
+ else:
+ break
+
+ if deleted_custom_targeting_keys > 0:
+ print('Number of custom targeting keys deleted: %s'
+ % deleted_custom_targeting_keys)
+ else:
+ print('No custom targeting keys were deleted.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, KEY_NAME)
diff --git a/examples/ad_manager/v202205/custom_targeting_service/delete_custom_targeting_values.py b/examples/ad_manager/v202205/custom_targeting_service/delete_custom_targeting_values.py
new file mode 100755
index 00000000..9728e755
--- /dev/null
+++ b/examples/ad_manager/v202205/custom_targeting_service/delete_custom_targeting_values.py
@@ -0,0 +1,77 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Deletes custom targeting values for a given custom targeting key.
+
+To determine which custom targeting keys and values exist, run
+get_all_custom_targeting_keys_and_values.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'
+
+
+def main(client, key_id):
+ # Initialize appropriate service.
+ custom_targeting_service = client.GetService(
+ 'CustomTargetingService', version='v202205')
+
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('customTargetingKeyId = :keyId')
+ .WithBindVariable('keyId', key_id))
+
+ deleted_custom_targeting_values = 0
+
+ # Get custom targeting values.
+ while True:
+ response = custom_targeting_service.getCustomTargetingValuesByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ value_ids = [str(value['id']) for value in response['results']]
+ action = {'xsi_type': 'DeleteCustomTargetingValues'}
+ value_statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('customTargetingKeyId = :keyId '
+ 'AND id IN (%s)' % ', '.join(value_ids))
+ .WithBindVariable('keyId', key_id))
+
+ # Delete custom targeting values.
+ result = custom_targeting_service.performCustomTargetingValueAction(
+ action, value_statement.ToStatement())
+ if result and int(result['numChanges']) > 0:
+ deleted_custom_targeting_values += int(result['numChanges'])
+ statement.offset += statement.limit
+ else:
+ break
+
+ if deleted_custom_targeting_values > 0:
+ print('Number of custom targeting values deleted: %s'
+ % deleted_custom_targeting_values)
+ else:
+ print('No custom targeting values were deleted.')
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, KEY_ID)
diff --git a/examples/ad_manager/v202205/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/ad_manager/v202205/custom_targeting_service/get_all_custom_targeting_keys_and_values.py
new file mode 100755
index 00000000..ec23c3ac
--- /dev/null
+++ b/examples/ad_manager/v202205/custom_targeting_service/get_all_custom_targeting_keys_and_values.py
@@ -0,0 +1,72 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all custom targeting keys and values.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ custom_targeting_service = client.GetService(
+ 'CustomTargetingService', version='v202205')
+
+ # Create statement to get all targeting keys.
+ targeting_key_statement = ad_manager.StatementBuilder(version='v202205')
+
+ all_keys = []
+
+ # Get custom targeting keys by statement.
+ while True:
+ response = custom_targeting_service.getCustomTargetingKeysByStatement(
+ targeting_key_statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ all_keys.extend(response['results'])
+ targeting_key_statement.offset += targeting_key_statement.limit
+ else:
+ break
+
+ if all_keys:
+ # Create a statement to select custom targeting values.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('customTargetingKeyId IN (%s)' %
+ ', '.join([str(key['id']) for key in all_keys])))
+
+ # Retrieve a small amount of custom targeting values at a time, paging
+ # through until all custom targeting values have been retrieved.
+ while True:
+ response = custom_targeting_service.getCustomTargetingValuesByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for custom_targeting_value in response['results']:
+ # Print out some information for each custom targeting value.
+ print('Custom targeting value with ID "%d", name "%s", display name '
+ '"%s", and custom targeting key ID "%d" was found.\n' %
+ (custom_targeting_value['id'], custom_targeting_value['name'],
+ custom_targeting_value['displayName'],
+ custom_targeting_value['customTargetingKeyId']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/ad_manager/v202205/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py
new file mode 100755
index 00000000..cf2da216
--- /dev/null
+++ b/examples/ad_manager/v202205/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py
@@ -0,0 +1,74 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all custom targeting keys and values.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ custom_targeting_service = client.GetService(
+ 'CustomTargetingService', version='v202205')
+
+ # Create statement to get targeting keys for predefined values.
+ targeting_key_statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('type = :type')
+ .WithBindVariable('type', 'PREDEFINED'))
+
+ all_keys = []
+
+ # Get custom targeting keys by statement.
+ while True:
+ response = custom_targeting_service.getCustomTargetingKeysByStatement(
+ targeting_key_statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ all_keys.extend(response['results'])
+ targeting_key_statement.offset += targeting_key_statement.limit
+ else:
+ break
+
+ if all_keys:
+ # Create a statement to select custom targeting values.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('customTargetingKeyId IN (:ids)')
+ .WithBindVariable('ids', [key['id'] for key in all_keys]))
+
+ # Retrieve a small amount of custom targeting values at a time, paging
+ # through until all custom targeting values have been retrieved.
+ while True:
+ response = custom_targeting_service.getCustomTargetingValuesByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for custom_targeting_value in response['results']:
+ # Print out some information for each custom targeting value.
+ print('Custom targeting value with ID "%d", name "%s", display name '
+ '"%s", and custom targeting key ID "%d" was found.\n' %
+ (custom_targeting_value['id'], custom_targeting_value['name'],
+ custom_targeting_value['displayName'],
+ custom_targeting_value['customTargetingKeyId']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/custom_targeting_service/update_custom_targeting_keys.py b/examples/ad_manager/v202205/custom_targeting_service/update_custom_targeting_keys.py
new file mode 100755
index 00000000..08cd59f5
--- /dev/null
+++ b/examples/ad_manager/v202205/custom_targeting_service/update_custom_targeting_keys.py
@@ -0,0 +1,67 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example updates the display name of a single custom targeting key.
+
+To determine which custom targeting keys exist, run
+get_all_custom_targeting_keys_and_values.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'
+
+
+def main(client, key_id):
+ # Initialize appropriate service.
+ custom_targeting_service = client.GetService(
+ 'CustomTargetingService', version='v202205')
+
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('id = :keyId')
+ .WithBindVariable('keyId', int(key_id))
+ .Limit(1))
+
+ # Get custom targeting keys by statement.
+ response = custom_targeting_service.getCustomTargetingKeysByStatement(
+ statement.ToStatement())
+
+ # Update each local custom targeting key object by changing its display name.
+ if 'results' in response and len(response['results']):
+ updated_keys = []
+ for key in response['results']:
+ if not key['displayName']:
+ key['displayName'] = key['name']
+ key['displayName'] += ' (Deprecated)'
+ updated_keys.append(key)
+ keys = custom_targeting_service.updateCustomTargetingKeys(updated_keys)
+
+ # Display results.
+ if keys:
+ for key in keys:
+ print('Custom targeting key with id "%s", name "%s", display name '
+ '"%s", and type "%s" was updated.'
+ % (key['id'], key['name'], key['displayName'], key['type']))
+ else:
+ print('No custom targeting keys were found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CUSTOM_TARGETING_KEY_ID)
diff --git a/examples/ad_manager/v202205/custom_targeting_service/update_custom_targeting_values.py b/examples/ad_manager/v202205/custom_targeting_service/update_custom_targeting_values.py
new file mode 100755
index 00000000..9eafeb34
--- /dev/null
+++ b/examples/ad_manager/v202205/custom_targeting_service/update_custom_targeting_values.py
@@ -0,0 +1,71 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Updates name of custom targeting values belonging to a custom targeting key.
+
+To determine which custom targeting keys exist, run
+get_all_custom_targeting_keys_and_values.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'
+
+
+def main(client, key_id):
+ # Initialize appropriate service.
+ custom_targeting_service = client.GetService(
+ 'CustomTargetingService', version='v202205')
+
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('customTargetingKeyId = :keyId')
+ .WithBindVariable('keyId', int(key_id)))
+
+ while True:
+ # Get custom targeting values by statement.
+ response = custom_targeting_service.getCustomTargetingValuesByStatement(
+ statement.ToStatement())
+
+ # Update each local custom targeting value object by changing its name.
+ if 'results' in response and len(response['results']):
+ updated_values = []
+ for value in response['results']:
+ if not value['displayName']:
+ value['displayName'] = value['name']
+ value['displayName'] += ' (Deprecated)'
+ updated_values.append(value)
+ values = custom_targeting_service.updateCustomTargetingValues(
+ updated_values)
+
+ # Display results.
+ for value in values:
+ print('Custom targeting value with id "%s", name "%s", and display'
+ ' name "%s" was updated.'
+ % (value['id'], value['name'], value['displayName']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ if response['totalResultSetSize'] == 0:
+ print('No custom targeting values were updated.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CUSTOM_TARGETING_KEY_ID)
diff --git a/examples/ad_manager/v202205/forecast_service/get_availability_forecast.py b/examples/ad_manager/v202205/forecast_service/get_availability_forecast.py
new file mode 100755
index 00000000..ae251195
--- /dev/null
+++ b/examples/ad_manager/v202205/forecast_service/get_availability_forecast.py
@@ -0,0 +1,251 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets a forecast for a prospective line item.
+
+The prospective line item targets the entire network. The targeting can be
+modified to determine forecasts for other criteria such as custom criteria
+targeting (in addition to targeting the whole network). See
+create_line_items.py for an example of how to create more complex targeting.
+
+"""
+
+
+import datetime
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+import pytz
+
+# Set the ID of the advertiser (company) to forecast for. Setting an advertiser
+# will cause the forecast to apply the appropriate unified blocking rules.
+ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE'
+
+
+def main(client, advertiser_id):
+ # Initialize appropriate service.
+ forecast_service = client.GetService('ForecastService', version='v202205')
+ network_service = client.GetService('NetworkService', version='v202205')
+
+ # get the root ad unit ID to target the entire network.
+ root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId']
+
+ now_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York'))
+ end_datetime = now_datetime + datetime.timedelta(days=5)
+
+ # Create prospective line item.
+ line_item = {
+ 'targeting': {
+ 'inventoryTargeting': {
+ 'targetedAdUnits': [
+ {
+ 'includeDescendants': True,
+ 'adUnitId': root_ad_unit_id,
+ }
+ ]
+ }
+ },
+ 'creativePlaceholders': [
+ {
+ 'size': {
+ 'width': '300',
+ 'height': '250'
+ },
+ 'isAmpOnly': True,
+ },
+ {
+ 'size': {
+ 'width': '120',
+ 'height': '600'
+ }
+ }
+ ],
+ 'lineItemType': 'SPONSORSHIP',
+ 'startDateTimeType': 'IMMEDIATELY',
+ 'endDateTime': end_datetime,
+ 'costType': 'CPM',
+ 'costPerUnit': {
+ 'currencyCode': 'USD',
+ 'microAmount': '2000000'
+ },
+ 'primaryGoal': {
+ 'units': '50',
+ 'unitType': 'IMPRESSIONS',
+ 'goalType': 'DAILY'
+ },
+ 'contractedUnitsBought': '100',
+ 'creativeRotationType': 'EVEN',
+ 'discountType': 'PERCENTAGE',
+ }
+
+ prospective_line_item = {
+ 'lineItem': line_item,
+ 'advertiserId': advertiser_id
+ }
+
+ # Set forecasting options.
+ forecast_options = {
+ 'includeContendingLineItems': True,
+ # The field includeTargetingCriteriaBreakdown can only be set if
+ # breakdowns are not manually specified.
+ # 'includeTargetingCriteriaBreakdown': True,
+ 'breakdown': {
+ 'timeWindows': [
+ now_datetime,
+ now_datetime + datetime.timedelta(days=1),
+ now_datetime + datetime.timedelta(days=2),
+ now_datetime + datetime.timedelta(days=3),
+ now_datetime + datetime.timedelta(days=4),
+ end_datetime
+ ],
+ 'targets': [
+ {
+ # Optional, the name field is only used to identify this
+ # breakdown in the response.
+ 'name': 'United States',
+ 'targeting': {
+ 'inventoryTargeting': {
+ 'targetedAdUnits': [
+ {
+ 'includeDescendants': True,
+ 'adUnitId': root_ad_unit_id,
+ }
+ ]
+ },
+ 'geoTargeting': {
+ 'targetedLocations': [
+ {
+ 'id': '2840',
+ 'displayName': 'US'
+ }
+ ]
+ }
+ }
+ },
+ {
+ # Optional, the name field is only used to identify this
+ # breakdown in the response.
+ 'name': 'Geneva',
+ 'targeting': {
+ 'inventoryTargeting': {
+ 'targetedAdUnits': [
+ {
+ 'includeDescendants': True,
+ 'adUnitId': root_ad_unit_id,
+ }
+ ]
+ },
+ 'geoTargeting': {
+ 'targetedLocations': [
+ {
+ 'id': '20133',
+ 'displayName': 'Geneva'
+ }
+ ]
+ }
+ }
+ }
+ ]
+ }
+ }
+
+ # Get forecast.
+ forecast = forecast_service.getAvailabilityForecast(
+ prospective_line_item, forecast_options)
+ matched = forecast['matchedUnits']
+ available = forecast['availableUnits']
+ possible = forecast['possibleUnits'] if 'possibleUnits' in forecast else None
+ unit_type = forecast['unitType'].lower()
+
+ available_percent_overall, possible_percent_overall = CalculateForecastStats(
+ matched, available, possible)
+
+ contending_line_items = getattr(forecast, 'contendingLineItems', [])
+
+ # Display results.
+ print('%s %s matched overall.' % (matched, unit_type))
+ print('%s%% %s available overall.' % (available_percent_overall, unit_type))
+ print('%d contending line items overall.' % len(contending_line_items))
+ if possible:
+ print('%s%% %s possible overall.' % (possible_percent_overall, unit_type))
+
+ if 'breakdowns' in forecast and len(forecast['breakdowns']):
+ for breakdown in forecast['breakdowns']:
+ print('For breakdown time period %s - %s:' % (
+ FormatSOAPDateTime(breakdown['startTime']),
+ FormatSOAPDateTime(breakdown['endTime'])))
+ for breakdown_entry in breakdown['breakdownEntries']:
+ matched = breakdown_entry['forecast']['matched']
+ available = breakdown_entry['forecast']['available']
+ possible = (breakdown_entry['forecast']['possible']
+ if 'possible' in breakdown_entry['forecast'] else None)
+ name = breakdown_entry['name'] if 'name' in breakdown_entry else None
+ if name:
+ print('\tFor targeting breakdown named \'%s\'' % name)
+ available_percent, possible_percent = CalculateForecastStats(
+ matched, available, possible)
+ print('\t\t%s %s matched.' % (matched, unit_type))
+ print('\t\t%s%% %s available.' % (available_percent, unit_type))
+ if possible:
+ print('\t\t%s%% %s possible.' % (possible_percent, unit_type))
+
+
+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'],
+ value['hour'], value['minute'], value['second'], value['timeZoneId'])
+
+
+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 that are available and possible.
+ """
+ if matched > 0:
+ available_percent = (float(available) / matched) * 100.
+ else:
+ available_percent = 0
+
+ if possible is not None:
+ if matched > 0:
+ possible_percent = (possible/float(matched)) * 100.
+ else:
+ possible_percent = 0
+ else:
+ possible_percent = None
+
+ return available_percent, possible_percent
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ADVERTISER_ID)
diff --git a/examples/ad_manager/v202205/forecast_service/get_availability_forecast_for_line_item.py b/examples/ad_manager/v202205/forecast_service/get_availability_forecast_for_line_item.py
new file mode 100755
index 00000000..41a89401
--- /dev/null
+++ b/examples/ad_manager/v202205/forecast_service/get_availability_forecast_for_line_item.py
@@ -0,0 +1,67 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example gets an availability forecast for an existing line item.
+
+To determine which line items exist, run get_all_line_items.py.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the line item to get a forecast for.
+LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
+
+
+def main(client, line_item_id):
+ # Initialize appropriate service.
+ forecast_service = client.GetService('ForecastService', version='v202205')
+
+ # Set forecasting options.
+ forecast_options = {
+ 'includeContendingLineItems': True,
+ 'includeTargetingCriteriaBreakdown': True,
+ }
+
+ # Get forecast for line item.
+ forecast = forecast_service.getAvailabilityForecastById(
+ line_item_id, forecast_options)
+ matched = int(forecast['matchedUnits'])
+ available_units = int(forecast['availableUnits'])
+
+ if matched > 0:
+ available_percent = (float(available_units) / matched) * 100.
+ else:
+ available_percent = 0
+
+ contending_line_items = getattr(forecast, 'contentingLineItems', [])
+
+ # Display results.
+ print('%s %s matched.' % (matched, forecast['unitType'].lower()))
+ print('%s%% %s available.' % (
+ available_percent, forecast['unitType'].lower()))
+ print('%d contending line items.' % len(contending_line_items))
+
+ if 'possibleUnits' in forecast and matched:
+ possible_percent = (int(forecast['possibleUnits'])/float(matched)) * 100.
+ print('%s%% %s possible' % (possible_percent, forecast['unitType'].lower()))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, LINE_ITEM_ID)
diff --git a/examples/ad_manager/v202205/forecast_service/get_delivery_forecast_for_line_items.py b/examples/ad_manager/v202205/forecast_service/get_delivery_forecast_for_line_items.py
new file mode 100755
index 00000000..eb9143aa
--- /dev/null
+++ b/examples/ad_manager/v202205/forecast_service/get_delivery_forecast_for_line_items.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example gets a delivery forecast for two existing line items.
+
+To determine which line items exist, run get_all_line_items.py.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the line items to get forecasts for.
+LINE_ITEM_ID_1 = 'INSERT_LINE_ITEM_1_ID_HERE'
+LINE_ITEM_ID_2 = 'INSERT_LINE_ITEM_2_ID_HERE'
+
+
+def main(client, line_item_id1, line_item_id2):
+ # Initialize appropriate service.
+ forecast_service = client.GetService('ForecastService', version='v202205')
+
+ # Get forecast for line item.
+ forecast = forecast_service.getDeliveryForecastByIds(
+ [line_item_id1, line_item_id2], {'ignoredLineItemIds': []})
+
+ for single_forecast in forecast['lineItemDeliveryForecasts']:
+ unit_type = single_forecast['unitType']
+ print('Forecast for line item %d:\n\t%d %s matched\n\t%d %s delivered\n\t'
+ '%d %s predicted\n' % (
+ single_forecast['lineItemId'], single_forecast['matchedUnits'],
+ unit_type, single_forecast['deliveredUnits'], unit_type,
+ single_forecast['predictedDeliveryUnits'], unit_type))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, LINE_ITEM_ID_1, LINE_ITEM_ID_2)
diff --git a/examples/ad_manager/v202205/forecast_service/get_traffic_data.py b/examples/ad_manager/v202205/forecast_service/get_traffic_data.py
new file mode 100755
index 00000000..6c9f7adf
--- /dev/null
+++ b/examples/ad_manager/v202205/forecast_service/get_traffic_data.py
@@ -0,0 +1,123 @@
+#!/usr/bin/env python
+#
+# Copyright 2020, Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets the forecasted run-of-network traffic data."""
+
+
+import datetime
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ forecast_service = client.GetService('ForecastService', version='v202205')
+ network_service = client.GetService('NetworkService', version='v202205')
+
+ # get the root ad unit ID to target the entire network.
+ root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId']
+
+ # Create a start date that's 7 days in the past and an end date that's 7 days
+ # in the future.
+ today = datetime.date.today()
+ start_date = today - datetime.timedelta(days=7)
+ end_date = today + datetime.timedelta(days=7)
+
+ # Create targeting.
+ targeting = {
+ 'inventoryTargeting': {
+ 'targetedAdUnits': [
+ {
+ 'includeDescendants': True,
+ 'adUnitId': root_ad_unit_id,
+ }
+ ]
+ }
+ }
+
+ # Request the traffic forecast data.
+ traffic_data = forecast_service.getTrafficData({
+ 'targeting': targeting,
+ 'requestedDateRange': {
+ 'startDate': start_date,
+ 'endDate': end_date
+ }
+ })
+
+ # Display historical data.
+ historical_time_series = traffic_data['historicalTimeSeries']
+ if historical_time_series is None:
+ print('No historical data to display.')
+ else:
+ historical_start_date, historical_end_date = GetDatesFromForecastTimeSeries(
+ historical_time_series)
+
+ print('Historical Data:')
+ offset = 0
+ current_date = historical_start_date
+ while current_date <= historical_end_date:
+ print('%s: %d' % (current_date.isoformat(),
+ historical_time_series['values'][offset]))
+ offset += 1
+ current_date = historical_start_date + datetime.timedelta(days=offset)
+
+ # Display forecasted data.
+ forecasted_time_series = traffic_data['forecastedTimeSeries']
+ if forecasted_time_series is None:
+ print('No forecasted data to display.')
+ else:
+ forecasted_start_date, forecasted_end_date = GetDatesFromForecastTimeSeries(
+ forecasted_time_series)
+
+ print('Forecasted Data:')
+ offset = 0
+ current_date = forecasted_start_date
+ while current_date <= forecasted_end_date:
+ print('%s: %d' % (current_date.isoformat(),
+ forecasted_time_series['values'][offset]))
+ offset += 1
+ current_date = forecasted_start_date + datetime.timedelta(days=offset)
+
+
+def GetDatesFromForecastTimeSeries(time_series):
+ """Creates datetime.date objects from a forecast time series object.
+
+ Args:
+ time_series: The forecast time series containing start and end date info.
+
+ Returns:
+ A tuple of datetime.date objects, the first representing the start date and
+ the second representing the end date.
+ """
+ date_range = time_series['timeSeriesDateRange']
+ start_date = datetime.date(
+ date_range['startDate']['year'],
+ date_range['startDate']['month'],
+ date_range['startDate']['day']
+ )
+ end_date = datetime.date(
+ date_range['endDate']['year'],
+ date_range['endDate']['month'],
+ date_range['endDate']['day']
+ )
+ return start_date, end_date
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/inventory_service/__init__.py b/examples/ad_manager/v202205/inventory_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202205/inventory_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202205/inventory_service/archive_ad_units.py b/examples/ad_manager/v202205/inventory_service/archive_ad_units.py
new file mode 100755
index 00000000..d5d5650b
--- /dev/null
+++ b/examples/ad_manager/v202205/inventory_service/archive_ad_units.py
@@ -0,0 +1,75 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example archives ad units.
+
+The parent ad unit and all ad units underneath it will be archived. To create ad
+units, run create_ad_units.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+PARENT_AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE'
+
+
+def main(client, parent_id):
+ # Initialize appropriate service.
+ inventory_service = client.GetService('InventoryService', version='v202205')
+
+ # Create a query to select ad units under the parent ad unit and the parent ad
+ # unit.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('parentId = :parentId or id = :parentId')
+ .WithBindVariable('parentId', int(parent_id)))
+
+ ad_units_archived = 0
+
+ # Get ad units by statement.
+ while True:
+ response = inventory_service.getAdUnitsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for ad_unit in response['results']:
+ print('Ad unit with ID "%s" and name "%s" will be archived.'
+ % (ad_unit['id'], ad_unit['name']))
+ # Perform action.
+ result = inventory_service.performAdUnitAction(
+ {'xsi_type': 'ArchiveAdUnits'}, statement.ToStatement())
+ if result and int(result['numChanges']) > 0:
+ ad_units_archived += int(result['numChanges'])
+ statement.offset += statement.limit
+ else:
+ break
+
+ # Display results.
+ if ad_units_archived > 0:
+ print('Number of ad units archived: %s' % ad_units_archived)
+ else:
+ print('No ad units were archived.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, PARENT_AD_UNIT_ID)
diff --git a/examples/ad_manager/v202205/inventory_service/create_ad_units.py b/examples/ad_manager/v202205/inventory_service/create_ad_units.py
new file mode 100755
index 00000000..e90bbf7f
--- /dev/null
+++ b/examples/ad_manager/v202205/inventory_service/create_ad_units.py
@@ -0,0 +1,70 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new ad units.
+
+To determine which ad units exist, run get_all_ad_units.py
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+PARENT_AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE'
+
+
+def main(client, parent_id):
+ # Initialize appropriate service.
+ inventory_service = client.GetService('InventoryService', version='v202205')
+
+ # Create ad unit size.
+ ad_unit_size = {
+ 'size': {
+ 'width': '300',
+ 'height': '250'
+ },
+ 'environmentType': 'BROWSER'
+ }
+
+ # Create ad unit objects.
+ ad_unit = {
+ 'name': 'Ad_unit_%s' % uuid.uuid4(),
+ 'parentId': parent_id,
+ 'description': 'Ad unit description.',
+ 'targetWindow': 'BLANK',
+ 'adUnitSizes': [ad_unit_size]
+ }
+
+ # Add ad units.
+ ad_units = inventory_service.createAdUnits([ad_unit])
+
+ # Display results.
+ for ad_unit in ad_units:
+ print('Ad unit with ID "%s" and name "%s" was created.'
+ % (ad_unit['id'], ad_unit['name']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, PARENT_AD_UNIT_ID)
diff --git a/examples/ad_manager/v202205/inventory_service/get_ad_unit_hierarchy.py b/examples/ad_manager/v202205/inventory_service/get_ad_unit_hierarchy.py
new file mode 100755
index 00000000..8c705468
--- /dev/null
+++ b/examples/ad_manager/v202205/inventory_service/get_ad_unit_hierarchy.py
@@ -0,0 +1,115 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example prints all ad unit names as a tree."""
+
+
+# Import appropriate modules from the client library.
+import collections
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate services.
+ network_service = client.GetService('NetworkService', version='v202205')
+ inventory_service = client.GetService('InventoryService', version='v202205')
+
+ # Set the parent ad unit's ID for all children ad units to be fetched from.
+ current_network = network_service.getCurrentNetwork()
+ root_ad_unit_id = current_network['effectiveRootAdUnitId']
+
+ # Create a statement to select only the root ad unit by ID.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('id = :id')
+ .OrderBy('id', ascending=True)
+ .Limit(1)
+ .WithBindVariable('id', root_ad_unit_id))
+
+ # Make a request for the root ad unit
+ response = inventory_service.getAdUnitsByStatement(statement.ToStatement())
+ root_ad_unit = response['results'][0]
+
+ all_ad_units = get_all_ad_units(inventory_service)
+
+ display_hierarchy(root_ad_unit, 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='v202205')
+ .OrderBy('id', ascending=True))
+
+ # Pull down all ad units into a list
+ keep_iterating = True
+ total_results = 0
+ found_ad_units = []
+ while keep_iterating:
+ page = inventory_service.getAdUnitsByStatement(statement.ToStatement())
+ if 'results' in page and len(page['results']):
+ total_results = page['totalResultSetSize']
+ found_ad_units.extend(page['results'])
+
+ statement.offset += statement.limit
+ keep_iterating = statement.offset < total_results
+
+ return found_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.defaultdict(list)
+ for ad_unit in all_ad_units:
+ if 'parentId' in ad_unit:
+ parent_id_to_children[ad_unit['parentId']].append(ad_unit)
+ parent_id_to_children = dict(parent_id_to_children)
+
+ display_hierarchy_helper(root_ad_unit, parent_id_to_children, 0)
+
+
+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([' '] * depth)),
+ root['name'], root['id']))
+
+ # Recurse for each child of this root that has children.
+ for child in parent_id_to_children.get(root['id'], []):
+ display_hierarchy_helper(child, parent_id_to_children, depth + 1)
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/inventory_service/get_all_ad_unit_sizes.py b/examples/ad_manager/v202205/inventory_service/get_all_ad_unit_sizes.py
new file mode 100755
index 00000000..35682c64
--- /dev/null
+++ b/examples/ad_manager/v202205/inventory_service/get_all_ad_unit_sizes.py
@@ -0,0 +1,46 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all ad unit sizes.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ ad_unit_size_service = client.GetService(
+ 'InventoryService', version='v202205')
+
+ # Create a statement to select ad unit sizes.
+ statement = ad_manager.StatementBuilder(version='v202205')
+
+ # Retrieve a small amount of ad unit sizes at a time, paging
+ # through until all ad unit sizes have been retrieved.
+ response = ad_unit_size_service.getAdUnitSizesByStatement(
+ statement.ToStatement())
+ if response:
+ for ad_unit_size in response:
+ # Print out some information for each ad unit size.
+ if 'fullDisplayString' in ad_unit_size:
+ print('Ad unit size with dimensions "%s" was found.\n' %
+ (ad_unit_size['fullDisplayString']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/inventory_service/get_all_ad_units.py b/examples/ad_manager/v202205/inventory_service/get_all_ad_units.py
new file mode 100755
index 00000000..32ba6e99
--- /dev/null
+++ b/examples/ad_manager/v202205/inventory_service/get_all_ad_units.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all ad units.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ ad_unit_service = client.GetService('InventoryService', version='v202205')
+
+ # Create a statement to select ad units.
+ statement = ad_manager.StatementBuilder(version='v202205')
+
+ # Retrieve a small amount of ad units at a time, paging
+ # through until all ad units have been retrieved.
+ while True:
+ response = ad_unit_service.getAdUnitsByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for ad_unit in response['results']:
+ # Print out some information for each ad unit.
+ print('Ad unit with ID "%s" and name "%s" was found.\n' %
+ (ad_unit['id'], ad_unit['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/inventory_service/get_top_level_ad_units.py b/examples/ad_manager/v202205/inventory_service/get_top_level_ad_units.py
new file mode 100755
index 00000000..e23f749a
--- /dev/null
+++ b/examples/ad_manager/v202205/inventory_service/get_top_level_ad_units.py
@@ -0,0 +1,58 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all child ad units of the effective root ad unit."""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate services.
+ network_service = client.GetService('NetworkService', version='v202205')
+ inventory_service = client.GetService('InventoryService', version='v202205')
+
+ # Set the parent ad unit's ID for all children ad units to be fetched from.
+ current_network = network_service.getCurrentNetwork()
+ parent_ad_unit_id = current_network['effectiveRootAdUnitId']
+
+ # Create a statement to select ad units under the parent ad unit.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('parentId = :parentId')
+ .OrderBy('id', ascending=True)
+ .WithBindVariable('parentId', parent_ad_unit_id))
+
+ # Retrieve a small amount of ad units at a time, paging
+ # through until all ad units have been retrieved.
+ while True:
+ response = inventory_service.getAdUnitsByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for ad_unit in response['results']:
+ # Print out some information for each ad unit.
+ print('Ad unit with ID "%s" and name "%s" was found.\n' %
+ (ad_unit['id'], ad_unit['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/inventory_service/update_ad_units.py b/examples/ad_manager/v202205/inventory_service/update_ad_units.py
new file mode 100755
index 00000000..d3c9ab71
--- /dev/null
+++ b/examples/ad_manager/v202205/inventory_service/update_ad_units.py
@@ -0,0 +1,82 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates ad unit sizes by adding a banner ad size.
+
+To determine which ad units exist, run get_all_ad_units.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+# Set the ID of the ad unit to get.
+AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE'
+
+
+def main(client, ad_unit_id):
+ # Initialize appropriate service.
+ inventory_service = client.GetService('InventoryService', version='v202205')
+
+ # Create a statement to select a single ad unit by ID.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('id = :id')
+ .WithBindVariable('id', ad_unit_id))
+
+ # Get ad units by statement.
+ response = inventory_service.getAdUnitsByStatement(
+ statement.ToStatement())
+
+ # Add the size 468x60 to the ad unit.
+ ad_unit_size = {
+ 'size': {
+ 'width': '468',
+ 'height': '60'
+ },
+ 'environmentType': 'BROWSER'
+ }
+
+ if 'results' in response and len(response['results']):
+ updated_ad_units = []
+ for ad_unit in response['results']:
+ if 'adUnitSizes' not in ad_unit:
+ ad_unit['adUnitSizes'] = []
+ ad_unit['adUnitSizes'].append(ad_unit_size)
+ updated_ad_units.append(ad_unit)
+
+ # Update ad unit on the server.
+ ad_units = inventory_service.updateAdUnits(updated_ad_units)
+
+ # Display results.
+ for ad_unit in ad_units:
+ ad_unit_sizes = ['{%s x %s}' % (size['size']['width'],
+ size['size']['height'])
+ for size in ad_unit['adUnitSizes']]
+ print('Ad unit with ID "%s", name "%s", and sizes [%s] was updated'
+ % (ad_unit['id'], ad_unit['name'], ','.join(ad_unit_sizes)))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, AD_UNIT_ID)
diff --git a/examples/ad_manager/v202205/label_service/__init__.py b/examples/ad_manager/v202205/label_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202205/label_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202205/label_service/create_labels.py b/examples/ad_manager/v202205/label_service/create_labels.py
new file mode 100755
index 00000000..df1706e4
--- /dev/null
+++ b/examples/ad_manager/v202205/label_service/create_labels.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new labels.
+
+To determine which labels exist, run get_all_labels.py. This feature is only
+available to Ad Manager 360 solution networks.
+"""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ label_service = client.GetService('LabelService', version='v202205')
+
+ # Create label objects.
+ labels = []
+ for _ in range(5):
+ label = {
+ 'name': 'Label #%s' % uuid.uuid4(),
+ 'isActive': 'true',
+ 'types': ['COMPETITIVE_EXCLUSION']
+ }
+ labels.append(label)
+
+ # Add Labels.
+ labels = label_service.createLabels(labels)
+
+ # Display results.
+ for label in labels:
+ print('Label with id "%s", name "%s", and types {%s} was found.'
+ % (label['id'], label['name'], ','.join(label['types'])))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/label_service/deactivate_labels.py b/examples/ad_manager/v202205/label_service/deactivate_labels.py
new file mode 100755
index 00000000..ade940c8
--- /dev/null
+++ b/examples/ad_manager/v202205/label_service/deactivate_labels.py
@@ -0,0 +1,65 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example deactivates all active Labels.
+
+To determine which labels exist, run get_all_labels.py. This feature is only
+available to Ad Manager 360 solution networks.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ label_service = client.GetService('LabelService', version='v202205')
+
+ # Create query.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('isActive = :isActive')
+ .WithBindVariable('isActive', True))
+
+ labels_deactivated = 0
+
+ # Get labels by statement.
+ while True:
+ response = label_service.getLabelsByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for label in response['results']:
+ print('Label with id "%s" and name "%s" will be '
+ 'deactivated.' % (label['id'], label['name']))
+ # Perform action.
+ result = label_service.performLabelAction(
+ {'xsi_type': 'DeactivateLabels'}, statement.ToStatement())
+ if result and int(result['numChanges']) > 0:
+ labels_deactivated += int(result['numChanges'])
+ statement.offset += statement.limit
+ else:
+ break
+
+ # Display results.
+ if labels_deactivated > 0:
+ print('Number of labels deactivated: %s' % labels_deactivated)
+ else:
+ print('No labels were deactivated.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/label_service/get_active_labels.py b/examples/ad_manager/v202205/label_service/get_active_labels.py
new file mode 100755
index 00000000..652accd4
--- /dev/null
+++ b/examples/ad_manager/v202205/label_service/get_active_labels.py
@@ -0,0 +1,50 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all active labels.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ label_service = client.GetService('LabelService', version='v202205')
+ # Create a statement to select labels.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('isActive = :isActive')
+ .WithBindVariable('isActive', True))
+
+ # Retrieve a small amount of labels at a time, paging
+ # through until all labels have been retrieved.
+ while True:
+ response = label_service.getLabelsByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for label in response['results']:
+ # Print out some information for each label.
+ print('Label with ID "%d" and name "%s" was found.\n' % (label['id'],
+ label['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/label_service/get_all_labels.py b/examples/ad_manager/v202205/label_service/get_all_labels.py
new file mode 100755
index 00000000..04245fb6
--- /dev/null
+++ b/examples/ad_manager/v202205/label_service/get_all_labels.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all labels.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ label_service = client.GetService('LabelService', version='v202205')
+
+ # Create a statement to select labels.
+ statement = ad_manager.StatementBuilder(version='v202205')
+
+ # Retrieve a small amount of labels at a time, paging
+ # through until all labels have been retrieved.
+ while True:
+ response = label_service.getLabelsByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for label in response['results']:
+ # Print out some information for each label.
+ print('Label with ID "%d" and name "%s" was found.\n' % (label['id'],
+ label['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/label_service/update_labels.py b/examples/ad_manager/v202205/label_service/update_labels.py
new file mode 100755
index 00000000..074aea23
--- /dev/null
+++ b/examples/ad_manager/v202205/label_service/update_labels.py
@@ -0,0 +1,63 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates the description of a single label.
+
+To determine which labels exist, run get_all_labels.py. This feature is only
+available to Ad Manager 360 solution networks.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+LABEL_ID = 'INSERT_LABEL_ID_HERE'
+
+
+def main(client, label_id):
+ # Initialize appropriate service.
+ label_service = client.GetService('LabelService', version='v202205')
+
+ # Create a statement to select only active labels.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('id = :labelId')
+ .WithBindVariable('labelId', int(label_id)))
+
+ # Get labels by filter.
+ response = label_service.getLabelsByStatement(statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ # Update each local label object by changing the description.
+ updated_labels = []
+ for label in response['results']:
+ label['description'] = 'These labels are updated.'
+ updated_labels.append(label)
+
+ # Update labels remotely.
+ labels = label_service.updateLabels(updated_labels)
+
+ for label in labels:
+ print('Label with id "%s" and name "%s" was updated.'
+ % (label['id'], label['name']))
+ else:
+ print('No labels found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, LABEL_ID)
+
diff --git a/examples/ad_manager/v202205/line_item_creative_association_service/__init__.py b/examples/ad_manager/v202205/line_item_creative_association_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202205/line_item_creative_association_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202205/line_item_creative_association_service/create_licas.py b/examples/ad_manager/v202205/line_item_creative_association_service/create_licas.py
new file mode 100755
index 00000000..1c285f19
--- /dev/null
+++ b/examples/ad_manager/v202205/line_item_creative_association_service/create_licas.py
@@ -0,0 +1,57 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new line item creative associations (LICAs) for an
+existing line item and a set of creative ids.
+
+To determine which LICAs exist, run get_all_licas.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the line item ID and creative IDs to associate.
+LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
+CREATIVE_IDS = ['INSERT_CREATIVE_IDS_HERE']
+
+
+def main(client, line_item_id, creative_ids):
+ # Initialize appropriate service.
+ lica_service = client.GetService(
+ 'LineItemCreativeAssociationService', version='v202205')
+
+ licas = []
+ for creative_id in creative_ids:
+ licas.append({'creativeId': creative_id,
+ 'lineItemId': line_item_id})
+
+ # Create the LICAs remotely.
+ licas = lica_service.createLineItemCreativeAssociations(licas)
+
+ # Display results.
+ if licas:
+ for lica in licas:
+ print('LICA with line item id "%s", creative id "%s", and '
+ 'status "%s" was created.' %
+ (lica['lineItemId'], lica['creativeId'], lica['status']))
+ else:
+ print('No LICAs created.')
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, LINE_ITEM_ID, CREATIVE_IDS)
diff --git a/examples/ad_manager/v202205/line_item_creative_association_service/deactivate_licas.py b/examples/ad_manager/v202205/line_item_creative_association_service/deactivate_licas.py
new file mode 100755
index 00000000..a409731a
--- /dev/null
+++ b/examples/ad_manager/v202205/line_item_creative_association_service/deactivate_licas.py
@@ -0,0 +1,73 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example deactivates all LICAs for the line item.
+
+To determine which LICAs exist, run get_all_licas.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the id of the line item in which to deactivate LICAs.
+LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
+
+
+def main(client, line_item_id):
+ # Initialize appropriate service.
+ lica_service = client.GetService(
+ 'LineItemCreativeAssociationService', version='v202205')
+
+ # Create query.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('lineItemId = :lineItemId AND status = :status')
+ .WithBindVariable('status', 'ACTIVE')
+ .WithBindVariable('lineItemId', int(line_item_id)))
+
+ num_deactivated_licas = 0
+
+ # Get LICAs by statement.
+ while True:
+ response = lica_service.getLineItemCreativeAssociationsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for lica in response['results']:
+ print('LICA with line item id "%s", creative id "%s", and status'
+ ' "%s" will be deactivated.' %
+ (lica['lineItemId'], lica['creativeId'], lica['status']))
+
+ # Perform action.
+ result = lica_service.performLineItemCreativeAssociationAction(
+ {'xsi_type': 'DeactivateLineItemCreativeAssociations'},
+ statement.ToStatement())
+ if result and int(result['numChanges']) > 0:
+ num_deactivated_licas += int(result['numChanges'])
+ statement.offset += statement.limit
+ else:
+ break
+
+ # Display results.
+ if num_deactivated_licas > 0:
+ print('Number of LICAs deactivated: %s' % num_deactivated_licas)
+ else:
+ print('No LICAs were deactivated.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, LINE_ITEM_ID)
diff --git a/examples/ad_manager/v202205/line_item_creative_association_service/get_all_licas.py b/examples/ad_manager/v202205/line_item_creative_association_service/get_all_licas.py
new file mode 100755
index 00000000..aff39527
--- /dev/null
+++ b/examples/ad_manager/v202205/line_item_creative_association_service/get_all_licas.py
@@ -0,0 +1,57 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all line item creative associations.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ lica_service = client.GetService(
+ 'LineItemCreativeAssociationService', version='v202205')
+
+ # Create a statement to select line item creative associations.
+ statement = ad_manager.StatementBuilder(version='v202205')
+
+ # Retrieve a small amount of line item creative associations at a time, paging
+ # through until all line item creative associations have been retrieved.
+ while True:
+ response = lica_service.getLineItemCreativeAssociationsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for lica in response['results']:
+ # Print out some information for each line item creative association.
+ if 'creativeSetId' in lica:
+ print('LICA with line item ID "%s", creative set ID "%s", and '
+ 'status "%s" was found.' %
+ (lica['lineItemId'], lica['creativeSetId'], lica['status']))
+ else:
+ print('Line item creative association with line item ID "%d" and '
+ 'creative ID "%d" was found.\n' %
+ (lica['lineItemId'], lica['creativeId']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/line_item_creative_association_service/get_licas_for_line_item.py b/examples/ad_manager/v202205/line_item_creative_association_service/get_licas_for_line_item.py
new file mode 100755
index 00000000..a921f7e4
--- /dev/null
+++ b/examples/ad_manager/v202205/line_item_creative_association_service/get_licas_for_line_item.py
@@ -0,0 +1,60 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all line item creative associations for a given line item.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
+
+
+def main(client, line_item_id):
+ # Initialize appropriate service.
+ lica_service = client.GetService(
+ 'LineItemCreativeAssociationService', version='v202205')
+ # Create a statement to select line item creative associations.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('lineItemId = :lineItemId')
+ .WithBindVariable('lineItemId', line_item_id))
+
+ # Retrieve a small amount of line item creative associations at a time, paging
+ # through until all line item creative associations have been retrieved.
+ while True:
+ response = lica_service.getLineItemCreativeAssociationsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for lica in response['results']:
+ # Print out some information for each line item creative association.
+ if 'creativeSetId' in lica:
+ print('LICA with line item ID "%s", creative set ID "%s", and '
+ 'status "%s" was found.' %
+ (lica['lineItemId'], lica['creativeSetId'], lica['status']))
+ else:
+ print('Line item creative association with line item ID "%d" and '
+ 'creative ID "%d" was found.\n' %
+ (lica['lineItemId'], lica['creativeId']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, LINE_ITEM_ID)
diff --git a/examples/ad_manager/v202205/line_item_creative_association_service/push_creative_to_devices.py b/examples/ad_manager/v202205/line_item_creative_association_service/push_creative_to_devices.py
new file mode 100755
index 00000000..a24aa194
--- /dev/null
+++ b/examples/ad_manager/v202205/line_item_creative_association_service/push_creative_to_devices.py
@@ -0,0 +1,61 @@
+#!/usr/bin/env python
+#
+# Copyright 2021, Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example pushes a LICA to a linked device for preview.
+
+To determine which linked devices exist, use the PublisherQueryLanguageService
+linked_device table.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the associated line item id and creative id to push, and set the linked
+# device id where it will be pushed.
+LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
+CREATIVE_ID = 'INSERT_CREATIVE_ID_HERE'
+LINKED_DEVICE_ID = 'INSERT_LINKED_DEVICE_ID_HERE'
+
+
+def main(client, line_item_id, creative_id, linked_device_id):
+ # Initialize appropriate service.
+ lica_service = client.GetService(
+ 'LineItemCreativeAssociationService', version='v202205')
+
+ # Create query to select a single linked device.
+ # Linked devices can be read from the linked_device PQL table.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('id = :linkedDeviceId')
+ .WithBindVariable('linkedDeviceId', int(linked_device_id)))
+
+ # Make call to push creatives to devices.
+ result = lica_service.pushCreativeToDevices(statement.ToStatement(), {
+ 'lineItemId': line_item_id,
+ 'creativeId': creative_id
+ })
+
+ # Display results.
+ if result and int(result['numChanges']) > 0:
+ print('Pushed creatives to %s devices.' % result['numChanges'])
+ else:
+ print('No creatives were pushed.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, LINE_ITEM_ID, CREATIVE_ID, LINKED_DEVICE_ID)
diff --git a/examples/ad_manager/v202205/line_item_creative_association_service/update_licas.py b/examples/ad_manager/v202205/line_item_creative_association_service/update_licas.py
new file mode 100755
index 00000000..bbacda7d
--- /dev/null
+++ b/examples/ad_manager/v202205/line_item_creative_association_service/update_licas.py
@@ -0,0 +1,66 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates the destination URL of all line item creative
+associations (LICA).
+
+To determine which LICAs exist, run get_all_licas.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ lica_service = client.GetService(
+ 'LineItemCreativeAssociationService', version='v202205')
+
+ # Create statement object to get all LICAs.
+ statement = ad_manager.StatementBuilder(version='v202205')
+
+ while True:
+ # Get LICAs by statement.
+ response = lica_service.getLineItemCreativeAssociationsByStatement(
+ statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ # Update each local LICA object by changing its destination URL.
+ updated_licas = []
+ for lica in response['results']:
+ lica['destinationUrl'] = 'http://news.google.com'
+ updated_licas.append(lica)
+
+ # Update LICAs remotely.
+ licas = lica_service.updateLineItemCreativeAssociations(updated_licas)
+
+ # Display results.
+ for lica in licas:
+ print('LICA with line item id "%s", creative id "%s", and status '
+ '"%s" was updated.' % (lica['lineItemId'], lica['creativeId'],
+ lica['status']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ if response['totalResultSetSize'] == 0:
+ print('No LICAs found to update.')
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/line_item_service/__init__.py b/examples/ad_manager/v202205/line_item_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202205/line_item_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202205/line_item_service/activate_line_items.py b/examples/ad_manager/v202205/line_item_service/activate_line_items.py
new file mode 100755
index 00000000..52274a6f
--- /dev/null
+++ b/examples/ad_manager/v202205/line_item_service/activate_line_items.py
@@ -0,0 +1,75 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example activates all line items for the given order.
+
+To be activated, line items need to be in the approved state and have at least
+one creative associated with them. To approve line items, approve the order to
+which they belong by running approve_orders.py. To create LICAs, run
+create_licas.py. To determine which line items exist, run
+get_all_line_items.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the id of the order to get line items from.
+ORDER_ID = 'INSERT_ORDER_ID_HERE'
+
+
+def main(client, order_id):
+ # Initialize appropriate service.
+ line_item_service = client.GetService('LineItemService', version='v202205')
+
+ # Create query.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('orderId = :orderId AND status = :status')
+ .WithBindVariable('status', 'NEEDS_CREATIVES')
+ .WithBindVariable('orderId', int(order_id)))
+
+ line_items_activated = 0
+
+ # Get line items by statement.
+ while True:
+ response = line_item_service.getLineItemsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for line_item in response['results']:
+ print('Line item with id "%s", belonging to order id "%s", and '
+ 'name "%s" will be activated.' %
+ (line_item['id'], line_item['orderId'], line_item['name']))
+
+ # Perform action.
+ result = line_item_service.performLineItemAction(
+ {'xsi_type': 'ActivateLineItems'}, statement.ToStatement())
+ if result and int(result['numChanges']) > 0:
+ line_items_activated += int(result['numChanges'])
+ statement.offset += statement.limit
+ else:
+ break
+
+ # Display results.
+ if line_items_activated > 0:
+ print('Number of line items activated: %s' % line_items_activated)
+ else:
+ print('No line items were activated.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ORDER_ID)
diff --git a/examples/ad_manager/v202205/line_item_service/create_line_items.py b/examples/ad_manager/v202205/line_item_service/create_line_items.py
new file mode 100755
index 00000000..31f990b3
--- /dev/null
+++ b/examples/ad_manager/v202205/line_item_service/create_line_items.py
@@ -0,0 +1,165 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new line items.
+
+To determine which line items exist, run get_all_line_items.py. To determine
+which orders exist, run get_all_orders.py. To determine which placements exist,
+run get_all_placements.py.
+"""
+
+
+import datetime
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+import pytz
+
+# Set order that the created line item will belong to and add the id of a
+# placement containing ad units to target.
+ORDER_ID = 'INSERT_ORDER_ID_HERE'
+TARGETED_PLACEMENT_IDS = ['INSERT_PLACEMENT_IDS_HERE']
+
+
+def main(client, order_id, targeted_placement_ids):
+ # Initialize appropriate service.
+ line_item_service = client.GetService('LineItemService', version='v202205')
+
+ end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York'))
+ end_datetime += datetime.timedelta(days=365)
+
+ # Create line item objects.
+ line_items = []
+ for _ in range(5):
+ line_item = {
+ 'name': 'Line item #%s' % uuid.uuid4(),
+ 'orderId': order_id,
+ 'targeting': {
+ 'inventoryTargeting': {
+ 'targetedPlacementIds': targeted_placement_ids
+ },
+ 'geoTargeting': {
+ 'targetedLocations': [
+ {
+ 'id': '2840',
+ 'displayName': 'US'
+ },
+ {
+ 'id': '20133',
+ 'displayName': 'Geneva'
+ },
+ {
+ 'id': '9000093',
+ 'displayName': 'B3P',
+ }
+ ],
+ 'excludedLocations': [
+ {
+ 'id': '1016367',
+ 'displayName': 'Chicago',
+ },
+ {
+ 'id': '200501',
+ 'displayName': 'New York NY'
+ }
+ ]
+ },
+ 'dayPartTargeting': {
+ 'dayParts': [
+ {
+ 'dayOfWeek': 'SATURDAY',
+ 'startTime': {
+ 'hour': '0',
+ 'minute': 'ZERO'
+ },
+ 'endTime': {
+ 'hour': '24',
+ 'minute': 'ZERO'
+ }
+ },
+ {
+ 'dayOfWeek': 'SUNDAY',
+ 'startTime': {
+ 'hour': '0',
+ 'minute': 'ZERO'
+ },
+ 'endTime': {
+ 'hour': '24',
+ 'minute': 'ZERO'
+ }
+ }
+ ],
+ 'timeZone': 'BROWSER'
+ },
+ 'userDomainTargeting': {
+ 'domains': ['usa.gov'],
+ 'targeted': 'false'
+ },
+ 'technologyTargeting': {
+ 'browserTargeting': {
+ 'browsers': [{'id': '500072'}],
+ 'isTargeted': 'true'
+ }
+ }
+ },
+ 'creativePlaceholders': [
+ {
+ 'size': {
+ 'width': '300',
+ 'height': '250'
+ }
+ },
+ {
+ 'size': {
+ 'width': '120',
+ 'height': '600'
+ }
+ }
+ ],
+ 'startDateTimeType': 'IMMEDIATELY',
+ 'lineItemType': 'STANDARD',
+ 'endDateTime': end_datetime,
+ 'costType': 'CPM',
+ 'costPerUnit': {
+ 'currencyCode': 'USD',
+ 'microAmount': '2000000'
+ },
+ 'primaryGoal': {
+ 'units': '50',
+ 'unitType': 'IMPRESSIONS',
+ 'goalType': 'LIFETIME'
+ },
+ 'contractedUnitsBought': '100',
+ 'creativeRotationType': 'EVEN',
+ 'discountType': 'PERCENTAGE',
+ 'allowOverbook': 'true'
+ }
+ line_items.append(line_item)
+
+ # Add line items.
+ line_items = line_item_service.createLineItems(line_items)
+
+ # Display results.
+ for line_item in line_items:
+ print('Line item with id "%s", belonging to order id "%s", and named '
+ '"%s" was created.' % (line_item['id'], line_item['orderId'],
+ line_item['name']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ORDER_ID, TARGETED_PLACEMENT_IDS)
diff --git a/examples/ad_manager/v202205/line_item_service/create_video_line_item.py b/examples/ad_manager/v202205/line_item_service/create_video_line_item.py
new file mode 100755
index 00000000..013902c1
--- /dev/null
+++ b/examples/ad_manager/v202205/line_item_service/create_video_line_item.py
@@ -0,0 +1,135 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates a new line item to serve to video content.
+
+This feature is only available to Ad Manager 360 solution networks.
+"""
+
+import datetime
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+import pytz
+
+# Set order that all created line item will belong to and the video ad unit id
+# to target.
+ORDER_ID = 'INSERT_ORDER_ID_HERE'
+TARGETED_VIDEO_AD_UNIT_ID = 'INSERT_TARGETED_VIDEO_AD_UNIT_ID_HERE'
+
+# Set the video content to target.
+CONTENT_ID = 'INSERT_CONTENT_ID_HERE'
+# Set the video content bundle to target.
+CONTENT_BUNDLE_ID = 'INSERT_CONTENT_BUNDLE_ID_HERE'
+# Set the CMS metadata value to target.
+CMS_METADATA_VALUE_ID = 'INSERT_CMS_METADATA_VALUE_ID_HERE'
+
+
+def main(client, order_id, targeted_video_ad_unit_id, content_id,
+ content_bundle_id, cms_metadata_value_id):
+ # Initialize appropriate service.
+ line_item_service = client.GetService('LineItemService', version='v202205')
+
+ end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York'))
+ end_datetime += datetime.timedelta(days=365)
+
+ # Create line item object.
+ line_item = {
+ 'name': 'Line item #%s' % uuid.uuid4(),
+ 'orderId': order_id,
+ 'targeting': {
+ 'contentTargeting': {
+ 'targetedContentIds': [content_id],
+ 'targetedVideoContentBundleIds': [content_bundle_id]
+ },
+ 'customTargeting': {
+ 'logicalOperator': 'AND',
+ 'children': [{
+ 'xsi_type': 'CmsMetadataCriteria',
+ 'cmsMetadataValueIds': [cms_metadata_value_id],
+ 'operator': 'EQUALS'
+ }]
+ },
+ 'inventoryTargeting': {
+ 'targetedAdUnits': [{
+ 'adUnitId': targeted_video_ad_unit_id,
+ 'includeDescendants': 'true'
+ }]
+ },
+ 'requestPlatformTargeting': {
+ 'targetedRequestPlatforms': ['VIDEO_PLAYER']
+ },
+ 'videoPositionTargeting': {
+ 'targetedPositions': [{
+ 'videoPosition': {
+ 'positionType': 'PREROLL'
+ }
+ }]
+ }
+ },
+ 'creativePlaceholders': [{
+ 'size': {
+ 'width': '400',
+ 'height': '300'
+ },
+ 'companions': [{
+ 'size': {
+ 'width': '300',
+ 'height': '250'
+ },
+ }, {
+ 'size': {
+ 'width': '728',
+ 'height': '90'
+ },
+ }]
+ }],
+ 'environmentType': 'VIDEO_PLAYER',
+ 'companionDeliveryOption': 'OPTIONAL',
+ 'videoMaxDuration': 15000,
+ 'startDateTimeType': 'IMMEDIATELY',
+ 'lineItemType': 'SPONSORSHIP',
+ 'endDateTime': end_datetime,
+ 'costType': 'CPM',
+ 'costPerUnit': {
+ 'currencyCode': 'USD',
+ 'microAmount': '2000000'
+ },
+ 'primaryGoal': {
+ 'units': '50',
+ 'unitType': 'IMPRESSIONS',
+ 'goalType': 'DAILY'
+ },
+ 'contractedUnitsBought': '100',
+ 'creativeRotationType': 'OPTIMIZED',
+ 'discountType': 'PERCENTAGE',
+ 'allowOverbook': 'true'
+ }
+
+ # Add line item.
+ line_item = line_item_service.createLineItems([line_item])[0]
+
+ # Display results.
+ print('Video line item with id "%s", belonging to order id "%s", and '
+ 'named "%s" was created.' % (line_item['id'], line_item['orderId'],
+ line_item['name']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ORDER_ID, TARGETED_VIDEO_AD_UNIT_ID, CONTENT_ID,
+ CONTENT_BUNDLE_ID, CMS_METADATA_VALUE_ID)
diff --git a/examples/ad_manager/v202205/line_item_service/get_all_line_items.py b/examples/ad_manager/v202205/line_item_service/get_all_line_items.py
new file mode 100755
index 00000000..e1585b6c
--- /dev/null
+++ b/examples/ad_manager/v202205/line_item_service/get_all_line_items.py
@@ -0,0 +1,50 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all line items.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ line_item_service = client.GetService('LineItemService', version='v202205')
+
+ # Create a statement to select line items.
+ statement = ad_manager.StatementBuilder(version='v202205')
+
+ # Retrieve a small amount of line items at a time, paging
+ # through until all line items have been retrieved.
+ while True:
+ response = line_item_service.getLineItemsByStatement(statement.ToStatement(
+ ))
+ if 'results' in response and len(response['results']):
+ for line_item in response['results']:
+ # Print out some information for each line item.
+ print('Line item with ID "%d" and name "%s" was found.\n' %
+ (line_item['id'], line_item['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/line_item_service/get_line_items_that_need_creatives.py b/examples/ad_manager/v202205/line_item_service/get_line_items_that_need_creatives.py
new file mode 100755
index 00000000..05d98fee
--- /dev/null
+++ b/examples/ad_manager/v202205/line_item_service/get_line_items_that_need_creatives.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all line items that are missing creatives.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ line_item_service = client.GetService('LineItemService', version='v202205')
+ # Create a statement to select line items.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('isMissingCreatives = :isMissingCreatives')
+ .WithBindVariable('isMissingCreatives', True))
+
+ # Retrieve a small amount of line items at a time, paging
+ # through until all line items have been retrieved.
+ while True:
+ response = line_item_service.getLineItemsByStatement(statement.ToStatement(
+ ))
+ if 'results' in response and len(response['results']):
+ for line_item in response['results']:
+ # Print out some information for each line item.
+ print('Line item with ID "%d" and name "%s" was found.\n' %
+ (line_item['id'], line_item['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/line_item_service/get_recently_updated_line_items.py b/examples/ad_manager/v202205/line_item_service/get_recently_updated_line_items.py
new file mode 100755
index 00000000..5b08a98a
--- /dev/null
+++ b/examples/ad_manager/v202205/line_item_service/get_recently_updated_line_items.py
@@ -0,0 +1,59 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets only recently updated line items.
+"""
+
+# Import appropriate modules from the client library.
+from datetime import datetime
+from datetime import timedelta
+
+from googleads import ad_manager
+import pytz
+
+
+def main(client):
+ # Initialize appropriate service.
+ line_item_service = client.GetService('LineItemService', version='v202205')
+
+ last_modified = (datetime.now(tz=pytz.timezone('America/New_York'))
+ - timedelta(days=1))
+
+ # Create a statement to select line items.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('lastModifiedDateTime >= :lastModifiedDateTime')
+ .WithBindVariable('lastModifiedDateTime', last_modified))
+
+ # Retrieve a small amount of line items at a time, paging
+ # through until all line items have been retrieved.
+ while True:
+ response = line_item_service.getLineItemsByStatement(statement.ToStatement(
+ ))
+ if 'results' in response and len(response['results']):
+ for line_item in response['results']:
+ # Print out some information for each line item.
+ print('Line item with ID "%d" and name "%s" was found.\n' %
+ (line_item['id'], line_item['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/line_item_service/pause_line_items.py b/examples/ad_manager/v202205/line_item_service/pause_line_items.py
new file mode 100755
index 00000000..ca3afe4c
--- /dev/null
+++ b/examples/ad_manager/v202205/line_item_service/pause_line_items.py
@@ -0,0 +1,74 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example pauses a line item.
+
+Line items must be paused before they can be updated. To determine which line
+items exist, run get_all_line_items.py
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the line item to pause.
+LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
+
+
+def main(client):
+ # Initialize appropriate service.
+ line_item_service = client.GetService('LineItemService', version='v202205')
+
+ # Create a statement to select the line item.
+ # Change this to operate on more than one Line Item.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('id = :id')
+ .OrderBy('id', ascending=True)
+ .WithBindVariable('id', LINE_ITEM_ID))
+
+ result_set_size = 0
+ should_continue = True
+
+ # Iterate over paged results from the statement.
+ while should_continue:
+ page = line_item_service.getLineItemsByStatement(statement.ToStatement())
+ if 'results' in page and len(page['results']):
+ result_set_size = page['totalResultSetSize']
+ # Iterate over individual results in the page.
+ for line_item in page['results']:
+ print('Pausing line item with ID %d' % line_item['id'])
+ # Update statement for next page.
+ statement.offset += statement.limit
+ should_continue = statement.offset < result_set_size
+
+ print('Pausing %d line item(s)' % result_set_size)
+
+ if result_set_size > 0:
+ statement.offset = None
+ statement.limit = None
+
+ # Perform Pause action on all Line Items that match the statement.
+ update_result = line_item_service.performLineItemAction(
+ {'xsi_type': 'PauseLineItems'}, statement.ToStatement())
+
+ if update_result and update_result['numChanges'] > 0:
+ print('Updated %d line item(s)' % update_result['numChanges'])
+ else:
+ print('No line items were paused')
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/line_item_service/target_custom_criteria.py b/examples/ad_manager/v202205/line_item_service/target_custom_criteria.py
new file mode 100755
index 00000000..2e66009a
--- /dev/null
+++ b/examples/ad_manager/v202205/line_item_service/target_custom_criteria.py
@@ -0,0 +1,110 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example updates a line item to add custom criteria targeting.
+
+To determine which line items exist, run get_all_line_items.py. To determine
+which custom targeting keys and values exist, run
+get_all_custom_targeting_keys_and_values.py.
+"""
+
+
+import pprint
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
+KEY_ID1 = 'INSERT_TARGETING_KEY_ID_HERE'
+KEY_ID2 = 'INSERT_TARGETING_KEY_ID_HERE'
+KEY_ID3 = 'INSERT_TARGETING_KEY_ID_HERE'
+
+VALUE_ID1 = 'INSERT_TARGETING_VALUE_ID_HERE'
+VALUE_ID2 = 'INSERT_TARGETING_VALUE_ID_HERE'
+VALUE_ID3 = 'INSERT_TARGETING_VALUE_ID_HERE'
+
+
+def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2,
+ value_id3):
+ # Initialize appropriate service.
+ line_item_service = client.GetService('LineItemService', version='v202205')
+
+ # create custom criterias
+ custom_criteria1 = {
+ 'xsi_type': 'CustomCriteria',
+ 'keyId': key_id1,
+ 'valueIds': [value_id1],
+ 'operator': 'IS'
+ }
+
+ custom_criteria2 = {
+ 'xsi_type': 'CustomCriteria',
+ 'keyId': key_id2,
+ 'valueIds': [value_id2],
+ 'operator': 'IS_NOT'
+ }
+
+ custom_criteria3 = {
+ 'xsi_type': 'CustomCriteria',
+ 'keyId': key_id3,
+ 'valueIds': [value_id3],
+ 'operator': 'IS'
+ }
+
+ # Create the custom criteria set that will resemble:
+ # (custom_criteria1.key == custom_criteria1.value OR
+ # (custom_criteria2.key != custom_criteria2.value AND
+ # custom_criteria13.key == custom_criteria3.value))
+ sub_set = {
+ 'xsi_type': 'CustomCriteriaSet',
+ 'logicalOperator': 'AND',
+ 'children': [custom_criteria2, custom_criteria3]
+ }
+
+ top_set = {
+ 'xsi_type': 'CustomCriteriaSet',
+ 'logicalOperator': 'OR',
+ 'children': [custom_criteria1, sub_set]
+ }
+
+ # Create statement to get the line item
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('id = :lineItemId')
+ .WithBindVariable('lineItemId', int(line_item_id))
+ .Limit(1))
+
+ # Set custom criteria targeting on the line item.
+ line_item = line_item_service.getLineItemsByStatement(
+ statement.ToStatement())['results'][0]
+ line_item['targeting']['customTargeting'] = top_set
+
+ # Update line item.
+ line_item = line_item_service.updateLineItems([line_item])[0]
+
+ # Display results.
+ if line_item:
+ print('Line item with id "%s" updated with custom criteria targeting:'
+ % line_item['id'])
+ pprint.pprint(line_item['targeting']['customTargeting'])
+ else:
+ print('No line items were updated.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, LINE_ITEM_ID, KEY_ID1, KEY_ID2, KEY_ID3, VALUE_ID1,
+ VALUE_ID2, VALUE_ID3)
diff --git a/examples/ad_manager/v202205/line_item_service/update_line_items.py b/examples/ad_manager/v202205/line_item_service/update_line_items.py
new file mode 100755
index 00000000..416cc94e
--- /dev/null
+++ b/examples/ad_manager/v202205/line_item_service/update_line_items.py
@@ -0,0 +1,74 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates the delivery rate of all line items in an order.
+
+To determine which line items exist, run get_all_line_items.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set id of the order to get line items from.
+ORDER_ID = 'INSERT_ORDER_ID_HERE'
+
+
+def main(client, order_id):
+ # Initialize appropriate service.
+ line_item_service = client.GetService('LineItemService', version='v202205')
+
+ # Create statement object to only select line items with even delivery rates.
+
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where(('deliveryRateType = :deliveryRateType AND '
+ 'orderId = :orderId'))
+ .WithBindVariable('orderId', int(order_id))
+ .WithBindVariable('deliveryRateType', 'EVENLY')
+ .Limit(500))
+
+ # Get line items by statement.
+ response = line_item_service.getLineItemsByStatement(
+ statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ # Update each local line item by changing its delivery rate type.
+ updated_line_items = []
+ for line_item in response['results']:
+ if not line_item['isArchived']:
+ line_item['deliveryRateType'] = 'AS_FAST_AS_POSSIBLE'
+ updated_line_items.append(line_item)
+
+ # Update line items remotely.
+ line_items = line_item_service.updateLineItems(updated_line_items)
+
+ # Display results.
+ if line_items:
+ for line_item in line_items:
+ print('Line item with id "%s", belonging to order id "%s", named '
+ '"%s", and delivery rate "%s" was updated.'
+ % (line_item['id'], line_item['orderId'], line_item['name'],
+ line_item['deliveryRateType']))
+ else:
+ print('No line items were updated.')
+ else:
+ print('No line items found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ORDER_ID)
diff --git a/examples/ad_manager/v202205/live_stream_event_service/activate_live_stream_events.py b/examples/ad_manager/v202205/live_stream_event_service/activate_live_stream_events.py
new file mode 100755
index 00000000..e74b1135
--- /dev/null
+++ b/examples/ad_manager/v202205/live_stream_event_service/activate_live_stream_events.py
@@ -0,0 +1,71 @@
+#!/usr/bin/env python
+#
+# Copyright 2018 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example activates paused live stream events."""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the id of the LiveStreamEvent to get live stream events from.
+LIVE_STREAM_EVENT_ID = 'INSERT_LIVE_STREAM_EVENT_ID_HERE'
+
+
+def main(client, live_stream_event_id):
+ # Initialize appropriate service.
+ live_stream_event_service = client.GetService(
+ 'LiveStreamEventService', version='v202205')
+
+ # Create query to find paused live stream events.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where(('id = :id AND '
+ 'status = :status'))
+ .WithBindVariable('status', 'PAUSED')
+ .WithBindVariable('id', int(live_stream_event_id))
+ .Limit(500))
+
+ live_stream_events_activated = 0
+
+ # Get live stream events by statement.
+ while True:
+ response = live_stream_event_service.getLiveStreamEventsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for live_stream_event in response['results']:
+ print('live stream event with id "%s" and name "%s" will be activated.'
+ % (live_stream_event['id'], live_stream_event['name']))
+
+ # Perform action.
+ result = live_stream_event_service.performLiveStreamEventAction({
+ 'xsi_type': 'ActivateLiveStreamEvents'
+ }, statement.ToStatement())
+ if result and int(result['numChanges']) > 0:
+ live_stream_events_activated += int(result['numChanges'])
+ statement.offset += ad_manager.SUGGESTED_PAGE_LIMIT
+ else:
+ break
+
+ # Display results.
+ if live_stream_events_activated > 0:
+ print('# of live stream events activated: %s' % (
+ live_stream_events_activated))
+ else:
+ print('No live stream events were activated.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, LIVE_STREAM_EVENT_ID)
diff --git a/examples/ad_manager/v202205/live_stream_event_service/create_live_stream_events.py b/examples/ad_manager/v202205/live_stream_event_service/create_live_stream_events.py
new file mode 100755
index 00000000..674206ca
--- /dev/null
+++ b/examples/ad_manager/v202205/live_stream_event_service/create_live_stream_events.py
@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+#
+# Copyright 2018 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new live stream events.
+
+To determine which live stream events exist, run get_all_live_stream_events.py.
+To determine which cdn configurations exist, run get_cdn_configurations.py.
+"""
+
+import datetime
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+import pytz
+
+# Set content urls and adTags to use
+CONTENT_URLS = ['INSERT_CONTENT_URLS_HERE']
+AD_TAGS = ['INSERT_AD_TAGS_HERE']
+
+
+def main(client, content_urls, ad_tags):
+ # Initialize appropriate services.
+ live_events_service = client.GetService(
+ 'LiveStreamEventService', version='v202205')
+
+ # Stream will play for 365 days
+ start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York'))
+ end_datetime = start_datetime + datetime.timedelta(days=365)
+
+ # Create live stream event objects
+ live_stream_events = [{
+ 'name': 'Live Stream Event #%s' % uuid.uuid4(),
+ 'startDateTime': start_datetime,
+ 'endDateTime': end_datetime,
+ 'contentUrls': content_urls,
+ 'adTags': ad_tags
+ }]
+
+ # Add live stream events.
+ live_stream_events = live_events_service.createLiveStreamEvents(
+ live_stream_events)
+
+ # Display results.
+ for live_stream_event in live_stream_events:
+ print(
+ 'Live stream event with id "%s", named "%s" and status %s was created.'
+ % (live_stream_event['id'], live_stream_event['name'],
+ live_stream_event['status']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CONTENT_URLS, AD_TAGS)
diff --git a/examples/ad_manager/v202205/live_stream_event_service/get_all_live_stream_events.py b/examples/ad_manager/v202205/live_stream_event_service/get_all_live_stream_events.py
new file mode 100755
index 00000000..878af9de
--- /dev/null
+++ b/examples/ad_manager/v202205/live_stream_event_service/get_all_live_stream_events.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2018 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all live stream events.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ live_stream_event_service = client.GetService(
+ 'LiveStreamEventService', version='v202205')
+
+ # Create a statement to select live stream events.
+ statement = ad_manager.StatementBuilder(version='v202205')
+
+ # Retrieve a small amount of live stream events at a time, paging
+ # through until all live stream events have been retrieved.
+ while True:
+ response = live_stream_event_service.getLiveStreamEventsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for live_stream_event in response['results']:
+ # Print out some information for each live stream event.
+ print('live stream event with id "%d" and name "%s" was found.' %
+ (live_stream_event['id'], live_stream_event['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/live_stream_event_service/register_sessions_for_monitoring.py b/examples/ad_manager/v202205/live_stream_event_service/register_sessions_for_monitoring.py
new file mode 100755
index 00000000..0d74bb84
--- /dev/null
+++ b/examples/ad_manager/v202205/live_stream_event_service/register_sessions_for_monitoring.py
@@ -0,0 +1,45 @@
+#!/usr/bin/env python
+#
+# Copyright 2018 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example registers all live stream event-sessions ids for monitoring."""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# List of session ids
+SESSION_IDS = ['INSERT_SESSION_IDS_HERE']
+
+
+def main(client, session_ids):
+ # Initialize appropriate service.
+ live_stream_event_service = client.GetService(
+ 'LiveStreamEventService', version='v202205')
+
+ # Retrieve all sessions id that are being monitored
+ session_ids = live_stream_event_service.registerSessionsForMonitoring(
+ session_ids)
+ if session_ids:
+ for session_id in session_ids:
+ # Print out some information for each live stream event.
+ print('Session with ID "%s" registered for monitoring.' % (session_id))
+
+ print('\nNumber of results found: %s' % session_ids.size)
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, SESSION_IDS)
diff --git a/examples/ad_manager/v202205/live_stream_event_service/update_live_stream_events.py b/examples/ad_manager/v202205/live_stream_event_service/update_live_stream_events.py
new file mode 100755
index 00000000..a4a51d44
--- /dev/null
+++ b/examples/ad_manager/v202205/live_stream_event_service/update_live_stream_events.py
@@ -0,0 +1,69 @@
+#!/usr/bin/env python
+#
+# Copyright 2018 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates live stream events.
+
+To determine which live stream events exist, run get_all_live_stream_events.py.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set ID of the LiveStreamEvent to get live stream events from.
+LIVE_STREAM_EVENT_ID = 'INSERT_LIVE_STREAM_EVENT_ID_HERE'
+
+
+def main(client, live_stream_event_id):
+ # Initialize appropriate services.
+ live_stream_events_service = client.GetService(
+ 'LiveStreamEventService', version='v202205')
+
+ # Create statement object to only select matching live stream event.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where(('Id = :id'))
+ .WithBindVariable('id', int(live_stream_event_id))
+ .Limit(500))
+
+ # Get live stream events by statement.
+ response = live_stream_events_service.getLiveStreamEventsByStatement(
+ statement.ToStatement())
+
+ # Set adTags to be updated.
+ new_ad_tags = ['INSERT_NEW_AD_TAGS_HERE']
+
+ if 'results' in response and len(response['results']):
+ # Update each local live stream event by changing its attributes.
+ updated_live_stream_events = []
+ for live_stream_event in response['results']:
+ live_stream_event['startDateTimeType'] = 'IMMEDIATELY'
+ live_stream_event['adTags'] = new_ad_tags
+ updated_live_stream_events.append(live_stream_event)
+
+ # Update live stream events.
+ live_stream_events = live_stream_events_service.updateLiveStreamEvents(
+ updated_live_stream_events)
+
+ # Display results.
+ for live_stream_event in live_stream_events:
+ print('Live stream event with id "%s", named "%s" and status %s was '
+ 'updated.' % (live_stream_event['id'], live_stream_event['name'],
+ live_stream_event['status']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, LIVE_STREAM_EVENT_ID)
diff --git a/examples/ad_manager/v202205/native_style_service/__init__.py b/examples/ad_manager/v202205/native_style_service/__init__.py
new file mode 100755
index 00000000..473ddba1
--- /dev/null
+++ b/examples/ad_manager/v202205/native_style_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202205/native_style_service/create_native_styles.py b/examples/ad_manager/v202205/native_style_service/create_native_styles.py
new file mode 100755
index 00000000..970c61a0
--- /dev/null
+++ b/examples/ad_manager/v202205/native_style_service/create_native_styles.py
@@ -0,0 +1,178 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Creates a native app install ad."""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+# This is the creative template ID for the system-defined native app install ad
+# format, which we will create the native style from. Use
+# CreativeTemplateService.getCreativeTemplateByStatement() and
+# CreativeTemplate.isNativeEligible() to get other native ad formats available
+# in your network.
+CREATIVE_TEMPLATE_ID = 10004400
+WIDTH = 300
+HEIGHT = 345
+
+HTML_SNIPPET = """
+"""
+
+CSS_SNIPPET = """body {
+ background-color: rgba(255, 255, 255, 1);
+ font-family: "Roboto-Regular", sans-serif;
+ font-weight: normal;
+ font-size: 12px;
+ line-height: 14px;
+}
+.attribution {
+ background-color: rgba(236, 182, 0, 1);
+ color: rgba(255, 255, 255, 1);
+ font-size: 13px;
+ display: table;
+ margin: 4px 8px;
+ padding: 0 3px;
+ border-radius: 2px;
+}
+.image {
+ text-align: center;
+ margin: 8px;
+}
+.image img,
+.image-link {
+ width: 100%;
+}
+.app-icon {
+ float: left;
+ margin: 0 8px 4px 8px;
+ height: 40px;
+ width: 40px;
+ background-color: transparent;
+}
+.app-icon img {
+ height: 100%;
+ width: 100%;
+ border-radius: 20%;
+}
+.title {
+ font-weight: bold;
+ font-size: 14px;
+ line-height: 20px;
+ margin: 8px 8px 4px 8px;
+}
+.title a {
+ color: rgba(112, 112, 112, 1);
+ text-decoration: none;
+}
+.reviews {
+ float: left;
+}
+.reviews svg {
+ fill: rgba(0, 0, 0, 0.7);
+}
+.body {
+ clear: left;
+ margin: 8px;
+}
+.body a {
+ color: rgba(110, 110, 110, 1);
+ text-decoration: none;
+}
+.price {
+ display: none;
+}
+.button {
+ font-size: 14px;
+ font-weight: bold;
+ float: right;
+ margin: 0px 16px 16px 0px;
+ white-space: nowrap;
+}
+.button a {
+ color: #2196F3;
+ text-decoration: none;
+}
+.button svg {
+ display: none;
+}
+"""
+
+
+def main(client, html_snippet, css_snippet, creative_template_id, width,
+ height):
+ # Initialize appropriate service.
+ native_style_service = client.GetService('NativeStyleService',
+ version='v202205')
+
+ native_style = {
+ 'name': 'Native style #%d' % uuid.uuid4(),
+ 'htmlSnippet': html_snippet,
+ 'cssSnippet': css_snippet,
+ 'creativeTemplateId': creative_template_id,
+ 'size': {
+ 'width': width,
+ 'height': height,
+ 'isAspectRatio': False
+ }
+ }
+
+ # Create the native style on the server.
+ native_styles = native_style_service.createNativeStyles([native_style])
+
+ # Display results.
+ for native_style in native_styles:
+ print('A Native style with ID "%s", name "%s", and creative template ID'
+ '"%d" was created.' % (native_style['id'], native_style['name'],
+ native_style['creativeTemplateId']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, HTML_SNIPPET, CSS_SNIPPET, CREATIVE_TEMPLATE_ID,
+ WIDTH, HEIGHT)
diff --git a/examples/ad_manager/v202205/native_style_service/get_all_native_styles.py b/examples/ad_manager/v202205/native_style_service/get_all_native_styles.py
new file mode 100755
index 00000000..38a7d719
--- /dev/null
+++ b/examples/ad_manager/v202205/native_style_service/get_all_native_styles.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all native styles."""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ native_style_service = client.GetService('NativeStyleService',
+ version='v202205')
+
+ # Create a statement to select native styles.
+ statement = ad_manager.StatementBuilder(version='v202205')
+
+ # Retrieve a small amount of native styles at a time, paging
+ # through until all native styles have been retrieved.
+ while True:
+ response = native_style_service.getNativeStylesByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for native_style in response['results']:
+ # Print out some information for each native style.
+ print('Native style with ID "%d" and name "%s" was found.\n' %
+ (native_style['id'], native_style['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/network_service/__init__.py b/examples/ad_manager/v202205/network_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202205/network_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202205/network_service/get_all_networks.py b/examples/ad_manager/v202205/network_service/get_all_networks.py
new file mode 100755
index 00000000..3d4821a6
--- /dev/null
+++ b/examples/ad_manager/v202205/network_service/get_all_networks.py
@@ -0,0 +1,40 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all networks.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ network_service = client.GetService('NetworkService', version='v202205')
+
+ networks = network_service.getAllNetworks()
+
+ # Print out some information for each network.
+ for network in networks:
+ print('Network with network code "%s" and display name "%s" was found.'
+ % (network['networkCode'], network['displayName']))
+
+ print('\nNumber of results found: %s' % len(networks))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/network_service/get_current_network.py b/examples/ad_manager/v202205/network_service/get_current_network.py
new file mode 100755
index 00000000..2ec20444
--- /dev/null
+++ b/examples/ad_manager/v202205/network_service/get_current_network.py
@@ -0,0 +1,37 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets the current network."""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ network_service = client.GetService('NetworkService', version='v202205')
+
+ current_network = network_service.getCurrentNetwork()
+
+ print("Current network has network code '%s' and display name '%s'." %
+ (current_network['networkCode'], current_network['displayName']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/network_service/get_default_third_party_data_declaration.py b/examples/ad_manager/v202205/network_service/get_default_third_party_data_declaration.py
new file mode 100755
index 00000000..627896e9
--- /dev/null
+++ b/examples/ad_manager/v202205/network_service/get_default_third_party_data_declaration.py
@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+#
+# Copyright 2020, Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets the network's default third party data declarations."""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate services.
+ network_service = client.GetService('NetworkService', version='v202205')
+ pql_service = client.GetService('PublisherQueryLanguageService',
+ version='v202205')
+
+ # Fetch the default third party data declarations.
+ declarations = network_service.getDefaultThirdPartyDataDeclaration()
+
+ # Display the results.
+ if declarations is None:
+ print('No default ad technology partners have been set on this network.')
+ elif (declarations['declarationType'] == 'NONE' or
+ not declarations['thirdPartyCompanyIds']):
+ print('This network has specified that there are no ad technology providers'
+ ' associated with its reservation creatives by default.')
+ else:
+ print('This network has specified %d ad technology provider(s) associated'
+ ' with its reservation creatives by default:' %
+ len(declarations['thirdPartyCompanyIds']))
+
+ # In this case, there are third party companies to be displayed, so fetch
+ # the company names from the Rich_Media_Ad_Company PQL table.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Select('Id, Name')
+ .From('Rich_Media_Ad_Company')
+ .Where('Id IN (:company_ids)')
+ .WithBindVariable('company_ids',
+ declarations['thirdPartyCompanyIds']))
+
+ while True:
+ response = pql_service.select(statement.ToStatement())
+ if 'rows' in response and len(response['rows']):
+ for company in response['rows']:
+ print('Name: %s, id: %s' % (company['values'][1]['value'],
+ company['values'][0]['value']))
+ statement.offset += statement.limit
+ else:
+ break
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/network_service/make_test_network.py b/examples/ad_manager/v202205/network_service/make_test_network.py
new file mode 100755
index 00000000..d9ea4ab4
--- /dev/null
+++ b/examples/ad_manager/v202205/network_service/make_test_network.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example creates a test network.
+
+You do not need to have an Ad Manager account to run this example, but you do
+need to have a Google account (created at
+http://www.google.com/accounts/newaccount if you currently don't have one) that
+is not associated with any other Ad Manager test networks. Once this network is
+created, you can supply the network code in your settings to make calls to
+other services.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ network_service = client.GetService('NetworkService', version='v202205')
+
+ # Create a test network.
+ network = network_service.makeTestNetwork()
+
+ # Display results.
+ print('Test network with network code "%s" and display name "%s" '
+ 'created.' % (network['networkCode'], network['displayName']))
+ print('You may now sign in at '
+ 'http://www.google.com/admanager/main?networkCode=%s'
+ % network['networkCode'])
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/order_service/__init__.py b/examples/ad_manager/v202205/order_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202205/order_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202205/order_service/approve_orders.py b/examples/ad_manager/v202205/order_service/approve_orders.py
new file mode 100755
index 00000000..950ce011
--- /dev/null
+++ b/examples/ad_manager/v202205/order_service/approve_orders.py
@@ -0,0 +1,67 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example approves all eligible draft and pending orders.
+
+To determine which orders exist, run get_all_orders.py.
+"""
+
+
+import datetime
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ order_service = client.GetService('OrderService', version='v202205')
+
+ # Create a filter statement.
+ today = datetime.date.today()
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where(('status in (\'DRAFT\', \'PENDING_APPROVAL\') '
+ 'AND endDateTime >= :today AND isArchived = FALSE'))
+ .WithBindVariable('today', today))
+ orders_approved = 0
+
+ # Get orders by statement.
+ while True:
+ response = order_service.getOrdersByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ # Display results.
+ for order in response['results']:
+ print('Order with id "%s", name "%s", and status "%s" will be '
+ 'approved.' % (order['id'], order['name'], order['status']))
+ # Perform action.
+ result = order_service.performOrderAction(
+ {'xsi_type': 'ApproveOrders'}, statement.ToStatement())
+ if result and int(result['numChanges']) > 0:
+ orders_approved += int(result['numChanges'])
+ statement.offset += statement.limit
+ else:
+ break
+
+ # Display results.
+ if orders_approved > 0:
+ print('Number of orders approved: %s' % orders_approved)
+ else:
+ print('No orders were approved.')
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/order_service/create_orders.py b/examples/ad_manager/v202205/order_service/create_orders.py
new file mode 100755
index 00000000..23d30c34
--- /dev/null
+++ b/examples/ad_manager/v202205/order_service/create_orders.py
@@ -0,0 +1,59 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new orders.
+
+To determine which orders exist, run get_all_orders.py.
+"""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
+SALESPERSON_ID = 'INSERT_SALESPERSON_ID_HERE'
+TRAFFICKER_ID = 'INSERT_TRAFFICKER_ID_HERE'
+
+
+def main(client, company_id, salesperson_id, trafficker_id):
+ # Initialize appropriate service.
+ order_service = client.GetService('OrderService', version='v202205')
+
+ # Create order objects.
+ orders = []
+ for _ in range(5):
+ order = {
+ 'name': 'Order #%s' % uuid.uuid4(),
+ 'advertiserId': company_id,
+ 'salespersonId': salesperson_id,
+ 'traffickerId': trafficker_id
+ }
+ orders.append(order)
+
+ # Add orders.
+ orders = order_service.createOrders(orders)
+
+ # Display results.
+ for order in orders:
+ print('Order with id "%s" and name "%s" was created.'
+ % (order['id'], order['name']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, COMPANY_ID, SALESPERSON_ID, TRAFFICKER_ID)
diff --git a/examples/ad_manager/v202205/order_service/get_all_orders.py b/examples/ad_manager/v202205/order_service/get_all_orders.py
new file mode 100755
index 00000000..0051b584
--- /dev/null
+++ b/examples/ad_manager/v202205/order_service/get_all_orders.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all orders.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ order_service = client.GetService('OrderService', version='v202205')
+
+ # Create a statement to select orders.
+ statement = ad_manager.StatementBuilder(version='v202205')
+
+ # Retrieve a small amount of orders at a time, paging
+ # through until all orders have been retrieved.
+ while True:
+ response = order_service.getOrdersByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for order in response['results']:
+ # Print out some information for each order.
+ print('Order with ID "%d" and name "%s" was found.\n' % (order['id'],
+ order['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/order_service/get_orders_starting_soon.py b/examples/ad_manager/v202205/order_service/get_orders_starting_soon.py
new file mode 100755
index 00000000..22825114
--- /dev/null
+++ b/examples/ad_manager/v202205/order_service/get_orders_starting_soon.py
@@ -0,0 +1,60 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all orders that are starting soon.
+"""
+
+# Import appropriate modules from the client library.
+from datetime import datetime
+from datetime import timedelta
+
+from googleads import ad_manager
+import pytz
+
+
+def main(client):
+ # Initialize appropriate service.
+ order_service = client.GetService('OrderService', version='v202205')
+ now = datetime.now(tz=pytz.timezone('America/New_York'))
+ soon = now + timedelta(days=5)
+
+ # Create a statement to select orders.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where(('status = :status AND startDateTime >= :now '
+ 'AND startDateTime <= :soon'))
+ .WithBindVariable('status', 'APPROVED')
+ .WithBindVariable('now', now)
+ .WithBindVariable('soon', soon))
+
+ # Retrieve a small amount of orders at a time, paging
+ # through until all orders have been retrieved.
+ while True:
+ response = order_service.getOrdersByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for order in response['results']:
+ # Print out some information for each order.
+ print('Order with ID "%d" and name "%s" was found.\n' % (order['id'],
+ order['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/order_service/update_orders.py b/examples/ad_manager/v202205/order_service/update_orders.py
new file mode 100755
index 00000000..448d19f2
--- /dev/null
+++ b/examples/ad_manager/v202205/order_service/update_orders.py
@@ -0,0 +1,71 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates the notes of a single order specified by ID.
+
+To determine which orders exist, run get_all_orders.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+ORDER_ID = 'INSERT_ORDER_ID_HERE'
+
+
+def main(client, order_id):
+ # Initialize appropriate service.
+ order_service = client.GetService('OrderService', version='v202205')
+
+ # Create statement object to select a single order by an ID.
+
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('id = :orderId')
+ .WithBindVariable('orderId', int(order_id)))
+
+ # Get orders by statement.
+ response = order_service.getOrdersByStatement(statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ # Update each local order object by changing its notes.
+ updated_orders = []
+ for order in response['results']:
+ # Archived orders cannot be updated.
+ if not order['isArchived']:
+ order['notes'] = 'Spoke to advertiser. All is well.'
+ updated_orders.append(order)
+
+ # Update orders remotely.
+ orders = order_service.updateOrders(updated_orders)
+
+ # Display results.
+ if orders:
+ for order in orders:
+ print('Order with id "%s", name "%s", advertiser id "%s", and '
+ 'notes "%s" was updated.'
+ % (order['id'], order['name'], order['advertiserId'],
+ order['notes']))
+ else:
+ print('No orders were updated.')
+ else:
+ print('No orders found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ORDER_ID)
+
diff --git a/examples/ad_manager/v202205/placement_service/create_placements.py b/examples/ad_manager/v202205/placement_service/create_placements.py
new file mode 100755
index 00000000..9511270d
--- /dev/null
+++ b/examples/ad_manager/v202205/placement_service/create_placements.py
@@ -0,0 +1,108 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new placements for various ad unit sizes.
+
+To determine which placements exist, run get_all_placements.py.
+"""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ placement_service = client.GetService('PlacementService', version='v202205')
+ inventory_service = client.GetService('InventoryService', version='v202205')
+
+ # Create placement object to store medium rectangle ad units.
+ medium_rectangle_ad_unit_placement = {
+ 'name': 'Medium rectangle AdUnit Placement #%s' % uuid.uuid4(),
+ 'description': 'Contains ad units that hold creatives of size 300x250',
+ 'targetedAdUnitIds': []
+ }
+
+ # Create placement object to store skyscraper ad units.
+ skyscraper_ad_unit_placement = {
+ 'name': 'Skyscraper AdUnit Placement #%s' % uuid.uuid4(),
+ 'description': 'Contains ad units that hold creatives of size 120x600',
+ 'targetedAdUnitIds': []
+ }
+
+ # Create placement object to store banner ad units.
+ banner_ad_unit_placement = {
+ 'name': 'Banner AdUnit Placement #%s' % uuid.uuid4(),
+ 'description': 'Contains ad units that hold creatives of size 468x60',
+ 'targetedAdUnitIds': []
+ }
+
+ placement_list = []
+
+ # Create statement to get all the ad units.
+ statement = ad_manager.StatementBuilder(version='v202205')
+
+ while True:
+ response = inventory_service.getAdUnitsByStatement(
+ statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ # Separate the ad units by size.
+ for ad_unit in response['results']:
+ if 'adUnitSizes' in ad_unit:
+ for ad_unit_size in ad_unit['adUnitSizes']:
+ size = ad_unit_size['size']
+ if size['width'] == '300' and size['height'] == '250':
+ medium_rectangle_ad_unit_placement['targetedAdUnitIds'].append(
+ ad_unit['id'])
+ elif size['width'] == '120' and size['height'] == '600':
+ skyscraper_ad_unit_placement['targetedAdUnitIds'].append(
+ ad_unit['id'])
+ elif size['width'] == '468' and size['height'] == '60':
+ banner_ad_unit_placement['targetedAdUnitIds'].append(
+ ad_unit['id'])
+ statement.offset += statement.limit
+ else:
+ break
+
+ # Only create placements with one or more ad unit.
+ if medium_rectangle_ad_unit_placement['targetedAdUnitIds']:
+ placement_list.append(medium_rectangle_ad_unit_placement)
+
+ if skyscraper_ad_unit_placement['targetedAdUnitIds']:
+ placement_list.append(skyscraper_ad_unit_placement)
+
+ if banner_ad_unit_placement['targetedAdUnitIds']:
+ placement_list.append(banner_ad_unit_placement)
+
+ # Add placements.
+ placements = placement_service.createPlacements(placement_list)
+
+ # Display results.
+ for placement in placements:
+ ad_unit_ids = ''
+ if 'targetedAdUnitIds' in placement:
+ ad_unit_ids = ', '.join(placement['targetedAdUnitIds'])
+ print('A Placement with ID "%s", name "%s", and containing ad units '
+ '{%s} was created.' % (placement['id'], placement['name'],
+ ad_unit_ids))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/placement_service/deactivate_placements.py b/examples/ad_manager/v202205/placement_service/deactivate_placements.py
new file mode 100755
index 00000000..a87f587c
--- /dev/null
+++ b/examples/ad_manager/v202205/placement_service/deactivate_placements.py
@@ -0,0 +1,62 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example deactivates all active placements.
+
+To determine which placements exist, run get_all_placements.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+PLACEMENT_ID = 'INSERT_PLACEMENT_ID_HERE'
+
+
+def main(client, placement_id):
+ # Initialize appropriate service.
+ placement_service = client.GetService('PlacementService', version='v202205')
+
+ # Create query.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('id = :placementId')
+ .WithBindVariable('placementId', int(placement_id))
+ .Limit(1))
+
+ # Get placements by statement.
+ placements = placement_service.getPlacementsByStatement(
+ statement.ToStatement())
+
+ for placement in placements:
+ print('Placement with id "%s", name "%s", and status "%s" will be '
+ 'deactivated.' % (placement['id'], placement['name'],
+ placement['status']))
+
+ # Perform action.
+ result = placement_service.performPlacementAction(
+ {'xsi_type': 'DeactivatePlacements'}, statement.ToStatement())
+
+ # Display results.
+ if result and int(result['numChanges']) > 0:
+ print('Number of placements deactivated: %s' % result['numChanges'])
+ else:
+ print('No placements were deactivated.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, PLACEMENT_ID)
diff --git a/examples/ad_manager/v202205/placement_service/get_active_placements.py b/examples/ad_manager/v202205/placement_service/get_active_placements.py
new file mode 100755
index 00000000..6fd53640
--- /dev/null
+++ b/examples/ad_manager/v202205/placement_service/get_active_placements.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all active placements.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ placement_service = client.GetService('PlacementService', version='v202205')
+ # Create a statement to select placements.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('status = :status')
+ .WithBindVariable('status', 'ACTIVE'))
+
+ # Retrieve a small amount of placements at a time, paging
+ # through until all placements have been retrieved.
+ while True:
+ response = placement_service.getPlacementsByStatement(statement.ToStatement(
+ ))
+ if 'results' in response and len(response['results']):
+ for placement in response['results']:
+ # Print out some information for each placement.
+ print('Placement with ID "%d" and name "%s" was found.\n' %
+ (placement['id'], placement['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/placement_service/get_all_placements.py b/examples/ad_manager/v202205/placement_service/get_all_placements.py
new file mode 100755
index 00000000..ca051f46
--- /dev/null
+++ b/examples/ad_manager/v202205/placement_service/get_all_placements.py
@@ -0,0 +1,50 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all placements.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ placement_service = client.GetService('PlacementService', version='v202205')
+
+ # Create a statement to select placements.
+ statement = ad_manager.StatementBuilder(version='v202205')
+
+ # Retrieve a small amount of placements at a time, paging
+ # through until all placements have been retrieved.
+ while True:
+ response = placement_service.getPlacementsByStatement(statement.ToStatement(
+ ))
+ if 'results' in response and len(response['results']):
+ for placement in response['results']:
+ # Print out some information for each placement.
+ print('Placement with ID "%d" and name "%s" was found.\n' %
+ (placement['id'], placement['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/placement_service/update_placements.py b/examples/ad_manager/v202205/placement_service/update_placements.py
new file mode 100755
index 00000000..365b31a4
--- /dev/null
+++ b/examples/ad_manager/v202205/placement_service/update_placements.py
@@ -0,0 +1,58 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates a single placement to allow for AdSense targeting.
+
+To determine which placements exist, run get_all_placements.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+PLACEMENT_ID = 'INSERT_PLACEMENT_ID_HERE'
+
+
+def main(client, placement_id):
+ # Initialize appropriate service.
+ placement_service = client.GetService('PlacementService', version='v202205')
+
+ # Create query.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('id = :id')
+ .OrderBy('id', ascending=True)
+ .Limit(1)
+ .WithBindVariable('id', placement_id))
+
+ # Get placements by statement.
+ page = placement_service.getPlacementsByStatement(
+ statement.ToStatement())
+
+ placement = page['results'][0]
+
+ placement['description'] = 'This placement contains all leaderboards.'
+
+ # Update placements remotely.
+ updated_placements = placement_service.updatePlacements([placement])
+
+ for placement in updated_placements:
+ print('Placement with id "%s" and name "%s" was updated.'
+ % (placement['id'], placement['name']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, PLACEMENT_ID)
diff --git a/examples/ad_manager/v202205/proposal_line_item_service/__init__.py b/examples/ad_manager/v202205/proposal_line_item_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202205/proposal_line_item_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202205/proposal_line_item_service/archive_proposal_line_items.py b/examples/ad_manager/v202205/proposal_line_item_service/archive_proposal_line_items.py
new file mode 100755
index 00000000..b86f7de2
--- /dev/null
+++ b/examples/ad_manager/v202205/proposal_line_item_service/archive_proposal_line_items.py
@@ -0,0 +1,76 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example archives a proposal line item.
+
+To determine which proposal line items exist, run
+get_all_proposal_line_items.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the id of the proposal line item to archive.
+PROPOSAL_LINE_ITEM_ID = 'INSERT_PROPOSAL_LINE_ITEM_ID_HERE'
+
+
+def main(client, proposal_line_item_id):
+ # Initialize appropriate service.
+ proposal_line_item_service = client.GetService(
+ 'ProposalLineItemService', version='v202205')
+
+ # Create query.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('id = :id')
+ .WithBindVariable('id', int(proposal_line_item_id))
+ .Limit(1))
+
+ proposal_line_items_archived = 0
+
+ # Get proposal line items by statement.
+ while True:
+ response = proposal_line_item_service.getProposalLineItemsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for proposal_line_item in response['results']:
+ print('Proposal line item with id "%s", '
+ 'belonging to proposal id "%s", and '
+ 'name "%s" will be archived.' %
+ (proposal_line_item['id'], proposal_line_item['proposalId'],
+ proposal_line_item['name']))
+
+ # Perform action.
+ result = proposal_line_item_service.performProposalLineItemAction(
+ {'xsi_type': 'ArchiveProposalLineItems'}, statement.ToStatement())
+ if result and int(result['numChanges']) > 0:
+ proposal_line_items_archived += int(result['numChanges'])
+ statement.offset += statement.limit
+ else:
+ break
+
+ # Display results.
+ if proposal_line_items_archived > 0:
+ print('Number of proposal line items '
+ 'archived: %s' % proposal_line_items_archived)
+ else:
+ print('No proposal line items were archived.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, PROPOSAL_LINE_ITEM_ID)
diff --git a/examples/ad_manager/v202205/proposal_line_item_service/create_proposal_line_items.py b/examples/ad_manager/v202205/proposal_line_item_service/create_proposal_line_items.py
new file mode 100755
index 00000000..63e6a825
--- /dev/null
+++ b/examples/ad_manager/v202205/proposal_line_item_service/create_proposal_line_items.py
@@ -0,0 +1,108 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Creates a proposal line item."""
+
+
+import datetime
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+import pytz
+
+# Set proposal that the created proposal line item will belong to.
+PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE'
+
+
+def main(client, proposal_id):
+ proposal_line_item_service = client.GetService(
+ 'ProposalLineItemService', version='v202205')
+ network_service = client.GetService('NetworkService', version='v202205')
+
+ start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York'))
+ end_datetime = start_datetime + datetime.timedelta(days=365)
+
+ # Get the root ad unit to target.
+ root_ad_unit_id = (
+ network_service.getCurrentNetwork()['effectiveRootAdUnitId'])
+
+ # Create a single programmatic proposal line item.
+ proposal_line_item = {
+ # Setting common required fields for proposal line items.
+ 'name': 'Proposal line item #%s' % uuid.uuid4(),
+ 'proposalId': proposal_id,
+ 'targeting': {
+ 'inventoryTargeting': {
+ 'targetedAdUnits': {
+ 'adUnitId': root_ad_unit_id
+ }
+ },
+ 'requestPlatformTargeting': {
+ 'targetedRequestPlatforms': ['BROWSER']
+ },
+ # Target Display environment by excluding Mobile Apps.
+ # DeviceCapabilities can be obtained though the Device_Capability PQL
+ # table:
+ # https://developers.google.com/ad-manager/api/reference/latest/PublisherQueryLanguageService
+ 'technologyTargeting': {
+ 'deviceCapabilityTargeting': [{'id': 5005}]
+ }
+ },
+ 'startDateTime': start_datetime,
+ 'endDateTime': end_datetime,
+ 'creativePlaceholders': [
+ {
+ 'size': {
+ 'width': '300',
+ 'height': '250'
+ }
+ },
+ {
+ 'size': {
+ 'width': '120',
+ 'height': '600'
+ }
+ }
+ ],
+ 'goal': {
+ 'units': '1000',
+ 'unitType': 'IMPRESSIONS',
+ },
+ 'netRate': {
+ 'currencyCode': 'USD',
+ 'microAmount': '2000000'
+ },
+ 'rateType': 'CPM',
+ }
+
+ # Add proposal line items.
+ proposal_line_items = proposal_line_item_service.createProposalLineItems(
+ [proposal_line_item])
+
+ # Display results.
+ for proposal_line_item in proposal_line_items:
+ print('Proposal line item with id "%s", belonging to proposal with id "%s",'
+ ' and named "%s" was created.' % (proposal_line_item['id'],
+ proposal_line_item['proposalId'],
+ proposal_line_item['name']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, PROPOSAL_ID)
+
diff --git a/examples/ad_manager/v202205/proposal_line_item_service/get_all_proposal_line_items.py b/examples/ad_manager/v202205/proposal_line_item_service/get_all_proposal_line_items.py
new file mode 100755
index 00000000..94a7c9d0
--- /dev/null
+++ b/examples/ad_manager/v202205/proposal_line_item_service/get_all_proposal_line_items.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all proposal line items.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ proposal_line_item_service = client.GetService(
+ 'ProposalLineItemService', version='v202205')
+
+ # Create a statement to select proposal line items.
+ statement = ad_manager.StatementBuilder(version='v202205')
+
+ # Retrieve a small amount of proposal line items at a time, paging
+ # through until all proposal line items have been retrieved.
+ while True:
+ response = proposal_line_item_service.getProposalLineItemsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for proposal_line_item in response['results']:
+ # Print out some information for each proposal line item.
+ print('Proposal line item with ID "%d" and name "%s" was found.\n' %
+ (proposal_line_item['id'], proposal_line_item['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/ad_manager/v202205/proposal_line_item_service/get_proposal_line_items_for_proposal.py
new file mode 100755
index 00000000..9179dbae
--- /dev/null
+++ b/examples/ad_manager/v202205/proposal_line_item_service/get_proposal_line_items_for_proposal.py
@@ -0,0 +1,54 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all proposal line items belonging to a specific proposal.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE'
+
+
+def main(client, proposal_id):
+ # Initialize appropriate service.
+ proposal_line_item_service = client.GetService(
+ 'ProposalLineItemService', version='v202205')
+ # Create a statement to select proposal line items.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('proposalId = :proposalId')
+ .WithBindVariable('proposalId', proposal_id))
+
+ # Retrieve a small amount of proposal line items at a time, paging
+ # through until all proposal line items have been retrieved.
+ while True:
+ response = proposal_line_item_service.getProposalLineItemsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for proposal_line_item in response['results']:
+ # Print out some information for each proposal line item.
+ print('Proposal line item with ID "%d" and name "%s" was found.\n' %
+ (proposal_line_item['id'], proposal_line_item['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, PROPOSAL_ID)
diff --git a/examples/ad_manager/v202205/proposal_line_item_service/update_proposal_line_items.py b/examples/ad_manager/v202205/proposal_line_item_service/update_proposal_line_items.py
new file mode 100755
index 00000000..e32ba2e3
--- /dev/null
+++ b/examples/ad_manager/v202205/proposal_line_item_service/update_proposal_line_items.py
@@ -0,0 +1,72 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates a proposal line item's notes.
+
+To determine which proposal line items exist,
+run get_all_proposal_line_items.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set id of the proposal line item to update.
+PROPOSAL_LINE_ITEM_ID = 'INSERT_PROPOSAL_LINE_ITEM_ID_HERE'
+
+
+def main(client, proposal_line_item_id):
+ # Initialize appropriate service.
+ proposal_line_item_service = client.GetService(
+ 'ProposalLineItemService', version='v202205')
+
+ # Create statement to select a proposal line item.
+
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('id = :id')
+ .WithBindVariable('id', int(proposal_line_item_id))
+ .Limit(1))
+
+ # Get proposal line items by statement.
+ response = proposal_line_item_service.getProposalLineItemsByStatement(
+ statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ # Update each the proposal line item's notes field.
+ proposal_line_item = response['results'][0]
+ proposal_line_item['internalNotes'] = 'Proposal line is ready to submit.'
+
+ # Update proposal line items remotely.
+ proposal_line_items = proposal_line_item_service.updateProposalLineItems(
+ [proposal_line_item])
+
+ # Display results.
+ if proposal_line_items:
+ for proposal_line_item in proposal_line_items:
+ print('Line item with id "%s", belonging to proposal id "%s" and,'
+ ' named "%s" was updated.' % (
+ proposal_line_item['id'], proposal_line_item['proposalId'],
+ proposal_line_item['name']))
+ else:
+ print('No proposal line items were updated.')
+ else:
+ print('No proposal line items found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, PROPOSAL_LINE_ITEM_ID)
diff --git a/examples/ad_manager/v202205/proposal_service/__init__.py b/examples/ad_manager/v202205/proposal_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202205/proposal_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202205/proposal_service/create_proposals.py b/examples/ad_manager/v202205/proposal_service/create_proposals.py
new file mode 100755
index 00000000..d92cd562
--- /dev/null
+++ b/examples/ad_manager/v202205/proposal_service/create_proposals.py
@@ -0,0 +1,60 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example creates a proposal."""
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+PROGRAMMATIC_BUYER_ID = 'INSERT_BUYER_ID_FROM_PQL_TABLE_HERE'
+PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE'
+PRIMARY_TRAFFICKER_ID = 'INSERT_PRIMARY_TRAFFICKER_ID_HERE'
+
+
+def main(client, programmatic_buyer_id, primary_salesperson_id,
+ primary_trafficker_id):
+ proposal_service = client.GetService('ProposalService', version='v202205')
+
+ proposal = {
+ # Setting required Marketplace information.
+ 'isProgrammatic': 'true',
+ 'marketplaceInfo': {
+ 'buyerAccountId': programmatic_buyer_id,
+ },
+ # Set common required fields for proposals.
+ 'name': 'Proposal #%s' % uuid.uuid4(),
+ 'primarySalesperson': {
+ 'userId': primary_salesperson_id,
+ },
+ 'primaryTraffickerId': primary_trafficker_id,
+ 'probabilityOfClose': '100000',
+ }
+
+ proposals = proposal_service.createProposals([proposal])
+
+ # Display results.
+ for proposal in proposals:
+ print('Proposal with id "%s" and name "%s" was created.' %
+ (proposal['id'], proposal['name']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, PROGRAMMATIC_BUYER_ID, PRIMARY_SALESPERSON_ID,
+ PRIMARY_TRAFFICKER_ID)
diff --git a/examples/ad_manager/v202205/proposal_service/get_all_proposals.py b/examples/ad_manager/v202205/proposal_service/get_all_proposals.py
new file mode 100755
index 00000000..b2cfc3dc
--- /dev/null
+++ b/examples/ad_manager/v202205/proposal_service/get_all_proposals.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all proposals.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ proposal_service = client.GetService('ProposalService', version='v202205')
+
+ # Create a statement to select proposals.
+ statement = ad_manager.StatementBuilder(version='v202205')
+
+ # Retrieve a small amount of proposals at a time, paging
+ # through until all proposals have been retrieved.
+ while True:
+ response = proposal_service.getProposalsByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for proposal in response['results']:
+ # Print out some information for each proposal.
+ print('Proposal with ID "%d" and name "%s" was found.\n' %
+ (proposal['id'], proposal['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/proposal_service/get_marketplace_comments.py b/examples/ad_manager/v202205/proposal_service/get_marketplace_comments.py
new file mode 100755
index 00000000..3d8a9875
--- /dev/null
+++ b/examples/ad_manager/v202205/proposal_service/get_marketplace_comments.py
@@ -0,0 +1,56 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets the Marketplace comments for a programmatic proposal."""
+
+# Import appropriate modules from the client library.
+from datetime import datetime
+
+from googleads import ad_manager
+
+
+PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE'
+
+
+def main(client, proposal_id):
+ # Initialize appropriate service.
+ marketplace_comment_service = client.GetService(
+ 'ProposalService', version='v202205')
+ query = 'WHERE proposalId = %s' % proposal_id
+ # Create a statement to select marketplace comments.
+ statement = {'query': query}
+
+ response = marketplace_comment_service.getMarketplaceCommentsByStatement(
+ statement)
+
+ # Print out some information for each marketplace comment.
+ for marketplace_comment in response['results']:
+ date_time = marketplace_comment['creationTime']
+ date_time_string = datetime(date_time['date']['year'],
+ date_time['date']['month'],
+ date_time['date']['day'], date_time['hour'],
+ date_time['minute'],
+ date_time['second']).isoformat()
+ print('Marketplace comment with creation time "%s"and comment "%s" was '
+ 'found.\n' % (date_time_string, marketplace_comment['comment']))
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, PROPOSAL_ID)
diff --git a/examples/ad_manager/v202205/proposal_service/get_proposals_awaiting_seller_review.py b/examples/ad_manager/v202205/proposal_service/get_proposals_awaiting_seller_review.py
new file mode 100755
index 00000000..52ee216c
--- /dev/null
+++ b/examples/ad_manager/v202205/proposal_service/get_proposals_awaiting_seller_review.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all proposals awaiting seller review."""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ proposal_service = client.GetService('ProposalService', version='v202205')
+ # Create a statement to select proposals.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('negotiationStatus = :negotiationStatus')
+ .WithBindVariable('negotiationStatus', 'AWAITING_SELLER_REVIEW'))
+
+ # Retrieve a small amount of proposals at a time, paging
+ # through until all proposals have been retrieved.
+ while True:
+ response = proposal_service.getProposalsByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for proposal in response['results']:
+ # Print out some information for each proposal.
+ print('Proposal with ID "%d" and name "%s" was found.\n' %
+ (proposal['id'], proposal['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/proposal_service/request_buyers_acceptance.py b/examples/ad_manager/v202205/proposal_service/request_buyers_acceptance.py
new file mode 100755
index 00000000..0c30078c
--- /dev/null
+++ b/examples/ad_manager/v202205/proposal_service/request_buyers_acceptance.py
@@ -0,0 +1,67 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example requests buyer acceptance for a single proposal.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE'
+
+
+def main(client, proposal_id):
+ # Initialize appropriate service.
+ proposal_service = client.GetService('ProposalService', version='v202205')
+
+ # Create query.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('id = :proposalId')
+ .WithBindVariable('proposalId', proposal_id))
+ proposals_pushed_to_marketplace = 0
+
+ # Get proposals by statement.
+ while True:
+ response = proposal_service.getProposalsByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ # Display results.
+ for proposal in response['results']:
+ print('Programmatic proposal with id "%s", name "%s", and status '
+ '"%s" will be pushed to Marketplace.' % (proposal['id'],
+ proposal['name'],
+ proposal['status']))
+ # Perform action.
+ result = proposal_service.performProposalAction(
+ {'xsi_type': 'RequestBuyerAcceptance'}, statement.ToStatement())
+ if result and int(result['numChanges']) > 0:
+ proposals_pushed_to_marketplace += int(result['numChanges'])
+ statement.offset += statement.limit
+ else:
+ break
+
+ # Display results.
+ if proposals_pushed_to_marketplace > 0:
+ print('\nNumber of programmatic proposals pushed to Marketplace: %s'
+ % proposals_pushed_to_marketplace)
+ else:
+ print('\nNo programmatic proposals were pushed to Marketplace.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, PROPOSAL_ID)
diff --git a/examples/ad_manager/v202205/proposal_service/update_proposals.py b/examples/ad_manager/v202205/proposal_service/update_proposals.py
new file mode 100755
index 00000000..8de73911
--- /dev/null
+++ b/examples/ad_manager/v202205/proposal_service/update_proposals.py
@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates the notes of a single proposal specified by ID.
+
+To determine which proposals exist, run get_all_proposals.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE'
+
+
+def main(client, proposal_id):
+ # Initialize appropriate service.
+ proposal_service = client.GetService('ProposalService', version='v202205')
+
+ # Create statement object to select a single proposal by an ID.
+
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('id = :proposalId')
+ .WithBindVariable('proposalId', int(proposal_id))
+ .Limit(1))
+
+ # Get proposals by statement.
+ response = proposal_service.getProposalsByStatement(statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ # Update each local proposal object by changing its notes.
+ updated_proposals = []
+ for proposal in response['results']:
+ proposal['internalNotes'] = 'Proposal needs review before approval.'
+ updated_proposals.append(proposal)
+
+ # Update proposals remotely.
+ proposals = proposal_service.updateProposals(updated_proposals)
+
+ # Display results.
+ if proposals:
+ for proposal in proposals:
+ print('Proposal with id "%s", name "%s", and '
+ 'notes "%s" was updated.'
+ % (proposal['id'], proposal['name'], proposal['internalNotes']))
+ else:
+ print('No proposals were updated.')
+ else:
+ print('No proposals found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, PROPOSAL_ID)
diff --git a/examples/ad_manager/v202205/publisher_query_language_service/__init__.py b/examples/ad_manager/v202205/publisher_query_language_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202205/publisher_query_language_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202205/publisher_query_language_service/fetch_match_tables.py b/examples/ad_manager/v202205/publisher_query_language_service/fetch_match_tables.py
new file mode 100755
index 00000000..c60089f0
--- /dev/null
+++ b/examples/ad_manager/v202205/publisher_query_language_service/fetch_match_tables.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example fetches data from PQL tables and creates match table files."""
+
+
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize a report downloader.
+ report_downloader = client.GetDataDownloader(version='v202205')
+
+ line_items_file = tempfile.NamedTemporaryFile(
+ prefix='line_items_', suffix='.csv', mode='w', delete=False)
+ ad_units_file = tempfile.NamedTemporaryFile(
+ prefix='ad_units_', suffix='.csv', mode='w', delete=False)
+
+ line_items_pql_query = ('SELECT Name, Id, Status FROM Line_Item ORDER BY Id '
+ 'ASC')
+ ad_units_pql_query = 'SELECT Name, Id FROM Ad_Unit ORDER BY Id ASC'
+
+ # Downloads the response from PQL select statement to the specified file
+ report_downloader.DownloadPqlResultToCsv(
+ line_items_pql_query, line_items_file)
+ report_downloader.DownloadPqlResultToCsv(
+ ad_units_pql_query, ad_units_file)
+
+ line_items_file.close()
+ ad_units_file.close()
+
+ print('Saved line items to... %s' % line_items_file.name)
+ print('Saved ad units to... %s' % ad_units_file.name)
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/publisher_query_language_service/get_all_browsers.py b/examples/ad_manager/v202205/publisher_query_language_service/get_all_browsers.py
new file mode 100755
index 00000000..36f74419
--- /dev/null
+++ b/examples/ad_manager/v202205/publisher_query_language_service/get_all_browsers.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all browsers available to target from the Browser table.
+
+Other tables include 'Bandwidth_Group', 'Browser_Language',
+'Device_Capability', 'Operating_System', etc...
+
+A full list of available criteria tables can be found at
+https://developers.google.com/doubleclick-publishers/docs/reference/v201708/PublisherQueryLanguageService
+"""
+
+
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize a report downloader.
+ report_downloader = client.GetDataDownloader(version='v202205')
+
+ with tempfile.NamedTemporaryFile(
+ prefix='browser_data_',
+ suffix='.csv', mode='w', delete=False) as browser_data_file:
+
+ browser_pql_query = ('SELECT Id, BrowserName, MajorVersion, MinorVersion '
+ 'FROM Browser '
+ 'ORDER BY BrowserName ASC')
+
+ # Downloads the response from PQL select statement to the specified file
+ report_downloader.DownloadPqlResultToCsv(
+ browser_pql_query, browser_data_file)
+
+ print('Saved browser data to... %s' % browser_data_file.name)
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/ad_manager/v202205/publisher_query_language_service/get_all_programmatic_buyers.py
new file mode 100755
index 00000000..c59d0cc5
--- /dev/null
+++ b/examples/ad_manager/v202205/publisher_query_language_service/get_all_programmatic_buyers.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example fetches programmatic buyer information from the PQL table."""
+
+
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize a report downloader.
+ data_downloader = client.GetDataDownloader(version='v202205')
+
+ programmatic_buyers_file = tempfile.NamedTemporaryFile(
+ prefix='programmatic_buyers_', suffix='.csv', mode='w', delete=False)
+
+ programmatic_buyers_query = ('SELECT BuyerAccountId, Name '
+ 'FROM Programmatic_Buyer '
+ 'ORDER BY BuyerAccountId ASC')
+
+ # Downloads the response from PQL select statement to the specified file
+ data_downloader.DownloadPqlResultToCsv(
+ programmatic_buyers_query, programmatic_buyers_file)
+
+ programmatic_buyers_file.close()
+
+ print('Saved programmatic buyers to... %s' % programmatic_buyers_file.name)
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/publisher_query_language_service/get_geo_targets.py b/examples/ad_manager/v202205/publisher_query_language_service/get_geo_targets.py
new file mode 100755
index 00000000..864a8eda
--- /dev/null
+++ b/examples/ad_manager/v202205/publisher_query_language_service/get_geo_targets.py
@@ -0,0 +1,53 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example downloads geo targeting constants using PQL."""
+
+
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the type of geo target to query for.
+GEO_TARGET_TYPE = 'City'
+
+
+def main(client):
+ # Initialize a report downloader.
+ report_downloader = client.GetDataDownloader(version='v202205')
+
+ with tempfile.NamedTemporaryFile(
+ prefix='geo_data_',
+ suffix='.csv', mode='w', delete=False) as geo_data_file:
+
+ geo_pql_query = ('SELECT Id, Name, CanonicalParentId, ParentIds, '
+ 'CountryCode, Type '
+ 'FROM Geo_Target '
+ 'WHERE Type = :type AND Targetable = true '
+ 'ORDER BY CountryCode ASC, Name ASC')
+
+ # Downloads the response from PQL select statement to the specified file
+ report_downloader.DownloadPqlResultToCsv(
+ geo_pql_query, geo_data_file, {'type': geo_target_type})
+
+ print('Saved geo data to... %s' % geo_data_file.name)
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, GEO_TARGET_TYPE)
diff --git a/examples/ad_manager/v202205/publisher_query_language_service/get_line_items_named_like.py b/examples/ad_manager/v202205/publisher_query_language_service/get_line_items_named_like.py
new file mode 100755
index 00000000..f85af633
--- /dev/null
+++ b/examples/ad_manager/v202205/publisher_query_language_service/get_line_items_named_like.py
@@ -0,0 +1,48 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example fetches line items from the pql table with a LIKE clause."""
+
+
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize a report downloader.
+ report_downloader = client.GetDataDownloader(version='v202205')
+
+ with tempfile.NamedTemporaryFile(
+ prefix='line_items_',
+ suffix='.csv', mode='w', delete=False) as line_items_file:
+
+ line_items_pql_query = ("SELECT Id, Name, Status FROM Line_Item "
+ "WHERE Name LIKE 'line item%' "
+ "ORDER BY Id ASC")
+
+ # Downloads the response from PQL select statement to the specified file
+ report_downloader.DownloadPqlResultToCsv(
+ line_items_pql_query, line_items_file)
+
+ print('Saved line items to... %s' % line_items_file.name)
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/publisher_query_language_service/get_mcm_earnings.py b/examples/ad_manager/v202205/publisher_query_language_service/get_mcm_earnings.py
new file mode 100755
index 00000000..aadc556e
--- /dev/null
+++ b/examples/ad_manager/v202205/publisher_query_language_service/get_mcm_earnings.py
@@ -0,0 +1,58 @@
+#!/usr/bin/env python
+#
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets Multiple Customer Management earnings for the prior month.
+"""
+
+import datetime
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize a report downloader.
+ data_downloader = client.GetDataDownloader(version='v202205')
+
+ with tempfile.NamedTemporaryFile(
+ prefix='mcm_earnings_',
+ suffix='.csv', mode='w', delete=False) as mcm_earnings_file:
+
+ this_month_start = datetime.date.today().replace(day=1)
+ last_month_end = this_month_start - datetime.timedelta(days=1)
+ last_month_start = last_month_end.replace(day=1)
+
+ mcm_earnings_query = ('SELECT Month, ChildName, ChildNetworkCode, '
+ 'TotalEarningsCurrencyCode, TotalEarningsMicros, '
+ 'ParentPaymentCurrencyCode, ParentPaymentMicros, '
+ 'ChildPaymentCurrencyCode, ChildPaymentMicros, '
+ 'DeductionsMicros '
+ 'FROM Mcm_Earnings '
+ 'WHERE Month = :month '
+ 'ORDER BY ChildNetworkCode')
+
+ # Downloads the response from PQL select statement to the specified file
+ data_downloader.DownloadPqlResultToCsv(
+ mcm_earnings_query, mcm_earnings_file, {'month': last_month_start})
+
+ print('Saved MCM earnings to... %s' % mcm_earnings_file.name)
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/publisher_query_language_service/get_recent_changes.py b/examples/ad_manager/v202205/publisher_query_language_service/get_recent_changes.py
new file mode 100755
index 00000000..4391ce81
--- /dev/null
+++ b/examples/ad_manager/v202205/publisher_query_language_service/get_recent_changes.py
@@ -0,0 +1,156 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Gets recent changes in your network using the Change_History table.
+
+A full list of available tables can be found at:
+https://developers.google.com/doubleclick-publishers/docs/reference/latest/PublisherQueryLanguageService
+"""
+
+from datetime import date
+from datetime import datetime
+from datetime import timedelta
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+import pytz
+
+
+def main(client):
+ # Initialize appropriate service.
+ pql_service = client.GetService('PublisherQueryLanguageService', 'v202205')
+
+ end_date = datetime.now(tz=pytz.timezone('America/New_York'))
+ start_date = end_date - timedelta(days=1)
+ initial_query = ('ChangeDateTime > :startDateTime '
+ 'AND ChangeDateTime < :endDateTime')
+ pagination_query = 'Id < :id AND ' + initial_query
+
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Select(('Id, ChangeDateTime, EntityId, EntityType, '
+ 'Operation, UserId'))
+ .From('Change_History')
+ .Where(initial_query)
+ .OrderBy('ChangeDateTime', ascending=False)
+ .WithBindVariable('startDateTime', start_date)
+ .WithBindVariable('endDateTime', end_date))
+
+ keep_iterating = True
+ i = 0
+ total_rows = []
+
+ while keep_iterating:
+ response = pql_service.select(statement.ToStatement())
+ column_types = ([column_type['labelName']
+ for column_type in response['columnTypes']])
+ rows = response['rows']
+ rows_length = len(rows)
+ total_rows.extend(rows)
+
+ if rows and rows_length > 0:
+ # Get the earliest change ID in the result set.
+ last_row = rows[-1]
+ last_id = last_row['values'][0]['value']
+ i += 1
+
+ # Update the statement using the earliest row in the previous result.
+ statement.Where(pagination_query)
+ statement.WithBindVariable('id', last_id)
+
+ print('%d) %d changes prior to ID "%s" were found.\n'
+ % (i, rows_length, last_id))
+
+ keep_iterating = rows and len(rows) == statement.limit
+
+ # Print out columns header
+ print(','.join(column_types))
+
+ # Print out every row
+ for row in total_rows:
+ print(ConvertValueForCsv(row))
+
+
+def ConvertValueForCsv(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.
+ """
+ if 'value' in pql_value:
+ field = pql_value['value']
+ elif 'values' in pql_value:
+ field = pql_value['values']
+ else:
+ field = None
+
+ if field:
+ if isinstance(field, list):
+ return ','.join(['"%s"' % str(ConvertValueForCsv(single_field))
+ for single_field in field])
+ else:
+ class_type = ad_manager.AdManagerClassType(pql_value)
+
+ if class_type == 'TextValue':
+ return field.replace('"', '""').encode('UTF8')
+ elif class_type == 'NumberValue':
+ return float(field) if '.' in field else int(field)
+ elif class_type == 'DateTimeValue':
+ return ConvertDateTimeToOffset(field)
+ elif class_type == 'DateValue':
+ return date(int(field['date']['year']),
+ int(field['date']['month']),
+ int(field['date']['day'])).isoformat()
+ else:
+ return field
+ else:
+ return '-'
+
+
+def ConvertDateTimeToOffset(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 of the date time value uniform to
+ ReportService.
+ """
+ date_time_obj = datetime(int(date_time_value['date']['year']),
+ int(date_time_value['date']['month']),
+ int(date_time_value['date']['day']),
+ int(date_time_value['hour']),
+ int(date_time_value['minute']),
+ int(date_time_value['second']))
+ date_time_str = pytz.timezone(
+ date_time_value['timeZoneId']).localize(date_time_obj).isoformat()
+
+ if date_time_str[-5:] == '00:00':
+ return date_time_str[:-6] + 'Z'
+ else:
+ return date_time_str
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/report_service/__init__.py b/examples/ad_manager/v202205/report_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202205/report_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202205/report_service/run_delivery_report.py b/examples/ad_manager/v202205/report_service/run_delivery_report.py
new file mode 100755
index 00000000..d26b22be
--- /dev/null
+++ b/examples/ad_manager/v202205/report_service/run_delivery_report.py
@@ -0,0 +1,88 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Runs a report similar to the "Orders report" on the Ad Manager website.
+
+Includes additional attributes and can filter to include just one order.
+"""
+
+from datetime import datetime
+from datetime import timedelta
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+from googleads import errors
+
+ORDER_ID = 'INSERT_ORDER_ID_HERE'
+
+
+def main(client, order_id):
+ # Create statement object to filter for an order.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('ORDER_ID = :id')
+ .WithBindVariable('id', int(order_id))
+ .Limit(None) # No limit or offset for reports
+ .Offset(None))
+
+ # Set the start and end dates of the report to run (past 8 days).
+ end_date = datetime.now().date()
+ start_date = end_date - timedelta(days=8)
+
+ # Create report job.
+ report_job = {
+ 'reportQuery': {
+ 'dimensions': ['ORDER_ID', 'ORDER_NAME'],
+ 'dimensionAttributes': ['ORDER_TRAFFICKER', 'ORDER_START_DATE_TIME',
+ 'ORDER_END_DATE_TIME'],
+ 'statement': statement.ToStatement(),
+ 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS',
+ 'AD_SERVER_CTR', 'AD_SERVER_CPM_AND_CPC_REVENUE',
+ 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'],
+ 'dateRangeType': 'CUSTOM_DATE',
+ 'startDate': start_date,
+ 'endDate': end_date
+ }
+ }
+
+ # Initialize a DataDownloader.
+ report_downloader = client.GetDataDownloader(version='v202205')
+
+ try:
+ # Run the report and wait for it to finish.
+ report_job_id = report_downloader.WaitForReport(report_job)
+ except errors.AdManagerReportError as e:
+ print('Failed to generate report. Error was: %s' % e)
+
+ # Change to your preferred export format.
+ export_format = 'CSV_DUMP'
+
+ report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
+
+ # Download report data.
+ report_downloader.DownloadReportToFile(
+ report_job_id, export_format, report_file)
+
+ report_file.close()
+
+ # Display results.
+ print('Report job with id "%s" downloaded to:\n%s' % (
+ report_job_id, report_file.name))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ORDER_ID)
diff --git a/examples/ad_manager/v202205/report_service/run_inventory_report.py b/examples/ad_manager/v202205/report_service/run_inventory_report.py
new file mode 100755
index 00000000..1df7149d
--- /dev/null
+++ b/examples/ad_manager/v202205/report_service/run_inventory_report.py
@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example runs a typical daily inventory report."""
+
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+from googleads import errors
+
+
+def main(client):
+ # Initialize a DataDownloader.
+ report_downloader = client.GetDataDownloader(version='v202205')
+
+ # Create report job.
+ report_job = {
+ 'reportQuery': {
+ 'dimensions': ['DATE', 'AD_UNIT_NAME'],
+ 'adUnitView': 'HIERARCHICAL',
+ 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS',
+ 'AD_EXCHANGE_LINE_ITEM_LEVEL_IMPRESSIONS',
+ 'AD_EXCHANGE_LINE_ITEM_LEVEL_CLICKS',
+ 'TOTAL_LINE_ITEM_LEVEL_IMPRESSIONS',
+ 'TOTAL_LINE_ITEM_LEVEL_CPM_AND_CPC_REVENUE'],
+ 'dateRangeType': 'LAST_WEEK'
+ }
+ }
+
+ try:
+ # Run the report and wait for it to finish.
+ report_job_id = report_downloader.WaitForReport(report_job)
+ except errors.AdManagerReportError as e:
+ print('Failed to generate report. Error was: %s' % e)
+
+ # Change to your preferred export format.
+ export_format = 'CSV_DUMP'
+
+ report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
+
+ # Download report data.
+ report_downloader.DownloadReportToFile(
+ report_job_id, export_format, report_file)
+
+ report_file.close()
+
+ # Display results.
+ print('Report job with id "%s" downloaded to:\n%s' % (
+ report_job_id, report_file.name))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/report_service/run_reach_report.py b/examples/ad_manager/v202205/report_service/run_reach_report.py
new file mode 100755
index 00000000..dfd5fc3f
--- /dev/null
+++ b/examples/ad_manager/v202205/report_service/run_reach_report.py
@@ -0,0 +1,65 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example runs a reach report."""
+
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+from googleads import errors
+
+
+def main(client):
+ # Initialize a DataDownloader.
+ report_downloader = client.GetDataDownloader(version='v202205')
+
+ # Create report job.
+ report_job = {
+ 'reportQuery': {
+ 'dimensions': ['COUNTRY_NAME', 'LINE_ITEM_ID', 'LINE_ITEM_NAME'],
+ 'columns': ['UNIQUE_REACH_FREQUENCY', 'UNIQUE_REACH_IMPRESSIONS',
+ 'UNIQUE_REACH'],
+ 'dateRangeType': 'REACH_LIFETIME'
+ }
+ }
+
+ try:
+ # Run the report and wait for it to finish.
+ report_job_id = report_downloader.WaitForReport(report_job)
+ except errors.AdManagerReportError as e:
+ print('Failed to generate report. Error was: %s' % e)
+
+ # Change to your preferred export format.
+ export_format = 'CSV_DUMP'
+
+ report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
+
+ # Download report data.
+ report_downloader.DownloadReportToFile(
+ report_job_id, export_format, report_file)
+
+ report_file.close()
+
+ # Display results.
+ print('Report job with id "%s" downloaded to:\n%s' % (
+ report_job_id, report_file.name))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/report_service/run_reach_report_with_ad_unit_dimensions.py b/examples/ad_manager/v202205/report_service/run_reach_report_with_ad_unit_dimensions.py
new file mode 100755
index 00000000..5d5194d6
--- /dev/null
+++ b/examples/ad_manager/v202205/report_service/run_reach_report_with_ad_unit_dimensions.py
@@ -0,0 +1,69 @@
+#!/usr/bin/env python
+#
+# Copyright 2021 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example runs a reach report."""
+
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+from googleads import errors
+
+
+def main(client):
+ # Initialize a DataDownloader.
+ report_downloader = client.GetDataDownloader(version='v202205')
+
+ # Create report job.
+ report_job = {
+ 'reportQuery': {
+ # For Reach reports with AD_UNIT_ID or AD_UNIT_NAME in the dimensions
+ # list, adUnitView must be set to 'FLAT' or 'HIERARCHICAL'.
+ 'adUnitView': 'FLAT',
+ 'dimensions': ['MONTH_AND_YEAR', 'COUNTRY_NAME', 'AD_UNIT_ID',
+ 'AD_UNIT_NAME'],
+ 'columns': ['UNIQUE_REACH_FREQUENCY', 'UNIQUE_REACH_IMPRESSIONS',
+ 'UNIQUE_REACH'],
+ 'dateRangeType': 'LAST_MONTH'
+ }
+ }
+
+ try:
+ # Run the report and wait for it to finish.
+ report_job_id = report_downloader.WaitForReport(report_job)
+ except errors.AdManagerReportError as e:
+ print('Failed to generate report. Error was: %s' % e)
+
+ # Change to your preferred export format.
+ export_format = 'CSV_DUMP'
+
+ report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
+
+ # Download report data.
+ report_downloader.DownloadReportToFile(
+ report_job_id, export_format, report_file)
+
+ report_file.close()
+
+ # Display results.
+ print('Report job with id "%s" downloaded to:\n%s' % (
+ report_job_id, report_file.name))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/report_service/run_report_and_create_match_table.py b/examples/ad_manager/v202205/report_service/run_report_and_create_match_table.py
new file mode 100755
index 00000000..543c2e04
--- /dev/null
+++ b/examples/ad_manager/v202205/report_service/run_report_and_create_match_table.py
@@ -0,0 +1,88 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Runs a report for LineItems with additional data from a PQL table.
+
+Fetches a basic report over a network's LineItems and then adds some
+extra columns which might be useful for future analysis, such as
+LineItemType, from the PQL Line_Item table, creating a match table.
+"""
+
+from datetime import date
+from datetime import timedelta
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+from googleads import errors
+
+try:
+ import pandas
+except ImportError:
+ raise ImportError('This example requires the pandas library to be installed.')
+
+
+def main(client):
+ # Set the start and end dates of the report to run (past 8 days).
+ end_date = date.today()
+ start_date = end_date - timedelta(days=8)
+
+ # Create report job.
+ report_job = {
+ 'reportQuery': {
+ 'dimensions': ['LINE_ITEM_ID', 'LINE_ITEM_NAME'],
+ 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS',
+ 'AD_SERVER_CTR', 'AD_SERVER_CPM_AND_CPC_REVENUE',
+ 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'],
+ 'dateRangeType': 'CUSTOM_DATE',
+ 'startDate': start_date,
+ 'endDate': end_date
+ }
+ }
+
+ # Initialize a DataDownloader.
+ report_downloader = client.GetDataDownloader(version='v202205')
+
+ try:
+ # Run the report and wait for it to finish.
+ report_job_id = report_downloader.WaitForReport(report_job)
+ except errors.AdManagerReportError as e:
+ print('Failed to generate report. Error was: %s' % e)
+
+ with tempfile.NamedTemporaryFile(
+ suffix='.csv.gz', mode='wb', delete=False) as report_file:
+ # Download report data.
+ report_downloader.DownloadReportToFile(
+ report_job_id, 'CSV_DUMP', report_file)
+
+ # Create a PQL query to fetch the line item data
+ line_items_pql_query = ('SELECT Id, LineItemType, Status FROM LineItem')
+
+ # Download the response from PQL select statement
+ line_items = report_downloader.DownloadPqlResultToList(line_items_pql_query)
+
+ # Use pandas to join the two csv files into a match table
+ report = pandas.read_csv(report_file.name)
+ line_items = pandas.DataFrame(data=line_items[1:], columns=line_items[0])
+ merged_result = pandas.merge(report, line_items,
+ left_on='Dimension.LINE_ITEM_ID', right_on='id')
+ merged_result.to_csv('~/complete_line_items_report.csv', index=False)
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/report_service/run_report_with_custom_fields.py b/examples/ad_manager/v202205/report_service/run_report_with_custom_fields.py
new file mode 100755
index 00000000..45b7aa15
--- /dev/null
+++ b/examples/ad_manager/v202205/report_service/run_report_with_custom_fields.py
@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Runs a report with custom fields found in the line items of an order."""
+
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+from googleads import errors
+
+CUSTOM_FIELD_ID = 'INSERT_CUSTOM_FIELD_ID'
+CUSTOM_DIMENSION_KEY_ID = 'INSERT_CUSTOM_DIMENSION_KEY_ID'
+
+
+def main(client, custom_field_id, custom_dimension_key_id):
+ # Initialize a DataDownloader.
+ report_downloader = client.GetDataDownloader(version='v202205')
+
+ # Create report job.
+ report_job = {
+ 'reportQuery': {
+ 'dimensions': ['CUSTOM_DIMENSION', 'LINE_ITEM_ID', 'LINE_ITEM_NAME'],
+ 'columns': ['AD_SERVER_IMPRESSIONS'],
+ 'dateRangeType': 'LAST_MONTH',
+ 'customFieldIds': [custom_field_id],
+ 'customDimensionKeyIds': [custom_dimension_key_id]
+ }
+ }
+
+ try:
+ # Run the report and wait for it to finish.
+ report_job_id = report_downloader.WaitForReport(report_job)
+ except errors.AdManagerReportError as e:
+ print('Failed to generate report. Error was: %s' % e)
+
+ # Change to your preferred export format.
+ export_format = 'CSV_DUMP'
+
+ report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
+
+ # Download report data.
+ report_downloader.DownloadReportToFile(
+ report_job_id, export_format, report_file)
+
+ report_file.close()
+
+ # Display results.
+ print('Report job with id "%s" downloaded to:\n%s' % (
+ report_job_id, report_file.name))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CUSTOM_FIELD_ID, CUSTOM_DIMENSION_KEY_ID)
diff --git a/examples/ad_manager/v202205/report_service/run_sales_report.py b/examples/ad_manager/v202205/report_service/run_sales_report.py
new file mode 100755
index 00000000..ed1d1eaa
--- /dev/null
+++ b/examples/ad_manager/v202205/report_service/run_sales_report.py
@@ -0,0 +1,64 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Runs a report equal to the 'Sales by salespersons report'."""
+
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+from googleads import errors
+
+
+def main(client):
+ # Initialize a DataDownloader.
+ report_downloader = client.GetDataDownloader(version='v202205')
+
+ # Create report job.
+ report_job = {
+ 'reportQuery': {
+ 'dimensions': ['SALESPERSON_ID', 'SALESPERSON_NAME'],
+ 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CPM_AND_CPC_REVENUE',
+ 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'],
+ 'dateRangeType': 'LAST_MONTH'
+ }
+ }
+
+ try:
+ # Run the report and wait for it to finish.
+ report_job_id = report_downloader.WaitForReport(report_job)
+ except errors.AdManagerReportError as e:
+ print('Failed to generate report. Error was: %s' % e)
+
+ # Change to your preferred export format.
+ export_format = 'CSV_DUMP'
+
+ report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
+
+ # Download report data.
+ report_downloader.DownloadReportToFile(
+ report_job_id, export_format, report_file)
+
+ report_file.close()
+
+ # Display results.
+ print('Report job with id "%s" downloaded to:\n%s' % (
+ report_job_id, report_file.name))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/report_service/run_saved_query.py b/examples/ad_manager/v202205/report_service/run_saved_query.py
new file mode 100755
index 00000000..ea7bd0dc
--- /dev/null
+++ b/examples/ad_manager/v202205/report_service/run_saved_query.py
@@ -0,0 +1,80 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example runs a report from a saved query.
+"""
+
+# Import appropriate modules from the client library.
+import tempfile
+
+from googleads import ad_manager
+from googleads import errors
+
+SAVED_QUERY_ID = 'INSERT_SAVED_QUERY_ID_HERE'
+
+
+def main(client, saved_query_id):
+ # Initialize appropriate service.
+ report_service = client.GetService('ReportService', version='v202205')
+
+ # Initialize a DataDownloader.
+ report_downloader = client.GetDataDownloader(version='v202205')
+
+ # Create statement object to filter for an order.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('id = :id')
+ .WithBindVariable('id', int(saved_query_id))
+ .Limit(1))
+
+ response = report_service.getSavedQueriesByStatement(
+ statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ saved_query = response['results'][0]
+
+ if saved_query['isCompatibleWithApiVersion']:
+ report_job = {}
+
+ # Set report query and optionally modify it.
+ report_job['reportQuery'] = saved_query['reportQuery']
+
+ try:
+ # Run the report and wait for it to finish.
+ report_job_id = report_downloader.WaitForReport(report_job)
+ except errors.AdManagerReportError as e:
+ print('Failed to generate report. Error was: %s' % e)
+ # Change to your preferred export format.
+ export_format = 'CSV_DUMP'
+
+ report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
+
+ # Download report data.
+ report_downloader.DownloadReportToFile(
+ report_job_id, export_format, report_file)
+
+ report_file.close()
+
+ # Display results.
+ print('Report job with id "%s" downloaded to:\n%s' % (
+ report_job_id, report_file.name))
+ else:
+ print('The query specified is not compatible with the API version.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, SAVED_QUERY_ID)
diff --git a/examples/ad_manager/v202205/site_service/create_sites.py b/examples/ad_manager/v202205/site_service/create_sites.py
new file mode 100755
index 00000000..845a4041
--- /dev/null
+++ b/examples/ad_manager/v202205/site_service/create_sites.py
@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+#
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example creates a Site for Multiple Customer Management."""
+
+# Import appropriate modules from the client library.
+import sys
+from googleads import ad_manager
+
+# Set the URL and child network code for the Site.
+URL = 'INSERT_URL_HERE'
+CHILD_NETWORK_CODE = 'INSERT_CHILD_NETWORK_CODE_HERE'
+
+
+def main(client, url, child_network_code):
+ # Initialize appropriate services.
+ network_service = client.GetService('NetworkService', version='v202205')
+ site_service = client.GetService('SiteService', version='v202205')
+
+ # Check that the child network code is approved for MANAGE_INVENTORY by this
+ # network.
+ current_network = network_service.getCurrentNetwork()
+ child_network = None
+ for child in current_network['childPublishers']:
+ if child['childNetworkCode'] == child_network_code:
+ child_network = child
+
+ if child_network is None:
+ print(('Child network %s not found on the current network (%s). Cannot '
+ 'create site.') % (child_network_code,
+ current_network['networkCode']))
+ sys.exit(1)
+
+ if child_network['approvedDelegationType'] != 'MANAGE_INVENTORY':
+ print(('Child network %s has not approved for the current network (%s) '
+ 'to manage its inventory. Cannot create site.') % (
+ child_network_code, current_network['networkCode']))
+ sys.exit(1)
+
+ # Create site object.
+ site = {'url': url, 'childNetworkCode': child_network_code}
+
+ # Create the site on the server.
+ created_sites = site_service.createSites([site])
+
+ # Display results.
+ for site in created_sites:
+ print('Site with id %d and URL "%s" was created for child network %s.' % (
+ site['id'], site['url'], site['childNetworkCode']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, URL, CHILD_NETWORK_CODE)
diff --git a/examples/ad_manager/v202205/site_service/get_all_sites.py b/examples/ad_manager/v202205/site_service/get_all_sites.py
new file mode 100755
index 00000000..8420c04a
--- /dev/null
+++ b/examples/ad_manager/v202205/site_service/get_all_sites.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+#
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all Sites."""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ site_service = client.GetService('SiteService', version='v202205')
+
+ # Create a statement to select Sites.
+ statement = ad_manager.StatementBuilder(version='v202205')
+
+ # Retrieve a small number of sites at a time, paging through until all sites
+ # have been retrieved.
+ while True:
+ response = site_service.getSitesByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for site in response['results']:
+ # Print out some information for each site.
+ print('Site with Id %d and URL "%s" was found.' %
+ (site['id'], site['url']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/site_service/get_sites_requiring_approval.py b/examples/ad_manager/v202205/site_service/get_sites_requiring_approval.py
new file mode 100755
index 00000000..505c2c6b
--- /dev/null
+++ b/examples/ad_manager/v202205/site_service/get_sites_requiring_approval.py
@@ -0,0 +1,50 @@
+#!/usr/bin/env python
+#
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets Sites under MCM requiring review."""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ site_service = client.GetService('SiteService', version='v202205')
+
+ # Create a statement to select Sites needing approval.
+ statement = ad_manager.StatementBuilder(version='v202205').Where(
+ "approvalStatus = 'REQUIRES_REVIEW'")
+
+ # Retrieve a small number of sites at a time, paging through until all sites
+ # have been retrieved.
+ while True:
+ response = site_service.getSitesByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for site in response['results']:
+ # Print out some information for each site.
+ print('Site with Id %d and URL "%s" was found.' %
+ (site['id'], site['url']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/site_service/submit_sites_for_approval.py b/examples/ad_manager/v202205/site_service/submit_sites_for_approval.py
new file mode 100755
index 00000000..86b1bcdc
--- /dev/null
+++ b/examples/ad_manager/v202205/site_service/submit_sites_for_approval.py
@@ -0,0 +1,44 @@
+#!/usr/bin/env python
+#
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example submits a Site for approval."""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the id of the site to submit for approval.
+SITE_ID = 'INSERT_SITE_ID_HERE'
+
+
+def main(client):
+ # Initialize appropriate service.
+ site_service = client.GetService('SiteService', version='v202205')
+
+ # Create a statement to select Site.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('id = :id')
+ .WithBindVariable('id', SITE_ID))
+
+ response = site_service.performSiteAction(
+ {'xsi_type': 'SubmitSiteForApproval'}, statement.ToStatement())
+
+ print('\nNumber of sites changed: %s' % response['numChanges'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/suggested_ad_unit_service/__init__.py b/examples/ad_manager/v202205/suggested_ad_unit_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202205/suggested_ad_unit_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202205/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/ad_manager/v202205/suggested_ad_unit_service/approve_all_suggested_ad_units.py
new file mode 100755
index 00000000..028697fd
--- /dev/null
+++ b/examples/ad_manager/v202205/suggested_ad_unit_service/approve_all_suggested_ad_units.py
@@ -0,0 +1,70 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example approves all suggested ad units with 50 or more requests.
+
+This feature is only available to Ad Manager 360 solution networks.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+THRESHOLD_NUMBER_OF_REQUESTS = '50'
+
+
+def main(client):
+ # Initialize appropriate service.
+ suggested_ad_unit_service = client.GetService(
+ 'SuggestedAdUnitService', version='v202205')
+
+ # Create a filter statement.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('numRequests > :numRequests')
+ .WithBindVariable('numRequests', THRESHOLD_NUMBER_OF_REQUESTS))
+ num_approved_suggested_ad_units = 0
+
+ # Get suggested ad units by statement.
+ while True:
+ response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ # Print suggested ad units that will be approved.
+ for suggested_ad_unit in response['results']:
+ print('Suggested ad unit with id "%s", and number of requests "%s"'
+ ' will be approved.' % (suggested_ad_unit['id'],
+ suggested_ad_unit['numRequests']))
+
+ # Approve suggested ad units.
+ result = suggested_ad_unit_service.performSuggestedAdUnitAction(
+ {'xsi_type': 'ApproveSuggestedAdUnits'},
+ statement.ToStatement())
+ if result and int(result['numChanges']) > 0:
+ num_approved_suggested_ad_units += int(result['numChanges'])
+ else:
+ break
+
+ if num_approved_suggested_ad_units > 0:
+ print('Number of suggested ad units approved: %s' %
+ num_approved_suggested_ad_units)
+ else:
+ print('No suggested ad units were approved.')
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
+
diff --git a/examples/ad_manager/v202205/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/ad_manager/v202205/suggested_ad_unit_service/get_all_suggested_ad_units.py
new file mode 100755
index 00000000..ee1f267a
--- /dev/null
+++ b/examples/ad_manager/v202205/suggested_ad_unit_service/get_all_suggested_ad_units.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all suggested ad units.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ suggested_ad_unit_service = client.GetService(
+ 'SuggestedAdUnitService', version='v202205')
+
+ # Create a statement to select suggested ad units.
+ statement = ad_manager.StatementBuilder(version='v202205')
+
+ # Retrieve a small amount of suggested ad units at a time, paging
+ # through until all suggested ad units have been retrieved.
+ while True:
+ response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for suggested_ad_unit in response['results']:
+ # Print out some information for each suggested ad unit.
+ print(
+ 'Suggested ad unit with ID "%s" and num requests "%d" was found.\n'
+ % (suggested_ad_unit['id'], suggested_ad_unit['numRequests']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/ad_manager/v202205/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py
new file mode 100755
index 00000000..8c4816c1
--- /dev/null
+++ b/examples/ad_manager/v202205/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all highly requested suggested ad units.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+NUM_REQUESTS = 'INSERT_NUM_REQUESTS_HERE'
+
+
+def main(client, num_requests):
+ # Initialize appropriate service.
+ suggested_ad_unit_service = client.GetService(
+ 'SuggestedAdUnitService', version='v202205')
+ # Create a statement to select suggested ad units.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('numRequests >= :numRequests')
+ .WithBindVariable('numRequests', int(num_requests)))
+
+ # Retrieve a small amount of suggested ad units at a time, paging
+ # through until all suggested ad units have been retrieved.
+ while True:
+ response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for suggested_ad_unit in response['results']:
+ # Print out some information for each suggested ad unit.
+ print(
+ 'Suggested ad unit with ID "%s" and num requests "%d" was found.\n'
+ % (suggested_ad_unit['id'], suggested_ad_unit['numRequests']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, NUM_REQUESTS)
diff --git a/examples/ad_manager/v202205/targeting_preset_service/__init__.py b/examples/ad_manager/v202205/targeting_preset_service/__init__.py
new file mode 100755
index 00000000..6d126cce
--- /dev/null
+++ b/examples/ad_manager/v202205/targeting_preset_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2019 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202205/targeting_preset_service/get_all_targeting_presets.py b/examples/ad_manager/v202205/targeting_preset_service/get_all_targeting_presets.py
new file mode 100755
index 00000000..3ec9ba2b
--- /dev/null
+++ b/examples/ad_manager/v202205/targeting_preset_service/get_all_targeting_presets.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2019 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all targeting presets.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ targeting_preset_service = client.GetService(
+ 'TargetingPresetService', version='v202205')
+
+ # Create a statement to select suggested ad units.
+ statement = ad_manager.StatementBuilder(version='v202205')
+
+ # Retrieve a small number of targeting presets at a time, paging
+ # through until all targeting presets have been retrieved.
+ while True:
+ response = targeting_preset_service.getTargetingPresetsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for targeting_preset in response['results']:
+ # Print out some information for each targeting preset.
+ print(
+ 'Targeting preset with ID "%d" and name "%s" was found.\n'
+ % (targeting_preset['id'], targeting_preset['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/team_service/__init__.py b/examples/ad_manager/v202205/team_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202205/team_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202205/team_service/create_teams.py b/examples/ad_manager/v202205/team_service/create_teams.py
new file mode 100755
index 00000000..2e2f9e6b
--- /dev/null
+++ b/examples/ad_manager/v202205/team_service/create_teams.py
@@ -0,0 +1,60 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example creates new teams.
+
+To determine which teams exist, run get_all_teams.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+"""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ team_service = client.GetService('TeamService', version='v202205')
+
+ # Create team objects.
+ teams = []
+ for _ in range(5):
+ team = {
+ 'name': 'Team %s' % uuid.uuid4(),
+ 'hasAllCompanies': 'false',
+ 'hasAllInventory': 'false',
+ 'teamAccessType': 'READ_WRITE'
+ }
+ teams.append(team)
+
+ # Add Teams.
+ teams = team_service.createTeams(teams)
+
+ # Display results.
+ for team in teams:
+ print('Team with ID "%s" and name "%s" was created.'
+ % (team['id'], team['name']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/team_service/get_all_teams.py b/examples/ad_manager/v202205/team_service/get_all_teams.py
new file mode 100755
index 00000000..41dc5331
--- /dev/null
+++ b/examples/ad_manager/v202205/team_service/get_all_teams.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all teams.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ team_service = client.GetService('TeamService', version='v202205')
+
+ # Create a statement to select teams.
+ statement = ad_manager.StatementBuilder(version='v202205')
+
+ # Retrieve a small amount of teams at a time, paging
+ # through until all teams have been retrieved.
+ while True:
+ response = team_service.getTeamsByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for team in response['results']:
+ # Print out some information for each team.
+ print('Team with ID "%d" and name "%s" was found.\n' % (team['id'],
+ team['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/team_service/update_teams.py b/examples/ad_manager/v202205/team_service/update_teams.py
new file mode 100755
index 00000000..ca9c8eb9
--- /dev/null
+++ b/examples/ad_manager/v202205/team_service/update_teams.py
@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example updates teams by changing its description.
+
+To determine which teams exist, run get_all_teams.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+TEAM_ID = 'INSERT_TEAM_ID_HERE'
+
+
+def main(client, team_id):
+ # Initialize appropriate service.
+ team_service = client.GetService('TeamService', version='v202205')
+
+ # Create a filter statement to select a single team by ID.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('id = :teamId')
+ .WithBindVariable('teamId', int(team_id)))
+
+ # Get teams by statement.
+ response = team_service.getTeamsByStatement(statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ updated_teams = []
+ # Update each local team object by changing its description.
+ for team in response['results']:
+ team['description'] = 'this team is great!'
+ updated_teams.append(team)
+
+ # Update teams on the server.
+ teams = team_service.updateTeams(updated_teams)
+
+ # Display results.
+ for team in teams:
+ print('Team with id "%s" and name "%s" was updated.'
+ % (team['id'], team['name']))
+ else:
+ print('No teams found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, TEAM_ID)
diff --git a/examples/ad_manager/v202205/user_service/__init__.py b/examples/ad_manager/v202205/user_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202205/user_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202205/user_service/create_users.py b/examples/ad_manager/v202205/user_service/create_users.py
new file mode 100755
index 00000000..a17bb785
--- /dev/null
+++ b/examples/ad_manager/v202205/user_service/create_users.py
@@ -0,0 +1,57 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new users.
+
+To determine which users exist, run get_all_users.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+NEW_USER_EMAIL_ADDRESS = 'INSERT_EMAIL_ADDRESS_HERE'
+NEW_USER_NAME = 'INSERT_NAME_HERE'
+
+
+def main(client, email, name):
+ # Initialize appropriate service.
+ user_service = client.GetService('UserService', version='v202205')
+
+ # Create user objects.
+ users = [
+ {
+ 'email': email,
+ 'name': name,
+ }
+ ]
+ for user in users:
+ # Set the system defined ID of the trafficker role.
+ # To determine what other roles exist, run get_all_roles.py.
+ user['roleId'] = '-7'
+
+ # Add users.
+ users = user_service.createUsers(users)
+
+ # Display results.
+ for user in users:
+ print('User with id "%s", email "%s", and role "%s" was created.'
+ % (user['id'], user['email'], user['roleName']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, NEW_USER_EMAIL_ADDRESS, NEW_USER_NAME)
diff --git a/examples/ad_manager/v202205/user_service/deactivate_users.py b/examples/ad_manager/v202205/user_service/deactivate_users.py
new file mode 100755
index 00000000..cde52540
--- /dev/null
+++ b/examples/ad_manager/v202205/user_service/deactivate_users.py
@@ -0,0 +1,65 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example deactivates a user.
+
+Deactivated users can no longer make requests to the API. The user making the
+request cannot deactivate itself. To determine which users exist, run
+get_all_users.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+USER_ID = 'INSERT_USER_ID_TO_DEACTIVATE_HERE'
+
+
+def main(client, user_id):
+ # Initialize appropriate service.
+ user_service = client.GetService('UserService', version='v202205')
+
+ # Create query.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('id = :userId')
+ .WithBindVariable('userId', int(user_id)))
+
+ # Get users by statement.
+ response = user_service.getUsersByStatement(statement.ToStatement())
+ users = response['results'] if 'results' in response else []
+
+ for user in users:
+ print('User with id "%s", email "%s", and status "%s" will be '
+ 'deactivated.'
+ % (user['id'], user['email'],
+ {'true': 'ACTIVE', 'false': 'INACTIVE'}[user['isActive']]))
+ print('Number of users to be deactivated: %s' % len(users))
+
+ # Perform action.
+ result = user_service.performUserAction({'xsi_type': 'DeactivateUsers'},
+ statement.ToStatement())
+
+ # Display results.
+ if result and int(result['numChanges']) > 0:
+ print('Number of users deactivated: %s' % result['numChanges'])
+ else:
+ print('No users were deactivated.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, USER_ID)
diff --git a/examples/ad_manager/v202205/user_service/get_all_roles.py b/examples/ad_manager/v202205/user_service/get_all_roles.py
new file mode 100755
index 00000000..9d4161ad
--- /dev/null
+++ b/examples/ad_manager/v202205/user_service/get_all_roles.py
@@ -0,0 +1,40 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all roles.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ user_service = client.GetService('UserService', version='v202205')
+
+ roles = user_service.getAllRoles()
+
+ # Print out some information for each role.
+ for role in roles:
+ print('Role with id "%s" and name "%s" was found.' %
+ (role['id'], role['name']))
+
+ print('\nNumber of results found: %s' % len(roles))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/user_service/get_all_users.py b/examples/ad_manager/v202205/user_service/get_all_users.py
new file mode 100755
index 00000000..2b815308
--- /dev/null
+++ b/examples/ad_manager/v202205/user_service/get_all_users.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all users.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ user_service = client.GetService('UserService', version='v202205')
+
+ # Create a statement to select users.
+ statement = ad_manager.StatementBuilder(version='v202205')
+
+ # Retrieve a small amount of users at a time, paging
+ # through until all users have been retrieved.
+ while True:
+ response = user_service.getUsersByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for user in response['results']:
+ # Print out some information for each user.
+ print('User with ID "%d" and name "%s" was found.\n' % (user['id'],
+ user['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/user_service/get_current_user.py b/examples/ad_manager/v202205/user_service/get_current_user.py
new file mode 100755
index 00000000..7ac3bb5b
--- /dev/null
+++ b/examples/ad_manager/v202205/user_service/get_current_user.py
@@ -0,0 +1,38 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets the current user."""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ user_service = client.GetService('UserService', version='v202205')
+
+ # Get current user.
+ user = user_service.getCurrentUser()
+
+ print('User with ID %d, name "%s", email "%s", and role "%s" '
+ 'is the current user.' % (
+ user.id, user.name, user.email, user.roleName))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/user_service/get_user_by_email_address.py b/examples/ad_manager/v202205/user_service/get_user_by_email_address.py
new file mode 100755
index 00000000..13de3a79
--- /dev/null
+++ b/examples/ad_manager/v202205/user_service/get_user_by_email_address.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets users by email.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+EMAIL_ADDRESS = 'INSERT_EMAIL_ADDRESS_HERE'
+
+
+def main(client, email_address):
+ # Initialize appropriate service.
+ user_service = client.GetService('UserService', version='v202205')
+ # Create a statement to select users.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('email = :email')
+ .WithBindVariable('email', email_address))
+
+ # Retrieve a small amount of users at a time, paging
+ # through until all users have been retrieved.
+ while True:
+ response = user_service.getUsersByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for user in response['results']:
+ # Print out some information for each user.
+ print('User with ID "%d" and name "%s" was found.\n' % (user['id'],
+ user['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, EMAIL_ADDRESS)
diff --git a/examples/ad_manager/v202205/user_service/update_users.py b/examples/ad_manager/v202205/user_service/update_users.py
new file mode 100755
index 00000000..5da27af2
--- /dev/null
+++ b/examples/ad_manager/v202205/user_service/update_users.py
@@ -0,0 +1,58 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates a user by adding " Sr." to the end of their name.
+
+To determine which users exist, run get_all_users.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+USER_ID = 'INSERT_USER_ID_TO_UPDATE_HERE'
+
+
+def main(client, user_id):
+ # Initialize appropriate service.
+ user_service = client.GetService('UserService', version='v202205')
+
+ # Create query.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('id = :userId')
+ .WithBindVariable('userId', int(user_id)))
+
+ # Get users by statement.
+ response = user_service.getUsersByStatement(statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ users = response['results']
+ for user in users:
+ user['name'] += ' Sr.'
+
+ # Update users on server.
+ users = user_service.updateUsers(users)
+ for user in users:
+ print('User with id "%s" and name "%s" was updated.'
+ % (user['id'], user['name']))
+ else:
+ print('No users found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, USER_ID)
diff --git a/examples/ad_manager/v202205/user_team_association_service/__init__.py b/examples/ad_manager/v202205/user_team_association_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202205/user_team_association_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202205/user_team_association_service/create_user_team_associations.py b/examples/ad_manager/v202205/user_team_association_service/create_user_team_associations.py
new file mode 100755
index 00000000..4cc3d758
--- /dev/null
+++ b/examples/ad_manager/v202205/user_team_association_service/create_user_team_associations.py
@@ -0,0 +1,67 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example adds a user to a team by creating an association between them.
+
+To determine which teams exists, run get_all_teams.py. To determine which
+users exist, run get_all_users.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+TEAM_ID = 'INSERT_TEAM_ID_HERE'
+USER_IDS = ['INSERT_USER_IDS_TO_ASSOCIATE_TO_TEAM_HERE']
+
+
+def main(client, team_id, user_ids):
+ # Initialize appropriate service.
+ user_team_association_service = client.GetService(
+ 'UserTeamAssociationService', version='v202205')
+
+ user_team_associations = []
+ for user_id in user_ids:
+ user_team_associations.append(
+ {
+ 'teamId': team_id,
+ 'userId': user_id
+ })
+
+ # Create the user team association on the server.
+ user_team_associations = (
+ user_team_association_service.createUserTeamAssociations(
+ user_team_associations))
+
+ # Display results.
+ if user_team_associations:
+ for user_team_association in user_team_associations:
+ print('A user team association between user with ID "%s" and team with'
+ ' ID "%s"was created.' % (user_team_association['userId'],
+ user_team_association['teamId']))
+ else:
+ print('No user team associations created.')
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, TEAM_ID, USER_IDS)
diff --git a/examples/ad_manager/v202205/user_team_association_service/delete_user_team_associations.py b/examples/ad_manager/v202205/user_team_association_service/delete_user_team_associations.py
new file mode 100755
index 00000000..88fee344
--- /dev/null
+++ b/examples/ad_manager/v202205/user_team_association_service/delete_user_team_associations.py
@@ -0,0 +1,77 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example removes the user from all its teams.
+
+To determine which users exist, run get_all_users.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+USER_ID = 'INSERT_USER_ID_HERE'
+
+
+def main(client, user_id):
+ # Initialize appropriate service.
+ user_team_association_service = client.GetService(
+ 'UserTeamAssociationService', version='v202205')
+
+ # Create filter text to select user team associations by the user ID.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('userId = :userId')
+ .WithBindVariable('userId', int(user_id)))
+
+ # Get user team associations by statement.
+ response = user_team_association_service.getUserTeamAssociationsByStatement(
+ statement.ToStatement())
+ user_team_associations = response['results'] if 'results' in response else []
+
+ for user_team_association in user_team_associations:
+ print('User team association between user with ID "%s" and team with '
+ 'ID "%s" will be deleted.' % (user_team_association['userId'],
+ user_team_association['teamId']))
+ print('Number of teams that the user will be removed from: %s' %
+ len(user_team_associations))
+
+ # Action doesn't require limit/offset
+ statement.limit = None
+ statement.offset = None
+
+ # Perform action.
+ result = user_team_association_service.performUserTeamAssociationAction(
+ {'xsi_type': 'DeleteUserTeamAssociations'},
+ statement.ToStatement())
+
+ # Display results.
+ if result and int(result['numChanges']) > 0:
+ print('Number of teams that the user was removed from: %s'
+ % result['numChanges'])
+ else:
+ print('No user team associations were deleted.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, USER_ID)
diff --git a/examples/ad_manager/v202205/user_team_association_service/get_all_user_team_associations.py b/examples/ad_manager/v202205/user_team_association_service/get_all_user_team_associations.py
new file mode 100755
index 00000000..d90faff7
--- /dev/null
+++ b/examples/ad_manager/v202205/user_team_association_service/get_all_user_team_associations.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all user team associations.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ user_team_association_service = client.GetService(
+ 'UserTeamAssociationService', version='v202205')
+
+ # Create a statement to select user team associations.
+ statement = ad_manager.StatementBuilder(version='v202205')
+
+ # Retrieve a small amount of user team associations at a time, paging
+ # through until all user team associations have been retrieved.
+ while True:
+ response = user_team_association_service.getUserTeamAssociationsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for user_team_association in response['results']:
+ # Print out some information for each user team association.
+ print('User team association with team id "%d" and user id "%d" was '
+ 'found.\n' % (user_team_association['teamId'],
+ user_team_association['userId']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202205/user_team_association_service/get_user_team_associations_for_user.py b/examples/ad_manager/v202205/user_team_association_service/get_user_team_associations_for_user.py
new file mode 100755
index 00000000..5dc88ff0
--- /dev/null
+++ b/examples/ad_manager/v202205/user_team_association_service/get_user_team_associations_for_user.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all user team associations (i.e. teams) for a given user.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+USER_ID = 'INSERT_USER_ID_HERE'
+
+
+def main(client, user_id):
+ # Initialize appropriate service.
+ user_team_association_service = client.GetService(
+ 'UserTeamAssociationService', version='v202205')
+ # Create a statement to select user team associations.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('userId = :userId')
+ .WithBindVariable('userId', int(user_id)))
+
+ # Retrieve a small amount of user team associations at a time, paging
+ # through until all user team associations have been retrieved.
+ while True:
+ response = user_team_association_service.getUserTeamAssociationsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for user_team_association in response['results']:
+ # Print out some information for each user team association.
+ print('User team association with user ID "%d" and team ID "%d" was '
+ 'found.\n' % (user_team_association['userId'],
+ user_team_association['teamId']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, USER_ID)
diff --git a/examples/ad_manager/v202205/user_team_association_service/update_user_team_associations.py b/examples/ad_manager/v202205/user_team_association_service/update_user_team_associations.py
new file mode 100755
index 00000000..95b85b15
--- /dev/null
+++ b/examples/ad_manager/v202205/user_team_association_service/update_user_team_associations.py
@@ -0,0 +1,78 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example updates user team associations.
+
+It updates a user team association by setting the overridden access type to read
+only for all teams that the user belongs to. To determine which users exists,
+run get_all_users.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+USER_ID = 'INSERT_USER_ID_TO_UPDATE_HERE'
+
+
+def main(client, user_id):
+ # Initialize appropriate service.
+ user_team_association_service = client.GetService(
+ 'UserTeamAssociationService', version='v202205')
+
+ # Create filter text to select user team associations by the user ID.
+ statement = (ad_manager.StatementBuilder(version='v202205')
+ .Where('userId = :userId')
+ .WithBindVariable('userId', int(user_id)))
+
+ # Get user team associations by statement.
+ response = user_team_association_service.getUserTeamAssociationsByStatement(
+ statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ updated_user_team_associations = []
+ # Update each local user team association to read only access.
+ for user_team_association in response['results']:
+ user_team_association['overriddenTeamAccessType'] = 'READ_ONLY'
+ updated_user_team_associations.append(user_team_association)
+
+ # Update user team associations on the server.
+ user_team_associations = (
+ user_team_association_service.updateUserTeamAssociations(
+ updated_user_team_associations))
+
+ # Display results.
+ if user_team_associations:
+ for user_team_association in user_team_associations:
+ print('User team association between user with ID "%s" and team with'
+ ' ID "%s" was updated.' % (user_team_association['userId'],
+ user_team_association['teamId']))
+ else:
+ print('No user team associations were updated.')
+ else:
+ print('No user team associations found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, USER_ID)
diff --git a/examples/ad_manager/v202208/activity_group_service/__init__.py b/examples/ad_manager/v202208/activity_group_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202208/activity_group_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202208/activity_group_service/create_activity_groups.py b/examples/ad_manager/v202208/activity_group_service/create_activity_groups.py
new file mode 100755
index 00000000..aacf9fcf
--- /dev/null
+++ b/examples/ad_manager/v202208/activity_group_service/create_activity_groups.py
@@ -0,0 +1,71 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new activity groups.
+
+To determine which activity groups exist, run get_all_activity_groups.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the advertiser company this activity group is associated with.
+ADVERTISER_COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
+
+
+def main(client, advertiser_company_id):
+ # Initialize appropriate service.
+ activity_group_service = client.GetService('ActivityGroupService',
+ version='v202208')
+
+ # Create a short-term activity group.
+ short_term_activity_group = {
+ 'name': 'Short-term activity group #%s' % uuid.uuid4(),
+ 'companyIds': [advertiser_company_id],
+ 'clicksLookback': '1',
+ 'impressionsLookback': '1'
+ }
+
+ # Create a long-term activity group.
+ long_term_activity_group = {
+ 'name': 'Long-term activity group #%s' % uuid.uuid4(),
+ 'companyIds': [advertiser_company_id],
+ 'clicksLookback': '30',
+ 'impressionsLookback': '30'
+ }
+
+ # Create the activity groups on the server.
+ activity_groups = activity_group_service.createActivityGroups([
+ short_term_activity_group, long_term_activity_group])
+
+ # Display results.
+ for activity_group in activity_groups:
+ print('Activity group with ID "%s" and name "%s" was created.'
+ % (activity_group['id'], activity_group['name']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ADVERTISER_COMPANY_ID)
diff --git a/examples/ad_manager/v202208/activity_group_service/get_active_activity_groups.py b/examples/ad_manager/v202208/activity_group_service/get_active_activity_groups.py
new file mode 100755
index 00000000..1d2d5c9f
--- /dev/null
+++ b/examples/ad_manager/v202208/activity_group_service/get_active_activity_groups.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all active activity groups.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ activity_group_service = client.GetService(
+ 'ActivityGroupService', version='v202208')
+ # Create a statement to select activity groups.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('status = :status')
+ .WithBindVariable('status', 'ACTIVE'))
+
+ # Retrieve a small amount of activity groups at a time, paging
+ # through until all activity groups have been retrieved.
+ while True:
+ response = activity_group_service.getActivityGroupsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for activity_group in response['results']:
+ # Print out some information for each activity group.
+ print('Activity group with ID "%d" and name "%s" was found.\n' %
+ (activity_group['id'], activity_group['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/activity_group_service/get_all_activity_groups.py b/examples/ad_manager/v202208/activity_group_service/get_all_activity_groups.py
new file mode 100755
index 00000000..d715b9b1
--- /dev/null
+++ b/examples/ad_manager/v202208/activity_group_service/get_all_activity_groups.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all activity groups.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ activity_group_service = client.GetService(
+ 'ActivityGroupService', version='v202208')
+
+ # Create a statement to select activity groups.
+ statement = ad_manager.StatementBuilder(version='v202208')
+
+ # Retrieve a small amount of activity groups at a time, paging
+ # through until all activity groups have been retrieved.
+ while True:
+ response = activity_group_service.getActivityGroupsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for activity_group in response['results']:
+ # Print out some information for each activity group.
+ print('Activity group with ID "%d" and name "%s" was found.\n' %
+ (activity_group['id'], activity_group['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/activity_group_service/update_activity_groups.py b/examples/ad_manager/v202208/activity_group_service/update_activity_groups.py
new file mode 100755
index 00000000..d4f6e528
--- /dev/null
+++ b/examples/ad_manager/v202208/activity_group_service/update_activity_groups.py
@@ -0,0 +1,70 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates activity groups.
+
+To determine which activity groups exist, run get_all_activity_groups.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the activity group and the company to update it with.
+ACTIVITY_GROUP_ID = 'INSERT_ACTIVITY_GROUP_ID_HERE'
+ADVERTISER_COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
+
+
+def main(client, activity_group_id, advertiser_company_id):
+ # Initialize appropriate service.
+ activity_group_service = client.GetService('ActivityGroupService',
+ version='v202208')
+
+ # Create statement object to select a single activity groups by ID.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('id = :activityGroupId')
+ .WithBindVariable('activityGroupId', int(activity_group_id))
+ .Limit(1))
+
+ # Get activity groups by statement.
+ response = activity_group_service.getActivityGroupsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ updated_activity_groups = []
+ for activity_group in response['results']:
+ activity_group['companyIds'].append(advertiser_company_id)
+ updated_activity_groups.append(activity_group)
+ # Update the activity groups on the server.
+ activity_groups = activity_group_service.updateActivityGroups(
+ updated_activity_groups)
+
+ for activity_group in activity_groups:
+ print(('Activity group with ID "%s" and name "%s" was updated.')
+ % (activity_group['id'], activity_group['name']))
+ else:
+ print('No activity groups found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ACTIVITY_GROUP_ID, ADVERTISER_COMPANY_ID)
diff --git a/examples/ad_manager/v202208/activity_service/__init__.py b/examples/ad_manager/v202208/activity_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202208/activity_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202208/activity_service/create_activities.py b/examples/ad_manager/v202208/activity_service/create_activities.py
new file mode 100755
index 00000000..2a57c11b
--- /dev/null
+++ b/examples/ad_manager/v202208/activity_service/create_activities.py
@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new activities.
+
+To determine which activities groups exist, run get_all_activities.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the activity group this activity is associated with.
+ACTIVITY_GROUP_ID = 'INSERT_ACTIVITY_GROUP_ID_HERE'
+
+
+def main(client, activity_group_id):
+ # Initialize appropriate service.
+ activity_service = client.GetService('ActivityService', version='v202208')
+
+ # Create a daily visits activity.
+ daily_visits_activity = {
+ 'name': 'Activity #%s' % uuid.uuid4(),
+ 'activityGroupId': activity_group_id,
+ 'type': 'DAILY_VISITS'
+ }
+
+ # Create a custom activity.
+ custom_activity = {
+ 'name': 'Activity #%s' % uuid.uuid4(),
+ 'activityGroupId': activity_group_id,
+ 'type': 'CUSTOM'
+ }
+
+ # Create the activities on the server.
+ activities = activity_service.createActivities([
+ daily_visits_activity, custom_activity])
+
+ # Display results.
+ for activity in activities:
+ print('An activity with ID "%s", name "%s", and type "%s" was '
+ 'created.' % (activity['id'], activity['name'], activity['type']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ACTIVITY_GROUP_ID)
diff --git a/examples/ad_manager/v202208/activity_service/get_active_activities.py b/examples/ad_manager/v202208/activity_service/get_active_activities.py
new file mode 100755
index 00000000..2d98022c
--- /dev/null
+++ b/examples/ad_manager/v202208/activity_service/get_active_activities.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all active activities.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ activity_service = client.GetService('ActivityService', version='v202208')
+ # Create a statement to select activities.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('status = :status')
+ .WithBindVariable('status', 'ACTIVE'))
+
+ # Retrieve a small amount of activities at a time, paging
+ # through until all activities have been retrieved.
+ while True:
+ response = activity_service.getActivitiesByStatement(statement.ToStatement(
+ ))
+ if 'results' in response and len(response['results']):
+ for activity in response['results']:
+ # Print out some information for each activity.
+ print('Activity with ID "%d", name "%s", and type "%s" was found.\n' %
+ (activity['id'], activity['name'], activity['type']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/activity_service/get_all_activities.py b/examples/ad_manager/v202208/activity_service/get_all_activities.py
new file mode 100755
index 00000000..988cacce
--- /dev/null
+++ b/examples/ad_manager/v202208/activity_service/get_all_activities.py
@@ -0,0 +1,50 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all activities.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ activity_service = client.GetService('ActivityService', version='v202208')
+
+ # Create a statement to select activities.
+ statement = ad_manager.StatementBuilder(version='v202208')
+
+ # Retrieve a small amount of activities at a time, paging
+ # through until all activities have been retrieved.
+ while True:
+ response = activity_service.getActivitiesByStatement(statement.ToStatement(
+ ))
+ if 'results' in response and len(response['results']):
+ for activity in response['results']:
+ # Print out some information for each activity.
+ print('Activity with ID "%d" and name "%s" was found.\n' %
+ (activity['id'], activity['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/activity_service/update_activities.py b/examples/ad_manager/v202208/activity_service/update_activities.py
new file mode 100755
index 00000000..69eba66c
--- /dev/null
+++ b/examples/ad_manager/v202208/activity_service/update_activities.py
@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates activities.
+
+To determine which activities exist, run get_all_activities.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the activity to update.
+ACTIVITY_ID = 'INSERT_ACTIVITY_ID_HERE'
+
+
+def main(client, activity_id):
+ # Initialize appropriate service.
+ activity_service = client.GetService('ActivityService', version='v202208')
+
+ # Create statement object to select one activity by ID to update.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('id = :activityId')
+ .WithBindVariable('activityId', int(activity_id))
+ .Limit(1))
+
+ # Get activities by statement.
+ response = activity_service.getActivitiesByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ updated_activities = []
+ for activity in response['results']:
+ # Update the expected URL.
+ activity['expectedURL'] = 'https://google.com'
+ updated_activities.append(activity)
+ # Update the activity on the server.
+ activities = activity_service.updateActivities(updated_activities)
+
+ for updated_activity in activities:
+ print(('Activity with ID "%s" and name "%s" was updated.')
+ % (updated_activity['id'], updated_activity['name']))
+ else:
+ print('No activities found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ACTIVITY_ID)
diff --git a/examples/ad_manager/v202208/adjustment_service/create_forecast_adjustments.py b/examples/ad_manager/v202208/adjustment_service/create_forecast_adjustments.py
new file mode 100755
index 00000000..74b2bae6
--- /dev/null
+++ b/examples/ad_manager/v202208/adjustment_service/create_forecast_adjustments.py
@@ -0,0 +1,65 @@
+#!/usr/bin/env python
+#
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example creates a forecast adjustment for New Year's Day traffic."""
+
+import datetime
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+TRAFFIC_FORECAST_SEGMENT_ID = 'INSERT_TRAFFIC_FORECAST_SEGMENT_ID_HERE'
+
+
+def main(client, traffic_forecast_segment_id):
+ # Initialize the adjustment service.
+ adjustment_service = client.GetService('AdjustmentService', version='v202208')
+
+ # Create a new forecast adjustment for New Year's Day traffic.
+ this_new_years = datetime.date(datetime.date.today().year, 1, 1)
+ next_new_years = datetime.date(datetime.date.today().year + 1, 1, 1)
+
+ forecast = {
+ 'name': 'Forecast adjustment #%s' % uuid.uuid4(),
+ 'trafficForecastSegmentId': traffic_forecast_segment_id,
+ 'dateRange': {
+ 'startDate': next_new_years,
+ 'endDate': next_new_years
+ },
+ 'status': 'ACTIVE',
+ 'volumeType': 'HISTORICAL_BASIS_VOLUME',
+ 'historicalBasisVolumeSettings': {
+ 'useParentTrafficForecastSegmentTargeting': True,
+ 'historicalDateRange': {
+ 'startDate': this_new_years,
+ 'endDate': this_new_years
+ },
+ 'multiplierMilliPercent': 110000
+ }
+ }
+
+ forecasts = adjustment_service.createForecastAdjustments([forecast])
+
+ for forecast in forecasts:
+ print('Forecast adjustment with id %d and name "%s" was created.' % (
+ forecast['id'], forecast['name']
+ ))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, TRAFFIC_FORECAST_SEGMENT_ID)
diff --git a/examples/ad_manager/v202208/adjustment_service/create_traffic_forecast_segments.py b/examples/ad_manager/v202208/adjustment_service/create_traffic_forecast_segments.py
new file mode 100755
index 00000000..58c8510b
--- /dev/null
+++ b/examples/ad_manager/v202208/adjustment_service/create_traffic_forecast_segments.py
@@ -0,0 +1,72 @@
+#!/usr/bin/env python
+#
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example creates a traffic forecast segment for all ad units in the U.S.
+"""
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize the adjustment service and the network service.
+ adjustment_service = client.GetService('AdjustmentService', version='v202208')
+ network_service = client.GetService('NetworkService', version='v202208')
+
+ # Get the root ad unit id to target the whole site.
+ current_network = network_service.getCurrentNetwork()
+ root_ad_unit_id = current_network['effectiveRootAdUnitId']
+
+ # Create inventory targeting.
+ inventory_targeting = {
+ 'targetedAdUnits': [{
+ 'includeDescendants': True,
+ 'adUnitId': root_ad_unit_id
+ }]
+ }
+
+ # Create targeting for United States traffic.
+ geo_targeting = {
+ 'targetedLocations': [{
+ 'id': 2840
+ }]
+ }
+
+ # Create traffic forecast segment object.
+ segment = {
+ 'name': 'Forecast segment #%s' % uuid.uuid4(),
+ 'targeting': {
+ 'inventoryTargeting': inventory_targeting,
+ 'geoTargeting': geo_targeting
+ }
+ }
+
+ # Create the traffic forecast segment on the server.
+ segments = adjustment_service.createTrafficForecastSegments([segment])
+
+ # Display the results.
+ for segment in segments:
+ print('Traffic forecast segment with id %d and %d forecast adjustments was '
+ 'created.' % (segment['id'],
+ segment['forecastAdjustmentCount']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/adjustment_service/get_all_forecast_adjustments.py b/examples/ad_manager/v202208/adjustment_service/get_all_forecast_adjustments.py
new file mode 100755
index 00000000..8b2958a3
--- /dev/null
+++ b/examples/ad_manager/v202208/adjustment_service/get_all_forecast_adjustments.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all forecast adjustments."""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize the adjustment service.
+ adjustment_service = client.GetService('AdjustmentService', version='v202208')
+
+ # Create a statement to get all forecast adjustments.
+ statement = ad_manager.StatementBuilder(version='v202208')
+
+ # Retrieve a small number of forecast adjustments at a time, paging
+ # through until all forecast adjustments have been retrieved.
+ while True:
+ response = adjustment_service.getForecastAdjustmentsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for adjustment in response['results']:
+ # Print out some information for each forecast adjustment.
+ print('Forecast adjustment with id %d and name "%s" belonging to '
+ 'forecast segment %d was found.' %
+ (adjustment['id'], adjustment['name'],
+ adjustment['trafficForecastSegmentId']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/adjustment_service/get_all_traffic_forecast_segments.py b/examples/ad_manager/v202208/adjustment_service/get_all_traffic_forecast_segments.py
new file mode 100755
index 00000000..c676a836
--- /dev/null
+++ b/examples/ad_manager/v202208/adjustment_service/get_all_traffic_forecast_segments.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+#
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all traffic forecast segments."""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize the adjustment service.
+ adjustment_service = client.GetService('AdjustmentService', version='v202208')
+
+ # Create a statement to get all traffic forecast segments.
+ statement = ad_manager.StatementBuilder(version='v202208')
+
+ # Retrieve a small number of segments at a time, paging through until all
+ # segments have been retrieved.
+ while True:
+ response = adjustment_service.getTrafficForecastSegmentsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for segment in response['results']:
+ # Print out some information for each traffic forecast segment.
+ print('Traffic forecast segment with id %d and name "%s" was found ' % (
+ segment['id'], segment['name'],
+ ))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py b/examples/ad_manager/v202208/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py
new file mode 100755
index 00000000..d7e3d465
--- /dev/null
+++ b/examples/ad_manager/v202208/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py
@@ -0,0 +1,57 @@
+#!/usr/bin/env python
+#
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all forecast adjustments for a traffic forecast segment."""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+TRAFFIC_FORECAST_SEGMENT_ID = 'INSERT_FORECAST_SEGMENT_ID_HERE'
+
+
+def main(client, traffic_forecast_segment_id):
+ # Initialize the adjustment service.
+ adjustment_service = client.GetService('AdjustmentService', version='v202208')
+
+ # Create a statement to get forecast adjustments for a given traffic forecast
+ # segment id.
+ statement = ad_manager.StatementBuilder(version='v202208').Where(
+ 'trafficForecastSegmentId = :segmentId').WithBindVariable(
+ 'segmentId', traffic_forecast_segment_id)
+
+ # Retrieve a small number of forecast adjustments at a time, paging
+ # through until all forecast adjustments have been retrieved.
+ while True:
+ response = adjustment_service.getForecastAdjustmentsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for adjustment in response['results']:
+ # Print out some information for each traffic adjustment.
+ print('Forecast adjustment with id %d and name "%s" belonging to '
+ 'forecast segment %d was found.' %
+ (adjustment['id'], adjustment['name'],
+ adjustment['trafficForecastSegmentId']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, int(TRAFFIC_FORECAST_SEGMENT_ID))
diff --git a/examples/ad_manager/v202208/adjustment_service/update_forecast_adjustments.py b/examples/ad_manager/v202208/adjustment_service/update_forecast_adjustments.py
new file mode 100755
index 00000000..d78de2ca
--- /dev/null
+++ b/examples/ad_manager/v202208/adjustment_service/update_forecast_adjustments.py
@@ -0,0 +1,64 @@
+#!/usr/bin/env python
+#
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example updates a forecast adjustment's name."""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+ADJUSTMENT_ID = 'INSERT_ADJUSTMENT_ID_HERE'
+
+
+def main(client, adjustment_id):
+ # Initialize the adjustment service.
+ adjustment_service = client.GetService('AdjustmentService', version='v202208')
+
+ # Create a statement to select a single forecast adjustment by id.
+ statement = (
+ ad_manager.StatementBuilder(
+ version='v202208').Where('id = :id').WithBindVariable(
+ 'id', adjustment_id))
+
+ # Get the forecast adjustment.
+ response = adjustment_service.getForecastAdjustmentsByStatement(
+ statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ # Update each local forecast adjustment's name.
+ updated_adjustments = []
+ for adjustment in response['results']:
+ adjustment['name'] += ' (updated)'
+ updated_adjustments.append(adjustment)
+
+ # Update the forecast adjustment on the server.
+ adjustments = adjustment_service.updateForecastAdjustments(
+ updated_adjustments)
+
+ # Display the results.
+ if adjustments:
+ for adjustment in adjustments:
+ print('Forecast adjustment with id %d and name "%s" was updated' % (
+ adjustment['id'], adjustment['name']))
+ else:
+ print('No forecast adjustments were updated.')
+ else:
+ print('No forecast adjustments found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ADJUSTMENT_ID)
diff --git a/examples/ad_manager/v202208/audience_segment_service/__init__.py b/examples/ad_manager/v202208/audience_segment_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202208/audience_segment_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202208/audience_segment_service/create_audience_segments.py b/examples/ad_manager/v202208/audience_segment_service/create_audience_segments.py
new file mode 100755
index 00000000..02157f32
--- /dev/null
+++ b/examples/ad_manager/v202208/audience_segment_service/create_audience_segments.py
@@ -0,0 +1,96 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example creates a new rule based first party audience segment."""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the IDs of the custom criteria to be used in the segment rule.
+CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'
+CUSTOM_TARGETING_VALUE_ID = 'INSERT_CUSTOM_TARGETING_VALUE_ID_HERE'
+
+
+def main(client, custom_targeting_key_id, custom_targeting_value_id):
+ # Initialize appropriate services.
+ audience_segment_service = client.GetService(
+ 'AudienceSegmentService', version='v202208')
+ network_service = client.GetService('NetworkService', version='v202208')
+
+ # Get the root ad unit ID used to target the entire network.
+ root_ad_unit_id = (
+ network_service.getCurrentNetwork()['effectiveRootAdUnitId'])
+
+ # Create inventory targeting (pointed at root ad unit i.e. the whole network)
+ inventory_targeting = {
+ 'targetedAdUnits': [
+ {'adUnitId': root_ad_unit_id}
+ ]
+ }
+
+ # Create custom criteria.
+ custom_criteria = [
+ {
+ 'xsi_type': 'CustomCriteria',
+ 'keyId': custom_targeting_key_id,
+ 'valueIds': [custom_targeting_value_id],
+ 'operator': 'IS'
+ }
+ ]
+
+ # Create the custom criteria set.
+ top_custom_criteria_set = {
+ 'logicalOperator': 'AND',
+ 'children': custom_criteria
+ }
+
+ # Create the audience segment rule.
+ rule = {
+ 'inventoryRule': inventory_targeting,
+ 'customCriteriaRule': top_custom_criteria_set
+ }
+
+ # Create an audience segment.
+ audience_segment = [
+ {
+ 'xsi_type': 'RuleBasedFirstPartyAudienceSegment',
+ 'name': ('Sports enthusiasts audience segment %s' %
+ uuid.uuid4()),
+ 'description': 'Sports enthusiasts between the ages of 20 and 30',
+ 'pageViews': '6',
+ 'recencyDays': '6',
+ 'membershipExpirationDays': '88',
+ 'rule': rule
+ }
+ ]
+
+ audience_segments = (
+ audience_segment_service.createAudienceSegments(audience_segment))
+
+ for created_audience_segment in audience_segments:
+ print('An audience segment with ID "%s", name "%s", and type "%s" '
+ 'was created.' % (created_audience_segment['id'],
+ created_audience_segment['name'],
+ created_audience_segment['type']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CUSTOM_TARGETING_KEY_ID, CUSTOM_TARGETING_VALUE_ID)
diff --git a/examples/ad_manager/v202208/audience_segment_service/get_all_audience_segments.py b/examples/ad_manager/v202208/audience_segment_service/get_all_audience_segments.py
new file mode 100755
index 00000000..49469fc9
--- /dev/null
+++ b/examples/ad_manager/v202208/audience_segment_service/get_all_audience_segments.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all audience segments.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ audience_segment_service = client.GetService(
+ 'AudienceSegmentService', version='v202208')
+
+ # Create a statement to select audience segments.
+ statement = ad_manager.StatementBuilder(version='v202208')
+
+ # Retrieve a small amount of audience segments at a time, paging
+ # through until all audience segments have been retrieved.
+ while True:
+ response = audience_segment_service.getAudienceSegmentsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for audience_segment in response['results']:
+ # Print out some information for each audience segment.
+ print('Audience segment with ID "%d", name "%s", and size "%d" was '
+ 'found.\n' % (audience_segment['id'], audience_segment['name'],
+ audience_segment['size']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/audience_segment_service/get_first_party_audience_segments.py b/examples/ad_manager/v202208/audience_segment_service/get_first_party_audience_segments.py
new file mode 100755
index 00000000..0d0ef59c
--- /dev/null
+++ b/examples/ad_manager/v202208/audience_segment_service/get_first_party_audience_segments.py
@@ -0,0 +1,53 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all first party audience segments.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ audience_segment_service = client.GetService(
+ 'AudienceSegmentService', version='v202208')
+ # Create a statement to select audience segments.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('type = :type')
+ .WithBindVariable('type', 'FIRST_PARTY'))
+
+ # Retrieve a small amount of audience segments at a time, paging
+ # through until all audience segments have been retrieved.
+ while True:
+ response = audience_segment_service.getAudienceSegmentsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for audience_segment in response['results']:
+ # Print out some information for each audience segment.
+ print('Audience segment with ID "%d", name "%s", and size "%d" was '
+ 'found.\n' % (audience_segment['id'], audience_segment['name'],
+ audience_segment['size']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/audience_segment_service/populate_first_party_audience_segments.py b/examples/ad_manager/v202208/audience_segment_service/populate_first_party_audience_segments.py
new file mode 100755
index 00000000..b24eaf79
--- /dev/null
+++ b/examples/ad_manager/v202208/audience_segment_service/populate_first_party_audience_segments.py
@@ -0,0 +1,71 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example populates a specific first party audience segment.
+
+To determine which first party audience segments exist, run
+get_first_party_audience_segments.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+AUDIENCE_SEGMENT_ID = 'INSERT_AUDIENCE_SEGMENT_ID_HERE'
+
+
+def main(client, audience_segment_id):
+ # Initialize appropriate service.
+ audience_segment_service = client.GetService(
+ 'AudienceSegmentService', version='v202208')
+
+ # Create statement object to get the specified first party audience segment.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('Type = :type AND Id = :audience_segment_id')
+ .WithBindVariable('audience_segment_id',
+ int(audience_segment_id))
+ .WithBindVariable('type', 'FIRST_PARTY')
+ .Limit(1))
+
+ response = audience_segment_service.getAudienceSegmentsByStatement(
+ statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ segments = response['results']
+
+ for segment in segments:
+ print(
+ 'Audience segment with id "%s" and name "%s" will be populated.'
+ % (segment['id'], segment['name']))
+
+ action = {
+ 'xsi_type': 'PopulateAudienceSegments'
+ }
+
+ populated_audience_segments = (
+ audience_segment_service.performAudienceSegmentAction(
+ action, statement.ToStatement()))
+
+ print('%s audience segment populated' %
+ populated_audience_segments['numChanges'])
+ else:
+ print('No Results Found')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, AUDIENCE_SEGMENT_ID)
diff --git a/examples/ad_manager/v202208/audience_segment_service/update_audience_segments.py b/examples/ad_manager/v202208/audience_segment_service/update_audience_segments.py
new file mode 100755
index 00000000..c7b35584
--- /dev/null
+++ b/examples/ad_manager/v202208/audience_segment_service/update_audience_segments.py
@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example updates rule based first party audience segments.
+
+To determine which audience segments exist, run get_all_audience_segments.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+AUDIENCE_SEGMENT_ID = 'INSERT_AUDIENCE_SEGMENT_ID_HERE'
+
+
+def main(client, audience_segment_id):
+ # Initialize appropriate service.
+ audience_segment_service = client.GetService(
+ 'AudienceSegmentService', version='v202208')
+
+ # Create statement object to get the specified first party audience segment.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('Type = :type AND Id = :audience_segment_id')
+ .WithBindVariable('audience_segment_id',
+ int(audience_segment_id))
+ .WithBindVariable('type', 'FIRST_PARTY')
+ .Limit(1))
+
+ # Get audience segments by statement.
+ response = audience_segment_service.getAudienceSegmentsByStatement(
+ statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ updated_audience_segments = []
+ for audience_segment in response['results']:
+ print('Audience segment with id "%s" and name "%s" will be updated.'
+ % (audience_segment['id'], audience_segment['name']))
+
+ audience_segment['membershipExpirationDays'] = '180'
+ updated_audience_segments.append(audience_segment)
+
+ audience_segments = audience_segment_service.updateAudienceSegments(
+ updated_audience_segments)
+
+ for audience_segment in audience_segments:
+ print('Audience segment with id "%s" and name "%s" was updated' %
+ (audience_segment['id'], audience_segment['name']))
+ else:
+ print('No audience segment found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, AUDIENCE_SEGMENT_ID)
diff --git a/examples/ad_manager/v202208/cdn_configuration_service/__init__.py b/examples/ad_manager/v202208/cdn_configuration_service/__init__.py
new file mode 100755
index 00000000..473ddba1
--- /dev/null
+++ b/examples/ad_manager/v202208/cdn_configuration_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202208/cdn_configuration_service/create_cdn_configurations.py b/examples/ad_manager/v202208/cdn_configuration_service/create_cdn_configurations.py
new file mode 100755
index 00000000..8a84ccb8
--- /dev/null
+++ b/examples/ad_manager/v202208/cdn_configuration_service/create_cdn_configurations.py
@@ -0,0 +1,89 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new cdn configurations.
+
+To determine which configurations exist, run get_all_cdn_configurations.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ cdn_config_service = client.GetService('CdnConfigurationService',
+ version='v202208')
+
+ # Create cdn config objects.
+ # Only LIVE_STREAM_SOURCE_CONTENT is currently supported by the API.
+ configs = [{
+ # Basic example with no security policies.
+ 'name': 'ApiConfig1',
+ 'cdnConfigurationType': 'LIVE_STREAM_SOURCE_CONTENT',
+ 'sourceContentConfiguration': {
+ 'ingestSettings': {
+ 'urlPrefix': 'ingest1.com',
+ 'securityPolicy': {
+ 'securityPolicyType': 'NONE'
+ }
+ },
+ 'defaultDeliverySettings': {
+ 'urlPrefix': 'delivery1.com',
+ 'securityPolicy': {
+ 'securityPolicyType': 'NONE'
+ }
+ }
+ }
+ }, {
+ # Complex example with security policies.
+ 'name': 'ApiConfig2',
+ 'cdnConfigurationType': 'LIVE_STREAM_SOURCE_CONTENT',
+ 'sourceContentConfiguration': {
+ 'ingestSettings': {
+ 'urlPrefix': 'ingest1.com',
+ 'securityPolicy': {
+ 'securityPolicyType': 'AKAMAI',
+ 'disableServerSideUrlSigning': False,
+ 'tokenAuthenticationKey': 'abc123',
+ }
+ },
+ 'defaultDeliverySettings': {
+ 'urlPrefix': 'delivery1.com',
+ 'securityPolicy': {
+ 'securityPolicyType': 'AKAMAI',
+ 'disableServerSideUrlSigning': True,
+ 'originForwardingType': 'CONVENTIONAL',
+ 'originPathPrefix': '/path/to/my/origin'
+ }
+ }
+ }
+ }]
+
+ # Add configs.
+ configs = cdn_config_service.createCdnConfigurations(configs)
+
+ # Display results.
+ for config in configs:
+ print('Created CDN configuration with type "%s" and name "%s".'
+ % (config['cdnConfigurationType'], config['name']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/cdn_configuration_service/get_all_cdn_configurations.py b/examples/ad_manager/v202208/cdn_configuration_service/get_all_cdn_configurations.py
new file mode 100755
index 00000000..66277c26
--- /dev/null
+++ b/examples/ad_manager/v202208/cdn_configuration_service/get_all_cdn_configurations.py
@@ -0,0 +1,54 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all CDN configuration objects.
+
+Currently only configurations of type LIVE_STREAM_SOURCE_CONTENT will be
+returned.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ cdn_config_service = client.GetService('CdnConfigurationService',
+ version='v202208')
+
+ # Create a statement to select cdn configurations.
+ statement = ad_manager.StatementBuilder(version='v202208')
+
+ # Retrieve a small number of configs at a time, paging
+ # through until all have been retrieved.
+ while True:
+ response = (cdn_config_service
+ .getCdnConfigurationsByStatement(statement.ToStatement()))
+ if 'results' in response and len(response['results']):
+ for cdn in response['results']:
+ # Print out some information for each company.
+ print('Found CDN configuration with type "%s" and name "%s".'
+ % (cdn['cdnConfigurationType'], cdn['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/cms_metadata_service/activate_cms_metadata_values.py b/examples/ad_manager/v202208/cms_metadata_service/activate_cms_metadata_values.py
new file mode 100755
index 00000000..13323c68
--- /dev/null
+++ b/examples/ad_manager/v202208/cms_metadata_service/activate_cms_metadata_values.py
@@ -0,0 +1,70 @@
+#!/usr/bin/env python
+#
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example activates CMS Metadata Values for a particular CMS Metadata Key.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the id of the CMS Metadata Key on which to activate the CMS Metadata
+# Values.
+CMS_METADATA_KEY_ID = 'INSERT_CMS_METADATA_KEY_ID_HERE'
+
+
+def main(client, cms_metadata_key_id):
+ # Initialize appropriate service.
+ cms_metadata_service = client.GetService('CmsMetadataService',
+ version='v202208')
+
+ # Create query.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('cmsKeyId = :cmsKeyId AND status = :status')
+ .WithBindVariable('status', 'INACTIVE')
+ .WithBindVariable('cmsKeyId', int(cms_metadata_key_id)))
+
+ values_activated = 0
+
+ # Get CMS Metadata Values by statement.
+ while True:
+ response = cms_metadata_service.getCmsMetadataValuesByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for cms_metadata_value in response['results']:
+ print('CMS Metadata Value with id "%s" and name "%s" will be '
+ 'activated.' % (cms_metadata_value['cmsMetadataValueId'],
+ cms_metadata_value['valueName']))
+
+ # Perform action.
+ result = cms_metadata_service.performCmsMetadataValueAction(
+ {'xsi_type': 'ActivateCmsMetadataValues'}, statement.ToStatement())
+ if result and int(result['numChanges']) > 0:
+ values_activated += int(result['numChanges'])
+ statement.offset += statement.limit
+ else:
+ break
+
+ # Display results.
+ if values_activated > 0:
+ print('Number of CMS Metadata Values activated: %s' % values_activated)
+ else:
+ print('No CMS Metadata Values were activated.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CMS_METADATA_KEY_ID)
diff --git a/examples/ad_manager/v202208/cms_metadata_service/get_all_cms_metadata_keys.py b/examples/ad_manager/v202208/cms_metadata_service/get_all_cms_metadata_keys.py
new file mode 100755
index 00000000..4e0987d4
--- /dev/null
+++ b/examples/ad_manager/v202208/cms_metadata_service/get_all_cms_metadata_keys.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2019 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all CmsMetadataKeys."""
+
+# Import appropriate modules from the client library.
+from __future__ import print_function
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ cms_metadata_service = client.GetService(
+ 'CmsMetadataService', version='v202208')
+
+ # Create a statement to select CmsMetadataKeys.
+ statement = ad_manager.StatementBuilder(version='v202208')
+
+ # Retrieve a small amount of keys at a time, paging
+ # through until all keys have been retrieved.
+ while True:
+ response = cms_metadata_service.getCmsMetadataKeysByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for cms_metadata_key in response['results']:
+ # Print out some information for each key.
+ print('CMS metadata key with Id %d and name "%s" was found.\n' %
+ (cms_metadata_key['id'], cms_metadata_key['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/cms_metadata_service/get_all_cms_metadata_values.py b/examples/ad_manager/v202208/cms_metadata_service/get_all_cms_metadata_values.py
new file mode 100755
index 00000000..53ef18b5
--- /dev/null
+++ b/examples/ad_manager/v202208/cms_metadata_service/get_all_cms_metadata_values.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python
+#
+# Copyright 2019 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all CmsMetadataValues."""
+
+# Import appropriate modules from the client library.
+from __future__ import print_function
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ cms_metadata_service = client.GetService(
+ 'CmsMetadataService', version='v202208')
+
+ # Create a statement to select CmsMetadataValues.
+ statement = ad_manager.StatementBuilder(version='v202208')
+
+ # Retrieve a small amount of values at a time, paging
+ # through until all values have been retrieved.
+ while True:
+ response = cms_metadata_service.getCmsMetadataValuesByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for cms_metadata_value in response['results']:
+ # Print out some information for each value.
+ print(('CMS metadata value with Id %d and name "%s", associated with '
+ 'the CmsMetadataKey with id %d and name "%s", was found.\n') %
+ (cms_metadata_value['cmsMetadataValueId'],
+ cms_metadata_value['valueName'], cms_metadata_value['key']['id'],
+ cms_metadata_value['key']['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/cms_metadata_service/get_cms_metadata_values_for_key.py b/examples/ad_manager/v202208/cms_metadata_service/get_cms_metadata_values_for_key.py
new file mode 100755
index 00000000..e54540f3
--- /dev/null
+++ b/examples/ad_manager/v202208/cms_metadata_service/get_cms_metadata_values_for_key.py
@@ -0,0 +1,60 @@
+#!/usr/bin/env python
+#
+# Copyright 2019 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all CmsMetadataValues for a particular CmsMetadataKey."""
+
+# Import appropriate modules from the client library.
+from __future__ import print_function
+from googleads import ad_manager
+
+CMS_METADATA_KEY_NAME = 'INSERT_CMS_METADATA_KEY_NAME_HERE'
+
+
+def main(client, cms_metadata_key_name):
+ # Initialize appropriate service.
+ cms_metadata_service = client.GetService(
+ 'CmsMetadataService', version='v202208')
+
+ # Create a statement to select CmsMetadataValues for a particular key.
+ statement = (
+ ad_manager.StatementBuilder(version='v202208').Where(
+ 'cmsKey = :cmsMetadataKeyName').WithBindVariable(
+ 'cmsMetadataKeyName', cms_metadata_key_name))
+
+ # Retrieve a small amount of values at a time, paging
+ # through until all values have been retrieved.
+ while True:
+ response = cms_metadata_service.getCmsMetadataValuesByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for cms_metadata_value in response['results']:
+ # Print out some information for each value.
+ print(('CMS metadata value with Id %d and name "%s", associated with '
+ 'the CmsMetadataKey with id %d and name "%s", was found.\n') %
+ (cms_metadata_value['cmsMetadataValueId'],
+ cms_metadata_value['valueName'], cms_metadata_value['key']['id'],
+ cms_metadata_value['key']['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CMS_METADATA_KEY_NAME)
diff --git a/examples/ad_manager/v202208/company_service/__init__.py b/examples/ad_manager/v202208/company_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202208/company_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202208/company_service/create_companies.py b/examples/ad_manager/v202208/company_service/create_companies.py
new file mode 100755
index 00000000..ed37a061
--- /dev/null
+++ b/examples/ad_manager/v202208/company_service/create_companies.py
@@ -0,0 +1,62 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new companies.
+
+To determine which companies exist, run get_all_companies.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ company_service = client.GetService('CompanyService', version='v202208')
+
+ # Create company objects.
+ companies = [
+ {
+ 'name': 'Advertiser #%s' % uuid.uuid4(),
+ 'type': 'ADVERTISER'
+ },
+ {
+ 'name': 'Agency #%s' % uuid.uuid4(),
+ 'type': 'AGENCY'
+ }
+ ]
+
+ # Add companies.
+ companies = company_service.createCompanies(companies)
+
+ # Display results.
+ for company in companies:
+ print('Company with ID "%s", name "%s", and type "%s" was created.'
+ % (company['id'], company['name'], company['type']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/company_service/get_advertisers.py b/examples/ad_manager/v202208/company_service/get_advertisers.py
new file mode 100755
index 00000000..d062063b
--- /dev/null
+++ b/examples/ad_manager/v202208/company_service/get_advertisers.py
@@ -0,0 +1,50 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all companies that are advertisers.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ company_service = client.GetService('CompanyService', version='v202208')
+ # Create a statement to select companies.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('type = :type')
+ .WithBindVariable('type', 'ADVERTISER'))
+
+ # Retrieve a small amount of companies at a time, paging
+ # through until all companies have been retrieved.
+ while True:
+ response = company_service.getCompaniesByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for company in response['results']:
+ # Print out some information for each company.
+ print('Company with ID "%d", name "%s", and type "%s" was found.\n' %
+ (company['id'], company['name'], company['type']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/company_service/get_all_companies.py b/examples/ad_manager/v202208/company_service/get_all_companies.py
new file mode 100755
index 00000000..0c32bedc
--- /dev/null
+++ b/examples/ad_manager/v202208/company_service/get_all_companies.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all companies.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ company_service = client.GetService('CompanyService', version='v202208')
+
+ # Create a statement to select companies.
+ statement = ad_manager.StatementBuilder(version='v202208')
+
+ # Retrieve a small amount of companies at a time, paging
+ # through until all companies have been retrieved.
+ while True:
+ response = company_service.getCompaniesByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for company in response['results']:
+ # Print out some information for each company.
+ print('Company with ID "%d", name "%s", and type "%s" was found.\n' %
+ (company['id'], company['name'], company['type']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/company_service/update_companies.py b/examples/ad_manager/v202208/company_service/update_companies.py
new file mode 100755
index 00000000..e141582b
--- /dev/null
+++ b/examples/ad_manager/v202208/company_service/update_companies.py
@@ -0,0 +1,70 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates company comments.
+
+To determine which companies exist, run get_all_companies.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the company to update.
+COMPANY_ID = 'INSERT_COMPANY_ID_HERE'
+
+
+def main(client, company_id):
+ # Initialize appropriate service.
+ company_service = client.GetService('CompanyService', version='v202208')
+
+ # Create statement object to only select a single company by ID.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('id = :id')
+ .WithBindVariable('id', int(company_id))
+ .Limit(1))
+
+ # Get companies by statement.
+ response = company_service.getCompaniesByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ updated_companies = []
+ for company in response['results']:
+ company['comment'] += ' Updated.'
+ updated_companies.append(company)
+
+ # Update the companies on the server.
+ companies = company_service.updateCompanies(updated_companies)
+
+ # Display results.
+ for company in companies:
+ print(('Company with ID "%s", name "%s", and comment "%s"'
+ ' was updated.')
+ % (company['id'], company['name'], company['comment']))
+ else:
+ print('No companies found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, COMPANY_ID)
diff --git a/examples/ad_manager/v202208/contact_service/__init__.py b/examples/ad_manager/v202208/contact_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202208/contact_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202208/contact_service/create_contacts.py b/examples/ad_manager/v202208/contact_service/create_contacts.py
new file mode 100755
index 00000000..744400af
--- /dev/null
+++ b/examples/ad_manager/v202208/contact_service/create_contacts.py
@@ -0,0 +1,71 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new contacts.
+
+To determine which contacts exist, run get_all_contacts.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the advertiser company this contact is associated with.
+ADVERTISER_COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
+
+# Set the ID of the agency company this contact is associated with.
+AGENCY_COMPANY_ID = 'INSERT_AGENCY_COMPANY_ID_HERE'
+
+
+def main(client, advertiser_company_id, agency_company_id):
+ # Initialize appropriate service.
+ contact_service = client.GetService('ContactService', version='v202208')
+
+ # Create an advertiser contact.
+ advertiser_contact = {
+ 'name': 'Mr. Advertiser #%s' % uuid.uuid4(),
+ 'email': 'advertiser@advertising.com',
+ 'companyId': advertiser_company_id
+ }
+
+ # Create an agency contact.
+ agency_contact = {
+ 'name': 'Ms. Agency #%s' % uuid.uuid4(),
+ 'email': 'agency@agencies.com',
+ 'companyId': agency_company_id
+ }
+
+ # Create the contacts on the server.
+ contacts = contact_service.createContacts([advertiser_contact,
+ agency_contact])
+
+ # Display results.
+ for contact in contacts:
+ print('Contact with ID "%s" name "%s" was created.'
+ % (contact['id'], contact['name']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ADVERTISER_COMPANY_ID, AGENCY_COMPANY_ID)
diff --git a/examples/ad_manager/v202208/contact_service/get_all_contacts.py b/examples/ad_manager/v202208/contact_service/get_all_contacts.py
new file mode 100755
index 00000000..5bef053f
--- /dev/null
+++ b/examples/ad_manager/v202208/contact_service/get_all_contacts.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all contacts.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ contact_service = client.GetService('ContactService', version='v202208')
+
+ # Create a statement to select contacts.
+ statement = ad_manager.StatementBuilder(version='v202208')
+
+ # Retrieve a small amount of contacts at a time, paging
+ # through until all contacts have been retrieved.
+ while True:
+ response = contact_service.getContactsByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for contact in response['results']:
+ # Print out some information for each contact.
+ print('Contact with ID "%d" and name "%s" was found.\n' %
+ (contact['id'], contact['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/contact_service/get_uninvited_contacts.py b/examples/ad_manager/v202208/contact_service/get_uninvited_contacts.py
new file mode 100755
index 00000000..7cb80324
--- /dev/null
+++ b/examples/ad_manager/v202208/contact_service/get_uninvited_contacts.py
@@ -0,0 +1,50 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all contacts that aren't invited yet.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ contact_service = client.GetService('ContactService', version='v202208')
+ # Create a statement to select contacts.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('status = :status')
+ .WithBindVariable('status', 'UNINVITED'))
+
+ # Retrieve a small amount of contacts at a time, paging
+ # through until all contacts have been retrieved.
+ while True:
+ response = contact_service.getContactsByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for contact in response['results']:
+ # Print out some information for each contact.
+ print('Contact with ID "%d" and name "%s" was found.\n' %
+ (contact['id'], contact['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/contact_service/update_contacts.py b/examples/ad_manager/v202208/contact_service/update_contacts.py
new file mode 100755
index 00000000..8e45be57
--- /dev/null
+++ b/examples/ad_manager/v202208/contact_service/update_contacts.py
@@ -0,0 +1,71 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates contact addresses.
+
+To determine which contacts exist, run get_all_contacts.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the contact to update.
+CONTACT_ID = 'INSERT_CONTACT_ID_HERE'
+
+
+def main(client, contact_id):
+ # Initialize appropriate service.
+ contact_service = client.GetService('ContactService', version='v202208')
+
+ # Create statement object to select the single contact by ID.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('id = :id')
+ .WithBindVariable('id', int(contact_id))
+ .Limit(1))
+
+ # Get contacts by statement.
+ response = contact_service.getContactsByStatement(
+ statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ updated_contacts = []
+ for contact in response['results']:
+ contact['address'] = '123 New Street, New York, NY, 10011'
+ updated_contacts.append(contact)
+
+ # Update the contact on the server.
+ contacts = contact_service.updateContacts(updated_contacts)
+
+ # Display results.
+ for contact in contacts:
+ print(('Contact with ID "%s", name "%s", and address "%s" '
+ 'was updated.')
+ % (contact['id'], contact['name'], contact['address']))
+ else:
+ print('No contacts found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CONTACT_ID)
diff --git a/examples/ad_manager/v202208/content_service/__init__.py b/examples/ad_manager/v202208/content_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202208/content_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202208/content_service/get_all_content.py b/examples/ad_manager/v202208/content_service/get_all_content.py
new file mode 100755
index 00000000..43424a92
--- /dev/null
+++ b/examples/ad_manager/v202208/content_service/get_all_content.py
@@ -0,0 +1,54 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all content."""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ content_service = client.GetService('ContentService', version='v202208')
+
+ # Create a statement to select content.
+ statement = ad_manager.StatementBuilder(version='v202208')
+
+ # Retrieve a small amount of content at a time, paging
+ # through until all content have been retrieved.
+ while True:
+ response = content_service.getContentByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for content in response['results']:
+ # Print out some information for each content.
+ content_description = ('Content with ID "%d" and name "%s"' %
+ (content['id'], content['name'].encode('utf-8')))
+ if content['contentBundleIds']:
+ content_description += (' belonging to bundle IDs %s' %
+ content['contentBundleIds'])
+ content_description += ' was found.'
+ print(content_description)
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/content_service/get_recently_modified_content.py b/examples/ad_manager/v202208/content_service/get_recently_modified_content.py
new file mode 100755
index 00000000..5a8e8521
--- /dev/null
+++ b/examples/ad_manager/v202208/content_service/get_recently_modified_content.py
@@ -0,0 +1,66 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets recently modified content."""
+
+# Import appropriate modules from the client library.
+from datetime import datetime
+from datetime import timedelta
+
+from googleads import ad_manager
+import pytz
+
+
+def main(client):
+ # Initialize appropriate service.
+ content_service = client.GetService('ContentService', version='v202208')
+
+ last_modified = (datetime.now(tz=pytz.timezone('America/New_York'))
+ - timedelta(days=1))
+
+ # Create a statement to get recently modified content based on
+ # lastModifiedDateTime. Changes to content bundle associations will update
+ # the lastModifiedDateTime, but CMS metadata changes may not change the
+ # lastModifiedDateTime.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('lastModifiedDateTime >= :lastModifiedDateTime')
+ .WithBindVariable('lastModifiedDateTime', last_modified))
+
+ # Retrieve a small amount of content at a time, paging
+ # through until all content have been retrieved.
+ while True:
+ response = content_service.getContentByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for content in response['results']:
+ # Print out some information for each content.
+ content_description = ('Content with ID "%d" and name "%s"' %
+ (content['id'], content['name'].encode('utf-8')))
+ if content['contentBundleIds']:
+ content_description += (' belonging to bundle IDs %s' %
+ content['contentBundleIds'])
+ content_description += ' was found.'
+ print(content_description)
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/creative_service/__init__.py b/examples/ad_manager/v202208/creative_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202208/creative_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202208/creative_service/copy_image_creatives.py b/examples/ad_manager/v202208/creative_service/copy_image_creatives.py
new file mode 100755
index 00000000..afabd7ef
--- /dev/null
+++ b/examples/ad_manager/v202208/creative_service/copy_image_creatives.py
@@ -0,0 +1,60 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example creates a copy of an image creative.
+
+To determine which image creatives exist, run get_image_creatives.py
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the line item to pause.
+CREATIVE_ID = 'INSERT_CREATIVE_ID_HERE'
+
+
+def main(client):
+ # Initialize appropriate service.
+ creative_service = client.GetService('CreativeService', version='v202208')
+
+ # Create a statement to get the image creative.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('id = :id')
+ .OrderBy('id', ascending=True)
+ .WithBindVariable('id', CREATIVE_ID))
+
+ # Get the creative.
+ query_result = creative_service.getCreativesByStatement(
+ statement.ToStatement())
+
+ image_creative = query_result['results'][0]
+
+ # Build the new creative, set id to None to create a copy.
+ image_creative['id'] = None
+ image_creative['name'] = 'Copy of %s' % image_creative['name']
+
+ result = creative_service.createCreatives([image_creative])[0]
+ print('A creative with ID %d, name "%s", and type "%s" was created and '
+ 'can be previewed at: %s' % (result['id'],
+ result['name'],
+ ad_manager.AdManagerClassType(result),
+ result['previewUrl']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/creative_service/create_creative_from_template.py b/examples/ad_manager/v202208/creative_service/create_creative_from_template.py
new file mode 100755
index 00000000..65972efd
--- /dev/null
+++ b/examples/ad_manager/v202208/creative_service/create_creative_from_template.py
@@ -0,0 +1,111 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates a new template creative for a given advertiser.
+
+To determine which companies are advertisers, run get_advertisers.py.
+To determine which creative templates exist, run
+get_all_creative_templates.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import os
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set id of the advertiser (company) that the creative will be assigned to.
+ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
+
+
+def main(client, advertiser_id):
+ # Initialize appropriate service.
+ creative_service = client.GetService('CreativeService', version='v202208')
+
+ # Use the image banner with optional third party tracking template.
+ creative_template_id = '10000680'
+
+ # Create image asset.
+ file_name = 'image%s.jpg' % uuid.uuid4()
+ image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data',
+ 'medium_rectangle.jpg'), 'r').read()
+ size = {
+ 'width': '300',
+ 'height': '250'
+ }
+ asset = {
+ 'xsi_type': 'CreativeAsset',
+ 'fileName': file_name,
+ 'assetByteArray': image_data,
+ 'size': size
+ }
+
+ # Create creative from templates.
+ creative = {
+ 'xsi_type': 'TemplateCreative',
+ 'name': 'Template Creative #%s' % uuid.uuid4(),
+ 'advertiserId': advertiser_id,
+ 'size': size,
+ 'creativeTemplateId': creative_template_id,
+ 'creativeTemplateVariableValues': [
+ {
+ 'xsi_type': 'AssetCreativeTemplateVariableValue',
+ 'uniqueName': 'Imagefile',
+ 'asset': asset
+ },
+ {
+ 'xsi_type': 'LongCreativeTemplateVariableValue',
+ 'uniqueName': 'Imagewidth',
+ 'value': '300'
+ },
+ {
+ 'xsi_type': 'LongCreativeTemplateVariableValue',
+ 'uniqueName': 'Imageheight',
+ 'value': '250'
+ },
+ {
+ 'xsi_type': 'UrlCreativeTemplateVariableValue',
+ 'uniqueName': 'ClickthroughURL',
+ 'value': 'www.google.com'
+ },
+ {
+ 'xsi_type': 'StringCreativeTemplateVariableValue',
+ 'uniqueName': 'Targetwindow',
+ 'value': '_blank'
+ }
+ ]
+ }
+
+ # Call service to create the creative.
+ creative = creative_service.createCreatives([creative])[0]
+
+ # Display results.
+ print('Template creative with id "%s", name "%s", and type "%s" was '
+ 'created and can be previewed at %s.'
+ % (creative['id'], creative['name'],
+ ad_manager.AdManagerClassType(creative), creative['previewUrl']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ADVERTISER_ID)
diff --git a/examples/ad_manager/v202208/creative_service/create_creatives.py b/examples/ad_manager/v202208/creative_service/create_creatives.py
new file mode 100755
index 00000000..d5ed4be4
--- /dev/null
+++ b/examples/ad_manager/v202208/creative_service/create_creatives.py
@@ -0,0 +1,93 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new image creatives for a given advertiser.
+
+To determine which companies are advertisers, run get_advertisers.py.
+To determine which creatives already exist, run get_all_creatives.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import os
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set id of the advertiser (company) that all creatives will be assigned to.
+ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
+
+
+def main(client, advertiser_id):
+ # Initialize appropriate service.
+ creative_service = client.GetService('CreativeService', version='v202208')
+
+ # Create creative objects.
+ creatives = []
+ with open(
+ os.path.join(
+ os.path.split(__file__)[0], '..', '..', 'data',
+ 'medium_rectangle.jpg'), 'rb') as image:
+ image_data = image.read()
+
+ for _ in range(5):
+ # Create creative size.
+ size = {
+ 'width': '300',
+ 'height': '250'
+ }
+
+ # Create image asset.
+ creative_asset = {
+ 'xsi_type': 'CreativeAsset',
+ 'fileName': 'image.jpg',
+ 'assetByteArray': image_data,
+ 'size': size
+ }
+
+ # Create an image creative.
+ creative = {
+ 'xsi_type': 'ImageCreative',
+ 'name': 'Image Creative #%s' % uuid.uuid4(),
+ 'advertiserId': advertiser_id,
+ 'destinationUrl': 'http://google.com',
+ 'size': size,
+ 'primaryImageAsset': creative_asset
+ }
+
+ creatives.append(creative)
+
+ # Add creatives.
+ creatives = creative_service.createCreatives(creatives)
+
+ # Display results.
+ for creative in creatives:
+ print('Image creative with id "%s", name "%s", and type "%s" was '
+ 'created and can be previewed at %s.' %
+ (creative['id'], creative['name'],
+ ad_manager.AdManagerClassType(creative), creative['previewUrl']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ADVERTISER_ID)
diff --git a/examples/ad_manager/v202208/creative_service/create_custom_creative.py b/examples/ad_manager/v202208/creative_service/create_custom_creative.py
new file mode 100755
index 00000000..a793a207
--- /dev/null
+++ b/examples/ad_manager/v202208/creative_service/create_custom_creative.py
@@ -0,0 +1,88 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example creates a custom creative for a given advertiser.
+
+This feature is only available to Ad Manager 360 solution networks. To determine
+which companies are advertisers, run get_advertisers.py. To determine
+which creative templates exist, run get_all_creative_templates.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import os
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set id of the advertiser (company) that the creative will be assigned to.
+ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
+
+
+def main(client, advertiser_id):
+ # Initialize appropriate service.
+ creative_service = client.GetService('CreativeService', version='v202208')
+
+ # Get the image data for the creative.
+ image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data',
+ 'medium_rectangle.jpg'), 'r').read()
+
+ # Create the HTML snippet used in the custom creative.
+ html_snippet = (' Click above for '
+ 'great deals!') % ('%%CLICK_URL_UNESC%%', '%%DEST_URL%%',
+ '%%FILE:IMAGE_ASSET%%')
+
+ # Create custom creative.
+ creative = {
+ 'xsi_type': 'CustomCreative',
+ 'name': 'Custom Creative #%s' % uuid.uuid4(),
+ 'advertiserId': advertiser_id,
+ 'size': {'width': '300', 'height': '250'},
+ 'destinationUrl': 'http://google.com',
+ 'customCreativeAssets': [
+ {
+ 'xsi_type': 'CustomCreativeAsset',
+ 'macroName': 'IMAGE_ASSET',
+ 'asset': {
+ 'assetByteArray': image_data,
+ 'fileName': 'image%s.jpg' % uuid.uuid4()
+ }
+ }
+ ],
+ 'htmlSnippet': html_snippet
+ }
+
+ # Call service to create the creative.
+ creatives = creative_service.createCreatives([creative])
+
+ # Display results.
+ if creatives:
+ creative = creatives[0]
+ print('Template creative with id "%s", name "%s", and type "%s" was '
+ 'created and can be previewed at %s.'
+ % (creative['id'], creative['name'],
+ ad_manager.AdManagerClassType(creative), creative['previewUrl']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ADVERTISER_ID)
diff --git a/examples/ad_manager/v202208/creative_service/create_native_creative.py b/examples/ad_manager/v202208/creative_service/create_native_creative.py
new file mode 100755
index 00000000..08fe41cd
--- /dev/null
+++ b/examples/ad_manager/v202208/creative_service/create_native_creative.py
@@ -0,0 +1,132 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates a new native creative for a given advertiser.
+
+To determine which companies are advertisers, run get_advertisers.py.
+
+The code in this example will use app data from the Google sample app
+'Pie Noon':
+
+https://play.google.com/store/apps/details?id=com.google.fpl.pie_noon&hl=en
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+"""
+
+import uuid
+from urllib.request import urlopen
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set id of the advertiser (company) that the creative will be assigned to.
+ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE'
+ICON_URL = ('https://lh4.ggpht.com/GIGNKdGHMEHFDw6TM2bgAUDKPQQRIReKZPqEpMeEhZO'
+ 'PYnTdOQGaSpGSEZflIFs0iw=h300')
+APP_ICON_SMALL = ('https://lh6.ggpht.com/Jzvjne5CLs6fJ1MHF-XeuUfpABzl0YNMlp4Rp'
+ 'HnvPRCIj4--eTDwtyouwUDzVVekXw=w300')
+
+
+def main(client, advertiser_id):
+ # Initialize appropriate service.
+ creative_service = client.GetService('CreativeService', version='v202208')
+
+ # Use the system defined native app install creative template.
+ creative_template_id = '10004400'
+
+ image_data = urlopen(ICON_URL).read()
+
+ app_icon_data = urlopen(APP_ICON_SMALL).read()
+
+ # Create creative from templates.
+ creative = {
+ 'xsi_type': 'TemplateCreative',
+ 'name': 'Native Creative #%s' % uuid.uuid4(),
+ 'advertiserId': advertiser_id,
+ 'size': {'width': '1', 'height': '1', 'isAspectRatio': False},
+ 'creativeTemplateId': creative_template_id,
+ 'destinationUrl': ('https://play.google.com/store/apps/details?id='
+ 'com.google.fpl.pie_noon'),
+ 'creativeTemplateVariableValues': [
+ {
+ 'xsi_type': 'AssetCreativeTemplateVariableValue',
+ 'uniqueName': 'Image',
+ 'asset': {
+ 'assetByteArray': image_data,
+ 'fileName': 'file%s.png' % uuid.uuid4()
+ }
+ },
+ {
+ 'xsi_type': 'AssetCreativeTemplateVariableValue',
+ 'uniqueName': 'Appicon',
+ 'asset': {
+ 'assetByteArray': app_icon_data,
+ 'fileName': 'appicon%s.png' % uuid.uuid4()
+ }
+ },
+ {
+ 'xsi_type': 'StringCreativeTemplateVariableValue',
+ 'uniqueName': 'Price',
+ 'value': 'Free'
+ },
+ {
+ 'xsi_type': 'StringCreativeTemplateVariableValue',
+ 'uniqueName': 'Calltoaction',
+ 'value': 'Install'
+ },
+ {
+ 'xsi_type': 'StringCreativeTemplateVariableValue',
+ 'uniqueName': 'Starrating',
+ 'value': '4'
+ },
+ {
+ 'xsi_type': 'StringCreativeTemplateVariableValue',
+ 'uniqueName': 'Store',
+ 'value': 'Google Play'
+ },
+ {
+ 'xsi_type': 'UrlCreativeTemplateVariableValue',
+ 'uniqueName': 'DeeplinkclickactionURL',
+ 'value': 'market://details?id=com.google.fpl.pie_noon'
+ },
+ {
+ 'xsi_type': 'StringCreativeTemplateVariableValue',
+ 'uniqueName': 'Body',
+ 'value': 'Try multi-screen mode!'
+ },
+ {
+ 'xsi_type': 'StringCreativeTemplateVariableValue',
+ 'uniqueName': 'Headline',
+ 'value': 'Pie Noon'
+ }
+ ]
+ }
+
+ # Call service to create the creative.
+ creative = creative_service.createCreatives([creative])[0]
+
+ # Display results.
+ print('Native creative with id "%s" and name "%s" was '
+ 'created and can be previewed at %s.'
+ % (creative['id'], creative['name'], creative['previewUrl']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ADVERTISER_ID)
diff --git a/examples/ad_manager/v202208/creative_service/create_video_creatives.py b/examples/ad_manager/v202208/creative_service/create_video_creatives.py
new file mode 100755
index 00000000..c3af5588
--- /dev/null
+++ b/examples/ad_manager/v202208/creative_service/create_video_creatives.py
@@ -0,0 +1,66 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates a new video creative for a given advertiser.
+
+To determine which companies are advertisers, run get_advertisers.py.
+To determine which creatives already exist, run get_all_creatives.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+"""
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set id of the advertiser (company) that the creative will be assigned to.
+ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE'
+
+
+def main(client, advertiser_id):
+ # Initialize appropriate service.
+ creative_service = client.GetService('CreativeService', version='v202208')
+
+ # Create a video creative.
+ creative = {
+ 'xsi_type': 'VideoCreative',
+ 'name': 'Video Creative #%s' % uuid.uuid4(),
+ 'advertiserId': advertiser_id,
+ 'size': {'width': '640', 'height': '360', 'isAspectRatio': False},
+ 'destinationUrl': 'https://google.com',
+ 'duration': '115000',
+ 'videoSourceUrl': (
+ 'https://storage.googleapis.com/interactive-media-ads/media/'
+ 'android.mp4')
+ }
+
+ # Call service to create the creative.
+ creative = creative_service.createCreatives([creative])[0]
+
+ # Display results.
+ print('Video creative with id "%s" and name "%s" was created and can be '
+ 'previewed at:\n%s.'
+ % (creative['id'], creative['name'], creative['vastPreviewUrl']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ADVERTISER_ID)
diff --git a/examples/ad_manager/v202208/creative_service/get_all_creatives.py b/examples/ad_manager/v202208/creative_service/get_all_creatives.py
new file mode 100755
index 00000000..6598c26a
--- /dev/null
+++ b/examples/ad_manager/v202208/creative_service/get_all_creatives.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all creatives.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ creative_service = client.GetService('CreativeService', version='v202208')
+
+ # Create a statement to select creatives.
+ statement = ad_manager.StatementBuilder(version='v202208')
+
+ # Retrieve a small amount of creatives at a time, paging
+ # through until all creatives have been retrieved.
+ while True:
+ response = creative_service.getCreativesByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for creative in response['results']:
+ # Print out some information for each creative.
+ print('Creative with ID "%d" and name "%s" was found.\n' %
+ (creative['id'], creative['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/creative_service/get_image_creatives.py b/examples/ad_manager/v202208/creative_service/get_image_creatives.py
new file mode 100755
index 00000000..4f035319
--- /dev/null
+++ b/examples/ad_manager/v202208/creative_service/get_image_creatives.py
@@ -0,0 +1,50 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all image creatives.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ creative_service = client.GetService('CreativeService', version='v202208')
+ # Create a statement to select creatives.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('creativeType = :creativeType')
+ .WithBindVariable('creativeType', 'ImageCreative'))
+
+ # Retrieve a small amount of creatives at a time, paging
+ # through until all creatives have been retrieved.
+ while True:
+ response = creative_service.getCreativesByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for creative in response['results']:
+ # Print out some information for each creative.
+ print('Creative with ID "%d" and name "%s" was found.\n' %
+ (creative['id'], creative['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/creative_service/update_creatives.py b/examples/ad_manager/v202208/creative_service/update_creatives.py
new file mode 100755
index 00000000..e17c9840
--- /dev/null
+++ b/examples/ad_manager/v202208/creative_service/update_creatives.py
@@ -0,0 +1,71 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates the destination URL of a single image creative.
+
+To determine which image creatives exist, run get_all_creatives.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+IMAGE_CREATIVE_ID = 'INSERT_IMAGE_CREATIVE_ID_HERE'
+
+
+def main(client, image_creative_id):
+ # Initialize appropriate service.
+ creative_service = client.GetService('CreativeService', version='v202208')
+
+ # Create statement object to get the creative by ID.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('creativeType = :type AND id = :id')
+ .WithBindVariable('type', 'ImageCreative')
+ .WithBindVariable('id', int(image_creative_id))
+ .Limit(1))
+
+ # Get creatives by statement.
+ response = creative_service.getCreativesByStatement(
+ statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ # Update each local creative object by changing its destination URL.
+ updated_creatives = []
+ for creative in response['results']:
+ creative['destinationUrl'] = 'http://news.google.com'
+ updated_creatives.append(creative)
+
+ # Update creatives remotely.
+ creatives = creative_service.updateCreatives(updated_creatives)
+
+ # Display results.
+ for creative in creatives:
+ print('Image creative with id "%s" and destination URL "%s" was '
+ 'updated.' % (creative['id'], creative['destinationUrl']))
+ else:
+ print('No creatives found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, IMAGE_CREATIVE_ID)
diff --git a/examples/ad_manager/v202208/creative_set_service/__init__.py b/examples/ad_manager/v202208/creative_set_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202208/creative_set_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202208/creative_set_service/associate_creative_set_to_line_item.py b/examples/ad_manager/v202208/creative_set_service/associate_creative_set_to_line_item.py
new file mode 100755
index 00000000..3551bb42
--- /dev/null
+++ b/examples/ad_manager/v202208/creative_set_service/associate_creative_set_to_line_item.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Creates a line item creative association for a creative set.
+
+To create creative sets, run create_creative_set.py. To create creatives, run
+create_creatives.py. To determine which LICAs exist, run get_all_licas.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+CREATIVE_SET_ID = 'INSERT_CREATIVE_SET_ID_HERE'
+LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
+
+
+def main(client, creative_set_id, line_item_id):
+ # Initialize appropriate service.
+ lica_service = client.GetService(
+ 'LineItemCreativeAssociationService', version='v202208')
+
+ # Create LICA for a creative set.
+ lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id}
+
+ # Add LICA.
+ lica = lica_service.createLineItemCreativeAssociations([lica])
+
+ # Display results.
+ print(('LICA with line item ID "%s" and creative set ID "%s" was '
+ 'created.') % (lica['lineItemId'], lica['creativeSetId']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CREATIVE_SET_ID, LINE_ITEM_ID)
diff --git a/examples/ad_manager/v202208/creative_set_service/create_creative_set.py b/examples/ad_manager/v202208/creative_set_service/create_creative_set.py
new file mode 100755
index 00000000..04598453
--- /dev/null
+++ b/examples/ad_manager/v202208/creative_set_service/create_creative_set.py
@@ -0,0 +1,62 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new creative sets.
+
+To determine which creative sets exist, run get_all_creative_sets.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+MASTER_CREATIVE_ID = 'INSERT_MASTER_CREATIVE_ID_HERE'
+COMPANION_CREATIVE_ID = 'INSERT_COMPANION_CREATIVE_ID_HERE'
+
+
+def main(client, master_creative_id, companion_creative_id):
+ # Initialize appropriate service.
+ creative_set_service = client.GetService('CreativeSetService',
+ version='v202208')
+
+ # Create creative set objects.
+ creative_set = {'name': 'Creative set #%s' % uuid.uuid4(),
+ 'masterCreativeId': master_creative_id,
+ 'companionCreativeIds': [companion_creative_id]}
+
+ # Add creative sets.
+ creative_set = creative_set_service.createCreativeSet(creative_set)
+
+ # Display results.
+ if creative_set:
+ print(('Creative set with ID "%s", master creative ID "%s", and '
+ 'companion creative IDs "%s" was created.') %
+ (creative_set['id'], creative_set['masterCreativeId'], ','.join(
+ str(v) for v in creative_set['companionCreativeIds'])))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, MASTER_CREATIVE_ID, COMPANION_CREATIVE_ID)
diff --git a/examples/ad_manager/v202208/creative_set_service/get_all_creative_sets.py b/examples/ad_manager/v202208/creative_set_service/get_all_creative_sets.py
new file mode 100755
index 00000000..9c051afb
--- /dev/null
+++ b/examples/ad_manager/v202208/creative_set_service/get_all_creative_sets.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all creative sets.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ creative_set_service = client.GetService(
+ 'CreativeSetService', version='v202208')
+
+ # Create a statement to select creative sets.
+ statement = ad_manager.StatementBuilder(version='v202208')
+
+ # Retrieve a small amount of creative sets at a time, paging
+ # through until all creative sets have been retrieved.
+ while True:
+ response = creative_set_service.getCreativeSetsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for creative_set in response['results']:
+ # Print out some information for each creative set.
+ print('Creative set with ID "%d" and name "%s" was found.\n' %
+ (creative_set['id'], creative_set['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/creative_set_service/get_creative_sets_for_master_creative.py b/examples/ad_manager/v202208/creative_set_service/get_creative_sets_for_master_creative.py
new file mode 100755
index 00000000..ae1617b7
--- /dev/null
+++ b/examples/ad_manager/v202208/creative_set_service/get_creative_sets_for_master_creative.py
@@ -0,0 +1,54 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all creative sets for a master creative.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+MASTER_CREATIVE_ID = 'INSERT_MASTER_CREATIVE_ID_HERE'
+
+
+def main(client, master_creative_id):
+ # Initialize appropriate service.
+ creative_set_service = client.GetService(
+ 'CreativeSetService', version='v202208')
+ # Create a statement to select creative sets.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('masterCreativeId = :masterCreativeId')
+ .WithBindVariable('masterCreativeId', master_creative_id))
+
+ # Retrieve a small amount of creative sets at a time, paging
+ # through until all creative sets have been retrieved.
+ while True:
+ response = creative_set_service.getCreativeSetsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for creative_set in response['results']:
+ # Print out some information for each creative set.
+ print('Creative set with ID "%d" and name "%s" was found.\n' %
+ (creative_set['id'], creative_set['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, MASTER_CREATIVE_ID)
diff --git a/examples/ad_manager/v202208/creative_set_service/update_creative_set.py b/examples/ad_manager/v202208/creative_set_service/update_creative_set.py
new file mode 100755
index 00000000..67059879
--- /dev/null
+++ b/examples/ad_manager/v202208/creative_set_service/update_creative_set.py
@@ -0,0 +1,73 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates a creative set by adding a companion creative.
+
+To determine which creative sets exist, run get_all_creative_sets.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the creative set to update.
+CREATIVE_SET_ID = 'INSERT_CREATIVE_SET_ID_HERE'
+COMPANION_CREATIVE_ID = 'INSERT_COMPANION_CREATIVE_ID_HERE'
+
+
+def main(client, creative_set_id, companion_creative_id):
+ # Initialize appropriate service.
+ creative_set_service = client.GetService('CreativeSetService',
+ version='v202208')
+
+ # Create statement to select a single creative set by ID.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('id = :creativeSetId')
+ .WithBindVariable('creativeSetId', int(creative_set_id)))
+
+ # Get creative set.
+ response = creative_set_service.getCreativeSetsByStatement(
+ statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ updated_created_sets = []
+ for creative_set in response['results']:
+ creative_set['companionCreativeIds'].append(companion_creative_id)
+ updated_created_sets.append(creative_set)
+
+ # Update the creative sets on the server.
+ creative_sets = creative_set_service.updateCreativeSet(updated_created_sets)
+
+ # Display results.
+ for creative_set in creative_sets:
+ print(('Creative set with ID "%s", master creative ID "%s", and '
+ 'companion creative IDs {%s} was updated.')
+ % (creative_set['id'], creative_set['masterCreativeId'],
+ ','.join(creative_set['companionCreativeIds'])))
+ else:
+ print('No creative sets found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CREATIVE_SET_ID, COMPANION_CREATIVE_ID)
diff --git a/examples/ad_manager/v202208/creative_template_service/__init__.py b/examples/ad_manager/v202208/creative_template_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202208/creative_template_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202208/creative_template_service/get_all_creative_templates.py b/examples/ad_manager/v202208/creative_template_service/get_all_creative_templates.py
new file mode 100755
index 00000000..59f506e7
--- /dev/null
+++ b/examples/ad_manager/v202208/creative_template_service/get_all_creative_templates.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all creative templates.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ creative_template_service = client.GetService(
+ 'CreativeTemplateService', version='v202208')
+
+ # Create a statement to select creative templates.
+ statement = ad_manager.StatementBuilder(version='v202208')
+
+ # Retrieve a small amount of creative templates at a time, paging
+ # through until all creative templates have been retrieved.
+ while True:
+ response = creative_template_service.getCreativeTemplatesByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for creative_template in response['results']:
+ # Print out some information for each creative template.
+ print('Creative template with ID "%d" and name "%s" was found.\n' %
+ (creative_template['id'], creative_template['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/creative_template_service/get_system_defined_creative_templates.py b/examples/ad_manager/v202208/creative_template_service/get_system_defined_creative_templates.py
new file mode 100755
index 00000000..e6becfcb
--- /dev/null
+++ b/examples/ad_manager/v202208/creative_template_service/get_system_defined_creative_templates.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all system defined creative templates.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ creative_template_service = client.GetService(
+ 'CreativeTemplateService', version='v202208')
+ # Create a statement to select creative templates.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('type = :type')
+ .WithBindVariable('type', 'SYSTEM_DEFINED'))
+
+ # Retrieve a small amount of creative templates at a time, paging
+ # through until all creative templates have been retrieved.
+ while True:
+ response = creative_template_service.getCreativeTemplatesByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for creative_template in response['results']:
+ # Print out some information for each creative template.
+ print('Creative template with ID "%d" and name "%s" was found.\n' %
+ (creative_template['id'], creative_template['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/creative_wrapper_service/create_creative_wrappers.py b/examples/ad_manager/v202208/creative_wrapper_service/create_creative_wrappers.py
new file mode 100755
index 00000000..00dd5610
--- /dev/null
+++ b/examples/ad_manager/v202208/creative_wrapper_service/create_creative_wrappers.py
@@ -0,0 +1,63 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates a new creative wrapper.
+
+Creative wrappers must be associated with a LabelType.CREATIVE_WRAPPER label and
+applied to ad units by AdUnit.appliedLabels. To determine which creative
+wrappers exist, run get_all_creative_wrappers.py
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+LABEL_ID = 'INSERT_CREATIVE_WRAPPER_LABEL_ID_HERE'
+
+
+def main(client, label_id):
+ # Initialize appropriate service.
+ creative_wrapper_service = client.GetService('CreativeWrapperService',
+ version='v202208')
+
+ # Create creative wrapper objects.
+ creative_wrapper = {
+ # A label can only be associated with one creative wrapper.
+ 'labelId': label_id,
+ 'ordering': 'INNER',
+ 'htmlHeader': 'My creative wrapper header',
+ 'htmlFooter': 'My creative wrapper footer'
+ }
+
+ # Add creative wrapper.
+ creative_wrappers = creative_wrapper_service.createCreativeWrappers(
+ [creative_wrapper])
+
+ # Display results.
+ for creative_wrapper in creative_wrappers:
+ print('Creative wrapper with ID "%s" applying to label "%s" was '
+ 'created.' % (creative_wrapper['id'], creative_wrapper['labelId']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, LABEL_ID)
diff --git a/examples/ad_manager/v202208/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/ad_manager/v202208/creative_wrapper_service/deactivate_creative_wrapper.py
new file mode 100755
index 00000000..1d4af2e2
--- /dev/null
+++ b/examples/ad_manager/v202208/creative_wrapper_service/deactivate_creative_wrapper.py
@@ -0,0 +1,78 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example deactivates a creative wrapper belonging to a label.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+LABEL_ID = 'INSERT_LABEL_ID_HERE'
+
+
+def main(client, label_id):
+ # Initialize appropriate service.
+ creative_wrapper_service = client.GetService('CreativeWrapperService',
+ version='v202208')
+
+ # Create a query to select the active creative wrappers for the given label.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('status = :status AND labelId = :labelId')
+ .WithBindVariable('status', 'ACTIVE')
+ .WithBindVariable('labelId', int(label_id)))
+
+ creative_wrappers_deactivated = 0
+
+ # Get creative wrappers by statement.
+ while True:
+ response = creative_wrapper_service.getCreativeWrappersByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ # Display results.
+ for creative_wrapper in response['results']:
+ print('Creative wrapper with ID "%s" applying to label "%s" with '
+ 'status "%s" will be deactivated.' %
+ (creative_wrapper['id'],
+ creative_wrapper['labelId'],
+ creative_wrapper['status']))
+ # Perform action.
+ result = creative_wrapper_service.performCreativeWrapperAction(
+ {'xsi_type': 'DeactivateCreativeWrappers'}, statement.ToStatement())
+ if result and int(result['numChanges']) > 0:
+ creative_wrappers_deactivated += int(result['numChanges'])
+ statement.offset += statement.limit
+ else:
+ break
+
+ # Display results.
+ if creative_wrappers_deactivated > 0:
+ print('Number of creative wrappers deactivated: %s' %
+ creative_wrappers_deactivated)
+ else:
+ print('No creative wrappers were deactivated.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, LABEL_ID)
diff --git a/examples/ad_manager/v202208/creative_wrapper_service/get_active_creative_wrappers.py b/examples/ad_manager/v202208/creative_wrapper_service/get_active_creative_wrappers.py
new file mode 100755
index 00000000..ba32968c
--- /dev/null
+++ b/examples/ad_manager/v202208/creative_wrapper_service/get_active_creative_wrappers.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all active creative wrappers.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ creative_wrapper_service = client.GetService(
+ 'CreativeWrapperService', version='v202208')
+ # Create a statement to select creative wrappers.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('status = :status')
+ .WithBindVariable('status', 'ACTIVE'))
+
+ # Retrieve a small amount of creative wrappers at a time, paging
+ # through until all creative wrappers have been retrieved.
+ while True:
+ response = creative_wrapper_service.getCreativeWrappersByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for creative_wrapper in response['results']:
+ # Print out some information for each creative wrapper.
+ print('Creative wrapper with ID "%d" and label ID "%d" was found.\n' %
+ (creative_wrapper['id'], creative_wrapper['labelId']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/creative_wrapper_service/get_all_creative_wrappers.py b/examples/ad_manager/v202208/creative_wrapper_service/get_all_creative_wrappers.py
new file mode 100755
index 00000000..df2b47c0
--- /dev/null
+++ b/examples/ad_manager/v202208/creative_wrapper_service/get_all_creative_wrappers.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all creative wrappers.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ creative_wrapper_service = client.GetService(
+ 'CreativeWrapperService', version='v202208')
+
+ # Create a statement to select creative wrappers.
+ statement = ad_manager.StatementBuilder(version='v202208')
+
+ # Retrieve a small amount of creative wrappers at a time, paging
+ # through until all creative wrappers have been retrieved.
+ while True:
+ response = creative_wrapper_service.getCreativeWrappersByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for creative_wrapper in response['results']:
+ # Print out some information for each creative wrapper.
+ print('Creative wrapper with ID "%d" and label id "%d" was found.\n' %
+ (creative_wrapper['id'], creative_wrapper['labelId']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/creative_wrapper_service/update_creative_wrappers.py b/examples/ad_manager/v202208/creative_wrapper_service/update_creative_wrappers.py
new file mode 100755
index 00000000..7cd854ab
--- /dev/null
+++ b/examples/ad_manager/v202208/creative_wrapper_service/update_creative_wrappers.py
@@ -0,0 +1,73 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates a creative wrapper to the 'OUTER' wrapping order.
+
+To determine which creative wrappers exist, run get_all_creative_wrappers.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the creative wrapper to update.
+CREATIVE_WRAPPER_ID = 'INSERT_CREATIVE_WRAPPER_ID_HERE'
+
+
+def main(client, creative_wrapper_id):
+ # Initialize appropriate service.
+ creative_wrapper_service = client.GetService('CreativeWrapperService',
+ version='v202208')
+
+ # Create statement to get a creative wrapper by ID.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('id = :creativeWrapperId')
+ .WithBindVariable('creativeWrapperId',
+ int(creative_wrapper_id)))
+
+ # Get creative wrappers.
+ response = creative_wrapper_service.getCreativeWrappersByStatement(
+ statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ updated_creative_wrappers = []
+ for creative_wrapper in response['results']:
+ creative_wrapper['ordering'] = 'OUTER'
+ updated_creative_wrappers.append(creative_wrapper)
+
+ # Update the creative wrappers on the server.
+ creative_wrappers = creative_wrapper_service.updateCreativeWrappers(
+ updated_creative_wrappers)
+
+ # Display results.
+ for creative_wrapper in creative_wrappers:
+ print(('Creative wrapper with ID "%s" and wrapping order "%s" '
+ 'was updated.') % (creative_wrapper['id'],
+ creative_wrapper['ordering']))
+ else:
+ print('No creative wrappers found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CREATIVE_WRAPPER_ID)
diff --git a/examples/ad_manager/v202208/custom_field_service/__init__.py b/examples/ad_manager/v202208/custom_field_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202208/custom_field_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202208/custom_field_service/create_custom_field_options.py b/examples/ad_manager/v202208/custom_field_service/create_custom_field_options.py
new file mode 100755
index 00000000..9533b048
--- /dev/null
+++ b/examples/ad_manager/v202208/custom_field_service/create_custom_field_options.py
@@ -0,0 +1,67 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example creates custom field options for a drop-down custom field.
+
+Once created, custom field options can be found under the options fields of the
+drop-down custom field and they cannot be deleted. To determine which custom
+fields exist, run get_all_custom_fields.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the drop-down custom field to create options for.
+CUSTOM_FIELD_ID = 'INSERT_DROP_DOWN_CUSTOM_FIELD_ID_HERE'
+
+
+def main(client, custom_field_id):
+ # Initialize appropriate service.
+ custom_field_service = client.GetService(
+ 'CustomFieldService', version='v202208')
+
+ # Create custom field options.
+ custom_field_options = [
+ {
+ 'displayName': 'Approved',
+ 'customFieldId': custom_field_id
+ },
+ {
+ 'displayName': 'Unapproved',
+ 'customFieldId': custom_field_id
+ }
+ ]
+
+ # Add custom field options.
+ custom_field_options = custom_field_service.createCustomFieldOptions(
+ custom_field_options)
+
+ # Display results.
+ for custom_field_option in custom_field_options:
+ print('Custom field option with ID "%s" and name "%s" was created.'
+ % (custom_field_option['id'], custom_field_option['displayName']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CUSTOM_FIELD_ID)
diff --git a/examples/ad_manager/v202208/custom_field_service/create_custom_fields.py b/examples/ad_manager/v202208/custom_field_service/create_custom_fields.py
new file mode 100755
index 00000000..ece4fb1b
--- /dev/null
+++ b/examples/ad_manager/v202208/custom_field_service/create_custom_fields.py
@@ -0,0 +1,66 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example creates custom fields.
+
+To determine which custom fields exist, run get_all_custom_fields.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ custom_field_service = client.GetService(
+ 'CustomFieldService', version='v202208')
+
+ # Create custom field objects.
+ custom_fields = [
+ {
+ 'name': 'Customer comments #%s' % uuid.uuid4(),
+ 'entityType': 'LINE_ITEM',
+ 'dataType': 'STRING',
+ 'visibility': 'FULL'
+ }, {
+ 'name': 'Internal approval status #%s' % uuid.uuid4(),
+ 'entityType': 'LINE_ITEM',
+ 'dataType': 'DROP_DOWN',
+ 'visibility': 'FULL'
+ }
+ ]
+
+ # Add custom fields.
+ custom_fields = custom_field_service.createCustomFields(custom_fields)
+
+ # Display results.
+ for custom_field in custom_fields:
+ print('Custom field with ID "%s" and name "%s" was created.'
+ % (custom_field['id'], custom_field['name']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/ad_manager/v202208/custom_field_service/deactivate_all_line_item_custom_fields.py
new file mode 100755
index 00000000..f59fb472
--- /dev/null
+++ b/examples/ad_manager/v202208/custom_field_service/deactivate_all_line_item_custom_fields.py
@@ -0,0 +1,73 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example deactivates all active line items custom fields.
+
+To determine which custom fields exist, run get_all_custom_fields.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ custom_field_service = client.GetService(
+ 'CustomFieldService', version='v202208')
+
+ # Create statement to select only active custom fields that apply to
+ # line items.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('entityType = :entityType and isActive = :isActive')
+ .WithBindVariable('entityType', 'LINE_ITEM')
+ .WithBindVariable('isActive', True))
+
+ custom_fields_deactivated = 0
+
+ # Get custom fields by statement.
+ while True:
+ response = custom_field_service.getCustomFieldsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ # Display results.
+ for custom_field in response['results']:
+ print('Custom field with ID "%s" and name "%s" will'
+ ' be deactivated.' % (custom_field['id'], custom_field['name']))
+ result = custom_field_service.performCustomFieldAction(
+ {'xsi_type': 'DeactivateCustomFields'}, statement.ToStatement())
+ if result and int(result['numChanges']) > 0:
+ custom_fields_deactivated += int(result['numChanges'])
+ statement.offset += statement.limit
+ else:
+ break
+
+ if custom_fields_deactivated > 0:
+ print('Number of custom fields deactivated: %s' % custom_fields_deactivated)
+ else:
+ print('No custom fields were deactivated.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/custom_field_service/get_all_custom_fields.py b/examples/ad_manager/v202208/custom_field_service/get_all_custom_fields.py
new file mode 100755
index 00000000..c406a4eb
--- /dev/null
+++ b/examples/ad_manager/v202208/custom_field_service/get_all_custom_fields.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all custom fields.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ custom_field_service = client.GetService(
+ 'CustomFieldService', version='v202208')
+
+ # Create a statement to select custom fields.
+ statement = ad_manager.StatementBuilder(version='v202208')
+
+ # Retrieve a small amount of custom fields at a time, paging
+ # through until all custom fields have been retrieved.
+ while True:
+ response = custom_field_service.getCustomFieldsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for custom_field in response['results']:
+ # Print out some information for each custom field.
+ print('Custom field with ID "%d" and name "%s" was found.\n' %
+ (custom_field['id'], custom_field['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/custom_field_service/get_custom_fields_for_line_items.py b/examples/ad_manager/v202208/custom_field_service/get_custom_fields_for_line_items.py
new file mode 100755
index 00000000..1c86aeff
--- /dev/null
+++ b/examples/ad_manager/v202208/custom_field_service/get_custom_fields_for_line_items.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all custom fields that can be applied to line items.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ custom_field_service = client.GetService(
+ 'CustomFieldService', version='v202208')
+ # Create a statement to select custom fields.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('entityType = :entityType')
+ .WithBindVariable('entityType', 'LINE_ITEM'))
+
+ # Retrieve a small amount of custom fields at a time, paging
+ # through until all custom fields have been retrieved.
+ while True:
+ response = custom_field_service.getCustomFieldsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for custom_field in response['results']:
+ # Print out some information for each custom field.
+ print('Custom field with ID "%d" and name "%s" was found.\n' %
+ (custom_field['id'], custom_field['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/custom_field_service/set_line_item_custom_field_value.py b/examples/ad_manager/v202208/custom_field_service/set_line_item_custom_field_value.py
new file mode 100755
index 00000000..bd5820bb
--- /dev/null
+++ b/examples/ad_manager/v202208/custom_field_service/set_line_item_custom_field_value.py
@@ -0,0 +1,139 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example sets custom field values on a line item.
+
+To determine which custom fields exist, run get_all_custom_fields.py.
+To determine which line item exist, run get_all_line_items.py.
+To create custom field options, run create_custom_field_options.py
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the custom fields, custom field option, and line item.
+CUSTOM_FIELD_ID = 'INSERT_CUSTOM_FIELD_ID_HERE'
+DROP_DOWN_CUSTOM_FIELD_ID = 'INSERT_DROP_DOWN_CUSTOM_FIELD_ID_HERE'
+CUSTOM_FIELD_OPTION_ID = 'INSERT_CUSTOM_FIELD_OPTION_ID_HERE'
+LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
+
+
+def main(client, custom_field_id, drop_down_custom_field_id,
+ custom_field_option_id, line_item_id):
+ # Initialize appropriate services.
+ custom_field_service = client.GetService(
+ 'CustomFieldService', version='v202208')
+
+ line_item_service = client.GetService('LineItemService', version='v202208')
+
+ # Create statement to get a custom field.
+ custom_field_statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('id = :customFieldId')
+ .WithBindVariable('customFieldId', custom_field_id)
+ .Limit(1))
+
+ # Get custom field.
+ custom_field = custom_field_service.getCustomFieldsByStatement(
+ custom_field_statement.ToStatement())['results'][0]
+
+ # Create statement to get a drop down custom field.
+ drop_down_custom_field_statement = (
+ ad_manager.StatementBuilder(version='v202208')
+ .Where('id = :dropDownCustomFieldId')
+ .WithBindVariable('dropDownCustomFieldId', drop_down_custom_field_id)
+ .Limit(1))
+
+ # Get drop-down custom field.
+ drop_down_custom_field = custom_field_service.getCustomFieldsByStatement(
+ drop_down_custom_field_statement.ToStatement())['results'][0]
+
+ # Create statement to get a line item.
+ line_item_statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('id = :lineItemId')
+ .WithBindVariable('lineItemId', line_item_id)
+ .Limit(1))
+
+ # Get line item.
+ line_item = line_item_service.getLineItemsByStatement(
+ line_item_statement.ToStatement())['results'][0]
+
+ if custom_field and line_item:
+ # Create custom field values.
+ custom_field_value = {
+ 'customFieldId': custom_field['id'],
+ 'xsi_type': 'CustomFieldValue',
+ 'value': {
+ 'xsi_type': 'TextValue',
+ 'value': 'Custom field value'
+ }
+ }
+
+ drop_down_custom_field_value = {
+ 'customFieldId': drop_down_custom_field['id'],
+ 'xsi_type': 'DropDownCustomFieldValue',
+ 'customFieldOptionId': custom_field_option_id,
+ }
+
+ custom_field_values = [custom_field_value, drop_down_custom_field_value]
+
+ old_custom_field_values = []
+ if 'customFieldValues' in line_item:
+ old_custom_field_values = line_item['customFieldValues']
+
+ # Only add existing custom field values for different custom fields than the
+ # ones you are setting.
+ for old_custom_field_value in old_custom_field_values:
+ if (old_custom_field_value['customFieldId'] !=
+ custom_field_value['customFieldId']
+ and old_custom_field_value['customFieldId'] !=
+ drop_down_custom_field_value['customFieldId']):
+ custom_field_values.append(old_custom_field_value)
+
+ line_item['customFieldValues'] = custom_field_values
+
+ # Update the line item on the server.
+ line_items = line_item_service.updateLineItems([line_item])
+
+ # Display results.
+ for line_item in line_items:
+ custom_field_value_strings = []
+ for value in line_item['customFieldValues']:
+ if ad_manager.AdManagerClassType(value) == 'CustomFieldValue':
+ custom_field_value_string = (
+ '{ID: "%s", value: "%s"}'
+ % (value['customFieldId'], value['value']['value']))
+ elif ad_manager.AdManagerClassType(value) == 'DropDownCustomFieldValue':
+ custom_field_value_string = (
+ '{ID: "%s", custom field option ID: "%s"}'
+ % (value['customFieldId'], value['customFieldOptionId']))
+ custom_field_value_strings.append(custom_field_value_string)
+ print('Line item with ID "%s" set with custom field values %s.'
+ % (line_item['id'], ','.join(custom_field_value_strings)))
+ else:
+ print('Line item or custom field not found.')
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CUSTOM_FIELD_ID, DROP_DOWN_CUSTOM_FIELD_ID,
+ CUSTOM_FIELD_OPTION_ID, LINE_ITEM_ID)
diff --git a/examples/ad_manager/v202208/custom_field_service/update_custom_fields.py b/examples/ad_manager/v202208/custom_field_service/update_custom_fields.py
new file mode 100755
index 00000000..de42faac
--- /dev/null
+++ b/examples/ad_manager/v202208/custom_field_service/update_custom_fields.py
@@ -0,0 +1,70 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example updates custom field descriptions.
+
+To determine which custom fields exist, run get_all_custom_fields.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the custom field to update.
+CUSTOM_FIELD_ID = 'INSERT_CUSTOM_FIELD_ID_HERE'
+
+
+def main(client, custom_field_id):
+ # Initialize appropriate service.
+ custom_field_service = client.GetService(
+ 'CustomFieldService', version='v202208')
+
+ # Create statement to get a custom field.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('id = :customFieldId')
+ .WithBindVariable('customFieldId', int(custom_field_id)))
+
+ # Get custom field.
+ custom_fields = custom_field_service.getCustomsFieldByStatement(
+ statement.ToStatement())
+
+ if custom_fields:
+ for custom_field in custom_fields:
+ custom_field['description'] += ' Updated.'
+
+ # Update the custom field on the server.
+ custom_fields = custom_field_service.updateCustomFields(custom_fields)
+
+ # Display results.
+ for custom_field in custom_fields:
+ print(('Custom field with ID "%s", name "%s", and '
+ 'description "%s" was updated.')
+ % (custom_field['id'], custom_field['name'],
+ custom_field['description']))
+ else:
+ print('No custom fields found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CUSTOM_FIELD_ID)
diff --git a/examples/ad_manager/v202208/custom_targeting_service/__init__.py b/examples/ad_manager/v202208/custom_targeting_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202208/custom_targeting_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202208/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/ad_manager/v202208/custom_targeting_service/create_custom_targeting_keys_and_values.py
new file mode 100755
index 00000000..a9f4adaf
--- /dev/null
+++ b/examples/ad_manager/v202208/custom_targeting_service/create_custom_targeting_keys_and_values.py
@@ -0,0 +1,132 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example creates new custom targeting keys and values.
+
+To determine which custom targeting keys and values exist, run
+get_all_custom_targeting_keys_and_values.py. To target these custom targeting
+keys and values, run target_custom_criteria_example.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ custom_targeting_service = client.GetService(
+ 'CustomTargetingService', version='v202208')
+
+ # Create custom targeting key objects.
+ keys = [
+ {
+ 'displayName': 'gender',
+ 'name': 'g',
+ 'type': 'PREDEFINED'
+ },
+ {
+ 'displayName': 'car model',
+ 'name': 'c',
+ 'type': 'FREEFORM'
+ },
+ # Add predefined key that may be use for content targeting.
+ {
+ 'displayName': 'genre',
+ 'name': 'genre',
+ 'type': 'PREDEFINED'
+ }
+ ]
+
+ # Add custom targeting keys.
+ keys = custom_targeting_service.createCustomTargetingKeys(keys)
+
+ # Display results.
+ if keys:
+ for key in keys:
+ print('A custom targeting key with id "%s", name "%s", and display '
+ 'name "%s" was created.' % (key['id'], key['name'],
+ key['displayName']))
+ else:
+ print('No keys were created.')
+
+ # Create custom targeting value objects.
+ values = [
+ {
+ 'customTargetingKeyId': keys[0]['id'],
+ 'displayName': 'male',
+ # Name is set to 1 so that the actual name can be hidden from website
+ # users.
+ 'name': '1',
+ 'matchType': 'EXACT'
+ },
+ {
+ 'customTargetingKeyId': keys[0]['id'],
+ 'displayName': 'female',
+ # Name is set to 2 so that the actual name can be hidden from website
+ # users.
+ 'name': '2',
+ 'matchType': 'EXACT'
+ },
+ {
+ 'customTargetingKeyId': keys[1]['id'],
+ 'displayName': 'honda civic',
+ 'name': 'honda civic',
+ 'matchType': 'EXACT'
+ },
+ {
+ 'customTargetingKeyId': keys[1]['id'],
+ 'displayName': 'toyota',
+ 'name': 'toyota',
+ 'matchType': 'EXACT'
+ },
+ {
+ 'customTargetingKeyId': keys[2]['id'],
+ 'displayName': 'comedy',
+ 'name': 'comedy',
+ 'matchType': 'EXACT'
+ },
+ {
+ 'customTargetingKeyId': keys[2]['id'],
+ 'displayName': 'drama',
+ 'name': 'drama',
+ 'matchType': 'EXACT'
+ }
+ ]
+
+ # Add custom targeting values.
+ values = custom_targeting_service.createCustomTargetingValues(values)
+
+ # Display results.
+ if values:
+ for value in values:
+ print('A custom targeting value with id "%s", belonging to key with id'
+ ' "%s", name "%s", and display name "%s" was created.'
+ % (value['id'], value['customTargetingKeyId'], value['name'],
+ value['displayName']))
+ else:
+ print('No values were created.')
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/custom_targeting_service/delete_custom_targeting_keys.py b/examples/ad_manager/v202208/custom_targeting_service/delete_custom_targeting_keys.py
new file mode 100755
index 00000000..892e232f
--- /dev/null
+++ b/examples/ad_manager/v202208/custom_targeting_service/delete_custom_targeting_keys.py
@@ -0,0 +1,77 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example deletes a custom targeting key by its name.
+
+To determine which custom targeting keys exist, run
+get_all_custom_targeting_keys_and_values.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+KEY_NAME = 'INSERT_CUSTOM_TARGETING_KEY_NAME_HERE'
+
+
+def main(client, key_name):
+ # Initialize appropriate service.
+ custom_targeting_service = client.GetService(
+ 'CustomTargetingService', version='v202208')
+
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('name = :name')
+ .WithBindVariable('name', key_name))
+
+ deleted_custom_targeting_keys = 0
+
+ # Get custom targeting keys.
+ while True:
+ response = custom_targeting_service.getCustomTargetingKeysByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ key_ids = [str(key['id']) for key in response['results']]
+ action = {'xsi_type': 'DeleteCustomTargetingKeys'}
+ key_statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('id IN (%s)' % ', '.join(key_ids)))
+
+ # Delete custom targeting keys.
+ result = custom_targeting_service.performCustomTargetingKeyAction(
+ action, key_statement.ToStatement())
+
+ if result and int(result['numChanges']) > 0:
+ deleted_custom_targeting_keys += int(result['numChanges'])
+ statement.offset += statement.limit
+ else:
+ break
+
+ if deleted_custom_targeting_keys > 0:
+ print('Number of custom targeting keys deleted: %s'
+ % deleted_custom_targeting_keys)
+ else:
+ print('No custom targeting keys were deleted.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, KEY_NAME)
diff --git a/examples/ad_manager/v202208/custom_targeting_service/delete_custom_targeting_values.py b/examples/ad_manager/v202208/custom_targeting_service/delete_custom_targeting_values.py
new file mode 100755
index 00000000..61049edd
--- /dev/null
+++ b/examples/ad_manager/v202208/custom_targeting_service/delete_custom_targeting_values.py
@@ -0,0 +1,77 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Deletes custom targeting values for a given custom targeting key.
+
+To determine which custom targeting keys and values exist, run
+get_all_custom_targeting_keys_and_values.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'
+
+
+def main(client, key_id):
+ # Initialize appropriate service.
+ custom_targeting_service = client.GetService(
+ 'CustomTargetingService', version='v202208')
+
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('customTargetingKeyId = :keyId')
+ .WithBindVariable('keyId', key_id))
+
+ deleted_custom_targeting_values = 0
+
+ # Get custom targeting values.
+ while True:
+ response = custom_targeting_service.getCustomTargetingValuesByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ value_ids = [str(value['id']) for value in response['results']]
+ action = {'xsi_type': 'DeleteCustomTargetingValues'}
+ value_statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('customTargetingKeyId = :keyId '
+ 'AND id IN (%s)' % ', '.join(value_ids))
+ .WithBindVariable('keyId', key_id))
+
+ # Delete custom targeting values.
+ result = custom_targeting_service.performCustomTargetingValueAction(
+ action, value_statement.ToStatement())
+ if result and int(result['numChanges']) > 0:
+ deleted_custom_targeting_values += int(result['numChanges'])
+ statement.offset += statement.limit
+ else:
+ break
+
+ if deleted_custom_targeting_values > 0:
+ print('Number of custom targeting values deleted: %s'
+ % deleted_custom_targeting_values)
+ else:
+ print('No custom targeting values were deleted.')
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, KEY_ID)
diff --git a/examples/ad_manager/v202208/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/ad_manager/v202208/custom_targeting_service/get_all_custom_targeting_keys_and_values.py
new file mode 100755
index 00000000..dd10dd0e
--- /dev/null
+++ b/examples/ad_manager/v202208/custom_targeting_service/get_all_custom_targeting_keys_and_values.py
@@ -0,0 +1,72 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all custom targeting keys and values.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ custom_targeting_service = client.GetService(
+ 'CustomTargetingService', version='v202208')
+
+ # Create statement to get all targeting keys.
+ targeting_key_statement = ad_manager.StatementBuilder(version='v202208')
+
+ all_keys = []
+
+ # Get custom targeting keys by statement.
+ while True:
+ response = custom_targeting_service.getCustomTargetingKeysByStatement(
+ targeting_key_statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ all_keys.extend(response['results'])
+ targeting_key_statement.offset += targeting_key_statement.limit
+ else:
+ break
+
+ if all_keys:
+ # Create a statement to select custom targeting values.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('customTargetingKeyId IN (%s)' %
+ ', '.join([str(key['id']) for key in all_keys])))
+
+ # Retrieve a small amount of custom targeting values at a time, paging
+ # through until all custom targeting values have been retrieved.
+ while True:
+ response = custom_targeting_service.getCustomTargetingValuesByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for custom_targeting_value in response['results']:
+ # Print out some information for each custom targeting value.
+ print('Custom targeting value with ID "%d", name "%s", display name '
+ '"%s", and custom targeting key ID "%d" was found.\n' %
+ (custom_targeting_value['id'], custom_targeting_value['name'],
+ custom_targeting_value['displayName'],
+ custom_targeting_value['customTargetingKeyId']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/ad_manager/v202208/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py
new file mode 100755
index 00000000..8b7657b1
--- /dev/null
+++ b/examples/ad_manager/v202208/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py
@@ -0,0 +1,74 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all custom targeting keys and values.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ custom_targeting_service = client.GetService(
+ 'CustomTargetingService', version='v202208')
+
+ # Create statement to get targeting keys for predefined values.
+ targeting_key_statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('type = :type')
+ .WithBindVariable('type', 'PREDEFINED'))
+
+ all_keys = []
+
+ # Get custom targeting keys by statement.
+ while True:
+ response = custom_targeting_service.getCustomTargetingKeysByStatement(
+ targeting_key_statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ all_keys.extend(response['results'])
+ targeting_key_statement.offset += targeting_key_statement.limit
+ else:
+ break
+
+ if all_keys:
+ # Create a statement to select custom targeting values.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('customTargetingKeyId IN (:ids)')
+ .WithBindVariable('ids', [key['id'] for key in all_keys]))
+
+ # Retrieve a small amount of custom targeting values at a time, paging
+ # through until all custom targeting values have been retrieved.
+ while True:
+ response = custom_targeting_service.getCustomTargetingValuesByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for custom_targeting_value in response['results']:
+ # Print out some information for each custom targeting value.
+ print('Custom targeting value with ID "%d", name "%s", display name '
+ '"%s", and custom targeting key ID "%d" was found.\n' %
+ (custom_targeting_value['id'], custom_targeting_value['name'],
+ custom_targeting_value['displayName'],
+ custom_targeting_value['customTargetingKeyId']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/custom_targeting_service/update_custom_targeting_keys.py b/examples/ad_manager/v202208/custom_targeting_service/update_custom_targeting_keys.py
new file mode 100755
index 00000000..780da8f5
--- /dev/null
+++ b/examples/ad_manager/v202208/custom_targeting_service/update_custom_targeting_keys.py
@@ -0,0 +1,67 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example updates the display name of a single custom targeting key.
+
+To determine which custom targeting keys exist, run
+get_all_custom_targeting_keys_and_values.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'
+
+
+def main(client, key_id):
+ # Initialize appropriate service.
+ custom_targeting_service = client.GetService(
+ 'CustomTargetingService', version='v202208')
+
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('id = :keyId')
+ .WithBindVariable('keyId', int(key_id))
+ .Limit(1))
+
+ # Get custom targeting keys by statement.
+ response = custom_targeting_service.getCustomTargetingKeysByStatement(
+ statement.ToStatement())
+
+ # Update each local custom targeting key object by changing its display name.
+ if 'results' in response and len(response['results']):
+ updated_keys = []
+ for key in response['results']:
+ if not key['displayName']:
+ key['displayName'] = key['name']
+ key['displayName'] += ' (Deprecated)'
+ updated_keys.append(key)
+ keys = custom_targeting_service.updateCustomTargetingKeys(updated_keys)
+
+ # Display results.
+ if keys:
+ for key in keys:
+ print('Custom targeting key with id "%s", name "%s", display name '
+ '"%s", and type "%s" was updated.'
+ % (key['id'], key['name'], key['displayName'], key['type']))
+ else:
+ print('No custom targeting keys were found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CUSTOM_TARGETING_KEY_ID)
diff --git a/examples/ad_manager/v202208/custom_targeting_service/update_custom_targeting_values.py b/examples/ad_manager/v202208/custom_targeting_service/update_custom_targeting_values.py
new file mode 100755
index 00000000..b087d46c
--- /dev/null
+++ b/examples/ad_manager/v202208/custom_targeting_service/update_custom_targeting_values.py
@@ -0,0 +1,71 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Updates name of custom targeting values belonging to a custom targeting key.
+
+To determine which custom targeting keys exist, run
+get_all_custom_targeting_keys_and_values.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'
+
+
+def main(client, key_id):
+ # Initialize appropriate service.
+ custom_targeting_service = client.GetService(
+ 'CustomTargetingService', version='v202208')
+
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('customTargetingKeyId = :keyId')
+ .WithBindVariable('keyId', int(key_id)))
+
+ while True:
+ # Get custom targeting values by statement.
+ response = custom_targeting_service.getCustomTargetingValuesByStatement(
+ statement.ToStatement())
+
+ # Update each local custom targeting value object by changing its name.
+ if 'results' in response and len(response['results']):
+ updated_values = []
+ for value in response['results']:
+ if not value['displayName']:
+ value['displayName'] = value['name']
+ value['displayName'] += ' (Deprecated)'
+ updated_values.append(value)
+ values = custom_targeting_service.updateCustomTargetingValues(
+ updated_values)
+
+ # Display results.
+ for value in values:
+ print('Custom targeting value with id "%s", name "%s", and display'
+ ' name "%s" was updated.'
+ % (value['id'], value['name'], value['displayName']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ if response['totalResultSetSize'] == 0:
+ print('No custom targeting values were updated.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CUSTOM_TARGETING_KEY_ID)
diff --git a/examples/ad_manager/v202208/forecast_service/get_availability_forecast.py b/examples/ad_manager/v202208/forecast_service/get_availability_forecast.py
new file mode 100755
index 00000000..489a0395
--- /dev/null
+++ b/examples/ad_manager/v202208/forecast_service/get_availability_forecast.py
@@ -0,0 +1,251 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets a forecast for a prospective line item.
+
+The prospective line item targets the entire network. The targeting can be
+modified to determine forecasts for other criteria such as custom criteria
+targeting (in addition to targeting the whole network). See
+create_line_items.py for an example of how to create more complex targeting.
+
+"""
+
+
+import datetime
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+import pytz
+
+# Set the ID of the advertiser (company) to forecast for. Setting an advertiser
+# will cause the forecast to apply the appropriate unified blocking rules.
+ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE'
+
+
+def main(client, advertiser_id):
+ # Initialize appropriate service.
+ forecast_service = client.GetService('ForecastService', version='v202208')
+ network_service = client.GetService('NetworkService', version='v202208')
+
+ # get the root ad unit ID to target the entire network.
+ root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId']
+
+ now_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York'))
+ end_datetime = now_datetime + datetime.timedelta(days=5)
+
+ # Create prospective line item.
+ line_item = {
+ 'targeting': {
+ 'inventoryTargeting': {
+ 'targetedAdUnits': [
+ {
+ 'includeDescendants': True,
+ 'adUnitId': root_ad_unit_id,
+ }
+ ]
+ }
+ },
+ 'creativePlaceholders': [
+ {
+ 'size': {
+ 'width': '300',
+ 'height': '250'
+ },
+ 'isAmpOnly': True,
+ },
+ {
+ 'size': {
+ 'width': '120',
+ 'height': '600'
+ }
+ }
+ ],
+ 'lineItemType': 'SPONSORSHIP',
+ 'startDateTimeType': 'IMMEDIATELY',
+ 'endDateTime': end_datetime,
+ 'costType': 'CPM',
+ 'costPerUnit': {
+ 'currencyCode': 'USD',
+ 'microAmount': '2000000'
+ },
+ 'primaryGoal': {
+ 'units': '50',
+ 'unitType': 'IMPRESSIONS',
+ 'goalType': 'DAILY'
+ },
+ 'contractedUnitsBought': '100',
+ 'creativeRotationType': 'EVEN',
+ 'discountType': 'PERCENTAGE',
+ }
+
+ prospective_line_item = {
+ 'lineItem': line_item,
+ 'advertiserId': advertiser_id
+ }
+
+ # Set forecasting options.
+ forecast_options = {
+ 'includeContendingLineItems': True,
+ # The field includeTargetingCriteriaBreakdown can only be set if
+ # breakdowns are not manually specified.
+ # 'includeTargetingCriteriaBreakdown': True,
+ 'breakdown': {
+ 'timeWindows': [
+ now_datetime,
+ now_datetime + datetime.timedelta(days=1),
+ now_datetime + datetime.timedelta(days=2),
+ now_datetime + datetime.timedelta(days=3),
+ now_datetime + datetime.timedelta(days=4),
+ end_datetime
+ ],
+ 'targets': [
+ {
+ # Optional, the name field is only used to identify this
+ # breakdown in the response.
+ 'name': 'United States',
+ 'targeting': {
+ 'inventoryTargeting': {
+ 'targetedAdUnits': [
+ {
+ 'includeDescendants': True,
+ 'adUnitId': root_ad_unit_id,
+ }
+ ]
+ },
+ 'geoTargeting': {
+ 'targetedLocations': [
+ {
+ 'id': '2840',
+ 'displayName': 'US'
+ }
+ ]
+ }
+ }
+ },
+ {
+ # Optional, the name field is only used to identify this
+ # breakdown in the response.
+ 'name': 'Geneva',
+ 'targeting': {
+ 'inventoryTargeting': {
+ 'targetedAdUnits': [
+ {
+ 'includeDescendants': True,
+ 'adUnitId': root_ad_unit_id,
+ }
+ ]
+ },
+ 'geoTargeting': {
+ 'targetedLocations': [
+ {
+ 'id': '20133',
+ 'displayName': 'Geneva'
+ }
+ ]
+ }
+ }
+ }
+ ]
+ }
+ }
+
+ # Get forecast.
+ forecast = forecast_service.getAvailabilityForecast(
+ prospective_line_item, forecast_options)
+ matched = forecast['matchedUnits']
+ available = forecast['availableUnits']
+ possible = forecast['possibleUnits'] if 'possibleUnits' in forecast else None
+ unit_type = forecast['unitType'].lower()
+
+ available_percent_overall, possible_percent_overall = CalculateForecastStats(
+ matched, available, possible)
+
+ contending_line_items = getattr(forecast, 'contendingLineItems', [])
+
+ # Display results.
+ print('%s %s matched overall.' % (matched, unit_type))
+ print('%s%% %s available overall.' % (available_percent_overall, unit_type))
+ print('%d contending line items overall.' % len(contending_line_items))
+ if possible:
+ print('%s%% %s possible overall.' % (possible_percent_overall, unit_type))
+
+ if 'breakdowns' in forecast and len(forecast['breakdowns']):
+ for breakdown in forecast['breakdowns']:
+ print('For breakdown time period %s - %s:' % (
+ FormatSOAPDateTime(breakdown['startTime']),
+ FormatSOAPDateTime(breakdown['endTime'])))
+ for breakdown_entry in breakdown['breakdownEntries']:
+ matched = breakdown_entry['forecast']['matched']
+ available = breakdown_entry['forecast']['available']
+ possible = (breakdown_entry['forecast']['possible']
+ if 'possible' in breakdown_entry['forecast'] else None)
+ name = breakdown_entry['name'] if 'name' in breakdown_entry else None
+ if name:
+ print('\tFor targeting breakdown named \'%s\'' % name)
+ available_percent, possible_percent = CalculateForecastStats(
+ matched, available, possible)
+ print('\t\t%s %s matched.' % (matched, unit_type))
+ print('\t\t%s%% %s available.' % (available_percent, unit_type))
+ if possible:
+ print('\t\t%s%% %s possible.' % (possible_percent, unit_type))
+
+
+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'],
+ value['hour'], value['minute'], value['second'], value['timeZoneId'])
+
+
+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 that are available and possible.
+ """
+ if matched > 0:
+ available_percent = (float(available) / matched) * 100.
+ else:
+ available_percent = 0
+
+ if possible is not None:
+ if matched > 0:
+ possible_percent = (possible/float(matched)) * 100.
+ else:
+ possible_percent = 0
+ else:
+ possible_percent = None
+
+ return available_percent, possible_percent
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ADVERTISER_ID)
diff --git a/examples/ad_manager/v202208/forecast_service/get_availability_forecast_for_line_item.py b/examples/ad_manager/v202208/forecast_service/get_availability_forecast_for_line_item.py
new file mode 100755
index 00000000..1b4dc727
--- /dev/null
+++ b/examples/ad_manager/v202208/forecast_service/get_availability_forecast_for_line_item.py
@@ -0,0 +1,67 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example gets an availability forecast for an existing line item.
+
+To determine which line items exist, run get_all_line_items.py.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the line item to get a forecast for.
+LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
+
+
+def main(client, line_item_id):
+ # Initialize appropriate service.
+ forecast_service = client.GetService('ForecastService', version='v202208')
+
+ # Set forecasting options.
+ forecast_options = {
+ 'includeContendingLineItems': True,
+ 'includeTargetingCriteriaBreakdown': True,
+ }
+
+ # Get forecast for line item.
+ forecast = forecast_service.getAvailabilityForecastById(
+ line_item_id, forecast_options)
+ matched = int(forecast['matchedUnits'])
+ available_units = int(forecast['availableUnits'])
+
+ if matched > 0:
+ available_percent = (float(available_units) / matched) * 100.
+ else:
+ available_percent = 0
+
+ contending_line_items = getattr(forecast, 'contentingLineItems', [])
+
+ # Display results.
+ print('%s %s matched.' % (matched, forecast['unitType'].lower()))
+ print('%s%% %s available.' % (
+ available_percent, forecast['unitType'].lower()))
+ print('%d contending line items.' % len(contending_line_items))
+
+ if 'possibleUnits' in forecast and matched:
+ possible_percent = (int(forecast['possibleUnits'])/float(matched)) * 100.
+ print('%s%% %s possible' % (possible_percent, forecast['unitType'].lower()))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, LINE_ITEM_ID)
diff --git a/examples/ad_manager/v202208/forecast_service/get_delivery_forecast_for_line_items.py b/examples/ad_manager/v202208/forecast_service/get_delivery_forecast_for_line_items.py
new file mode 100755
index 00000000..882d78ae
--- /dev/null
+++ b/examples/ad_manager/v202208/forecast_service/get_delivery_forecast_for_line_items.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example gets a delivery forecast for two existing line items.
+
+To determine which line items exist, run get_all_line_items.py.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the line items to get forecasts for.
+LINE_ITEM_ID_1 = 'INSERT_LINE_ITEM_1_ID_HERE'
+LINE_ITEM_ID_2 = 'INSERT_LINE_ITEM_2_ID_HERE'
+
+
+def main(client, line_item_id1, line_item_id2):
+ # Initialize appropriate service.
+ forecast_service = client.GetService('ForecastService', version='v202208')
+
+ # Get forecast for line item.
+ forecast = forecast_service.getDeliveryForecastByIds(
+ [line_item_id1, line_item_id2], {'ignoredLineItemIds': []})
+
+ for single_forecast in forecast['lineItemDeliveryForecasts']:
+ unit_type = single_forecast['unitType']
+ print('Forecast for line item %d:\n\t%d %s matched\n\t%d %s delivered\n\t'
+ '%d %s predicted\n' % (
+ single_forecast['lineItemId'], single_forecast['matchedUnits'],
+ unit_type, single_forecast['deliveredUnits'], unit_type,
+ single_forecast['predictedDeliveryUnits'], unit_type))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, LINE_ITEM_ID_1, LINE_ITEM_ID_2)
diff --git a/examples/ad_manager/v202208/forecast_service/get_traffic_data.py b/examples/ad_manager/v202208/forecast_service/get_traffic_data.py
new file mode 100755
index 00000000..d5d2e0f4
--- /dev/null
+++ b/examples/ad_manager/v202208/forecast_service/get_traffic_data.py
@@ -0,0 +1,123 @@
+#!/usr/bin/env python
+#
+# Copyright 2020, Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets the forecasted run-of-network traffic data."""
+
+
+import datetime
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ forecast_service = client.GetService('ForecastService', version='v202208')
+ network_service = client.GetService('NetworkService', version='v202208')
+
+ # get the root ad unit ID to target the entire network.
+ root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId']
+
+ # Create a start date that's 7 days in the past and an end date that's 7 days
+ # in the future.
+ today = datetime.date.today()
+ start_date = today - datetime.timedelta(days=7)
+ end_date = today + datetime.timedelta(days=7)
+
+ # Create targeting.
+ targeting = {
+ 'inventoryTargeting': {
+ 'targetedAdUnits': [
+ {
+ 'includeDescendants': True,
+ 'adUnitId': root_ad_unit_id,
+ }
+ ]
+ }
+ }
+
+ # Request the traffic forecast data.
+ traffic_data = forecast_service.getTrafficData({
+ 'targeting': targeting,
+ 'requestedDateRange': {
+ 'startDate': start_date,
+ 'endDate': end_date
+ }
+ })
+
+ # Display historical data.
+ historical_time_series = traffic_data['historicalTimeSeries']
+ if historical_time_series is None:
+ print('No historical data to display.')
+ else:
+ historical_start_date, historical_end_date = GetDatesFromForecastTimeSeries(
+ historical_time_series)
+
+ print('Historical Data:')
+ offset = 0
+ current_date = historical_start_date
+ while current_date <= historical_end_date:
+ print('%s: %d' % (current_date.isoformat(),
+ historical_time_series['values'][offset]))
+ offset += 1
+ current_date = historical_start_date + datetime.timedelta(days=offset)
+
+ # Display forecasted data.
+ forecasted_time_series = traffic_data['forecastedTimeSeries']
+ if forecasted_time_series is None:
+ print('No forecasted data to display.')
+ else:
+ forecasted_start_date, forecasted_end_date = GetDatesFromForecastTimeSeries(
+ forecasted_time_series)
+
+ print('Forecasted Data:')
+ offset = 0
+ current_date = forecasted_start_date
+ while current_date <= forecasted_end_date:
+ print('%s: %d' % (current_date.isoformat(),
+ forecasted_time_series['values'][offset]))
+ offset += 1
+ current_date = forecasted_start_date + datetime.timedelta(days=offset)
+
+
+def GetDatesFromForecastTimeSeries(time_series):
+ """Creates datetime.date objects from a forecast time series object.
+
+ Args:
+ time_series: The forecast time series containing start and end date info.
+
+ Returns:
+ A tuple of datetime.date objects, the first representing the start date and
+ the second representing the end date.
+ """
+ date_range = time_series['timeSeriesDateRange']
+ start_date = datetime.date(
+ date_range['startDate']['year'],
+ date_range['startDate']['month'],
+ date_range['startDate']['day']
+ )
+ end_date = datetime.date(
+ date_range['endDate']['year'],
+ date_range['endDate']['month'],
+ date_range['endDate']['day']
+ )
+ return start_date, end_date
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/inventory_service/__init__.py b/examples/ad_manager/v202208/inventory_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202208/inventory_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202208/inventory_service/archive_ad_units.py b/examples/ad_manager/v202208/inventory_service/archive_ad_units.py
new file mode 100755
index 00000000..26a16328
--- /dev/null
+++ b/examples/ad_manager/v202208/inventory_service/archive_ad_units.py
@@ -0,0 +1,75 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example archives ad units.
+
+The parent ad unit and all ad units underneath it will be archived. To create ad
+units, run create_ad_units.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+PARENT_AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE'
+
+
+def main(client, parent_id):
+ # Initialize appropriate service.
+ inventory_service = client.GetService('InventoryService', version='v202208')
+
+ # Create a query to select ad units under the parent ad unit and the parent ad
+ # unit.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('parentId = :parentId or id = :parentId')
+ .WithBindVariable('parentId', int(parent_id)))
+
+ ad_units_archived = 0
+
+ # Get ad units by statement.
+ while True:
+ response = inventory_service.getAdUnitsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for ad_unit in response['results']:
+ print('Ad unit with ID "%s" and name "%s" will be archived.'
+ % (ad_unit['id'], ad_unit['name']))
+ # Perform action.
+ result = inventory_service.performAdUnitAction(
+ {'xsi_type': 'ArchiveAdUnits'}, statement.ToStatement())
+ if result and int(result['numChanges']) > 0:
+ ad_units_archived += int(result['numChanges'])
+ statement.offset += statement.limit
+ else:
+ break
+
+ # Display results.
+ if ad_units_archived > 0:
+ print('Number of ad units archived: %s' % ad_units_archived)
+ else:
+ print('No ad units were archived.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, PARENT_AD_UNIT_ID)
diff --git a/examples/ad_manager/v202208/inventory_service/create_ad_units.py b/examples/ad_manager/v202208/inventory_service/create_ad_units.py
new file mode 100755
index 00000000..c940de90
--- /dev/null
+++ b/examples/ad_manager/v202208/inventory_service/create_ad_units.py
@@ -0,0 +1,70 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new ad units.
+
+To determine which ad units exist, run get_all_ad_units.py
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+PARENT_AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE'
+
+
+def main(client, parent_id):
+ # Initialize appropriate service.
+ inventory_service = client.GetService('InventoryService', version='v202208')
+
+ # Create ad unit size.
+ ad_unit_size = {
+ 'size': {
+ 'width': '300',
+ 'height': '250'
+ },
+ 'environmentType': 'BROWSER'
+ }
+
+ # Create ad unit objects.
+ ad_unit = {
+ 'name': 'Ad_unit_%s' % uuid.uuid4(),
+ 'parentId': parent_id,
+ 'description': 'Ad unit description.',
+ 'targetWindow': 'BLANK',
+ 'adUnitSizes': [ad_unit_size]
+ }
+
+ # Add ad units.
+ ad_units = inventory_service.createAdUnits([ad_unit])
+
+ # Display results.
+ for ad_unit in ad_units:
+ print('Ad unit with ID "%s" and name "%s" was created.'
+ % (ad_unit['id'], ad_unit['name']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, PARENT_AD_UNIT_ID)
diff --git a/examples/ad_manager/v202208/inventory_service/get_ad_unit_hierarchy.py b/examples/ad_manager/v202208/inventory_service/get_ad_unit_hierarchy.py
new file mode 100755
index 00000000..683fff15
--- /dev/null
+++ b/examples/ad_manager/v202208/inventory_service/get_ad_unit_hierarchy.py
@@ -0,0 +1,115 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example prints all ad unit names as a tree."""
+
+
+# Import appropriate modules from the client library.
+import collections
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate services.
+ network_service = client.GetService('NetworkService', version='v202208')
+ inventory_service = client.GetService('InventoryService', version='v202208')
+
+ # Set the parent ad unit's ID for all children ad units to be fetched from.
+ current_network = network_service.getCurrentNetwork()
+ root_ad_unit_id = current_network['effectiveRootAdUnitId']
+
+ # Create a statement to select only the root ad unit by ID.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('id = :id')
+ .OrderBy('id', ascending=True)
+ .Limit(1)
+ .WithBindVariable('id', root_ad_unit_id))
+
+ # Make a request for the root ad unit
+ response = inventory_service.getAdUnitsByStatement(statement.ToStatement())
+ root_ad_unit = response['results'][0]
+
+ all_ad_units = get_all_ad_units(inventory_service)
+
+ display_hierarchy(root_ad_unit, 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='v202208')
+ .OrderBy('id', ascending=True))
+
+ # Pull down all ad units into a list
+ keep_iterating = True
+ total_results = 0
+ found_ad_units = []
+ while keep_iterating:
+ page = inventory_service.getAdUnitsByStatement(statement.ToStatement())
+ if 'results' in page and len(page['results']):
+ total_results = page['totalResultSetSize']
+ found_ad_units.extend(page['results'])
+
+ statement.offset += statement.limit
+ keep_iterating = statement.offset < total_results
+
+ return found_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.defaultdict(list)
+ for ad_unit in all_ad_units:
+ if 'parentId' in ad_unit:
+ parent_id_to_children[ad_unit['parentId']].append(ad_unit)
+ parent_id_to_children = dict(parent_id_to_children)
+
+ display_hierarchy_helper(root_ad_unit, parent_id_to_children, 0)
+
+
+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([' '] * depth)),
+ root['name'], root['id']))
+
+ # Recurse for each child of this root that has children.
+ for child in parent_id_to_children.get(root['id'], []):
+ display_hierarchy_helper(child, parent_id_to_children, depth + 1)
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/inventory_service/get_all_ad_unit_sizes.py b/examples/ad_manager/v202208/inventory_service/get_all_ad_unit_sizes.py
new file mode 100755
index 00000000..c7e012b3
--- /dev/null
+++ b/examples/ad_manager/v202208/inventory_service/get_all_ad_unit_sizes.py
@@ -0,0 +1,46 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all ad unit sizes.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ ad_unit_size_service = client.GetService(
+ 'InventoryService', version='v202208')
+
+ # Create a statement to select ad unit sizes.
+ statement = ad_manager.StatementBuilder(version='v202208')
+
+ # Retrieve a small amount of ad unit sizes at a time, paging
+ # through until all ad unit sizes have been retrieved.
+ response = ad_unit_size_service.getAdUnitSizesByStatement(
+ statement.ToStatement())
+ if response:
+ for ad_unit_size in response:
+ # Print out some information for each ad unit size.
+ if 'fullDisplayString' in ad_unit_size:
+ print('Ad unit size with dimensions "%s" was found.\n' %
+ (ad_unit_size['fullDisplayString']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/inventory_service/get_all_ad_units.py b/examples/ad_manager/v202208/inventory_service/get_all_ad_units.py
new file mode 100755
index 00000000..01b99a93
--- /dev/null
+++ b/examples/ad_manager/v202208/inventory_service/get_all_ad_units.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all ad units.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ ad_unit_service = client.GetService('InventoryService', version='v202208')
+
+ # Create a statement to select ad units.
+ statement = ad_manager.StatementBuilder(version='v202208')
+
+ # Retrieve a small amount of ad units at a time, paging
+ # through until all ad units have been retrieved.
+ while True:
+ response = ad_unit_service.getAdUnitsByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for ad_unit in response['results']:
+ # Print out some information for each ad unit.
+ print('Ad unit with ID "%s" and name "%s" was found.\n' %
+ (ad_unit['id'], ad_unit['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/inventory_service/get_top_level_ad_units.py b/examples/ad_manager/v202208/inventory_service/get_top_level_ad_units.py
new file mode 100755
index 00000000..7aecd91d
--- /dev/null
+++ b/examples/ad_manager/v202208/inventory_service/get_top_level_ad_units.py
@@ -0,0 +1,58 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all child ad units of the effective root ad unit."""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate services.
+ network_service = client.GetService('NetworkService', version='v202208')
+ inventory_service = client.GetService('InventoryService', version='v202208')
+
+ # Set the parent ad unit's ID for all children ad units to be fetched from.
+ current_network = network_service.getCurrentNetwork()
+ parent_ad_unit_id = current_network['effectiveRootAdUnitId']
+
+ # Create a statement to select ad units under the parent ad unit.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('parentId = :parentId')
+ .OrderBy('id', ascending=True)
+ .WithBindVariable('parentId', parent_ad_unit_id))
+
+ # Retrieve a small amount of ad units at a time, paging
+ # through until all ad units have been retrieved.
+ while True:
+ response = inventory_service.getAdUnitsByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for ad_unit in response['results']:
+ # Print out some information for each ad unit.
+ print('Ad unit with ID "%s" and name "%s" was found.\n' %
+ (ad_unit['id'], ad_unit['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/inventory_service/update_ad_units.py b/examples/ad_manager/v202208/inventory_service/update_ad_units.py
new file mode 100755
index 00000000..3b0d17f4
--- /dev/null
+++ b/examples/ad_manager/v202208/inventory_service/update_ad_units.py
@@ -0,0 +1,82 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates ad unit sizes by adding a banner ad size.
+
+To determine which ad units exist, run get_all_ad_units.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+# Set the ID of the ad unit to get.
+AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE'
+
+
+def main(client, ad_unit_id):
+ # Initialize appropriate service.
+ inventory_service = client.GetService('InventoryService', version='v202208')
+
+ # Create a statement to select a single ad unit by ID.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('id = :id')
+ .WithBindVariable('id', ad_unit_id))
+
+ # Get ad units by statement.
+ response = inventory_service.getAdUnitsByStatement(
+ statement.ToStatement())
+
+ # Add the size 468x60 to the ad unit.
+ ad_unit_size = {
+ 'size': {
+ 'width': '468',
+ 'height': '60'
+ },
+ 'environmentType': 'BROWSER'
+ }
+
+ if 'results' in response and len(response['results']):
+ updated_ad_units = []
+ for ad_unit in response['results']:
+ if 'adUnitSizes' not in ad_unit:
+ ad_unit['adUnitSizes'] = []
+ ad_unit['adUnitSizes'].append(ad_unit_size)
+ updated_ad_units.append(ad_unit)
+
+ # Update ad unit on the server.
+ ad_units = inventory_service.updateAdUnits(updated_ad_units)
+
+ # Display results.
+ for ad_unit in ad_units:
+ ad_unit_sizes = ['{%s x %s}' % (size['size']['width'],
+ size['size']['height'])
+ for size in ad_unit['adUnitSizes']]
+ print('Ad unit with ID "%s", name "%s", and sizes [%s] was updated'
+ % (ad_unit['id'], ad_unit['name'], ','.join(ad_unit_sizes)))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, AD_UNIT_ID)
diff --git a/examples/ad_manager/v202208/label_service/__init__.py b/examples/ad_manager/v202208/label_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202208/label_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202208/label_service/create_labels.py b/examples/ad_manager/v202208/label_service/create_labels.py
new file mode 100755
index 00000000..70135316
--- /dev/null
+++ b/examples/ad_manager/v202208/label_service/create_labels.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new labels.
+
+To determine which labels exist, run get_all_labels.py. This feature is only
+available to Ad Manager 360 solution networks.
+"""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ label_service = client.GetService('LabelService', version='v202208')
+
+ # Create label objects.
+ labels = []
+ for _ in range(5):
+ label = {
+ 'name': 'Label #%s' % uuid.uuid4(),
+ 'isActive': 'true',
+ 'types': ['COMPETITIVE_EXCLUSION']
+ }
+ labels.append(label)
+
+ # Add Labels.
+ labels = label_service.createLabels(labels)
+
+ # Display results.
+ for label in labels:
+ print('Label with id "%s", name "%s", and types {%s} was found.'
+ % (label['id'], label['name'], ','.join(label['types'])))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/label_service/deactivate_labels.py b/examples/ad_manager/v202208/label_service/deactivate_labels.py
new file mode 100755
index 00000000..e460c2a6
--- /dev/null
+++ b/examples/ad_manager/v202208/label_service/deactivate_labels.py
@@ -0,0 +1,65 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example deactivates all active Labels.
+
+To determine which labels exist, run get_all_labels.py. This feature is only
+available to Ad Manager 360 solution networks.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ label_service = client.GetService('LabelService', version='v202208')
+
+ # Create query.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('isActive = :isActive')
+ .WithBindVariable('isActive', True))
+
+ labels_deactivated = 0
+
+ # Get labels by statement.
+ while True:
+ response = label_service.getLabelsByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for label in response['results']:
+ print('Label with id "%s" and name "%s" will be '
+ 'deactivated.' % (label['id'], label['name']))
+ # Perform action.
+ result = label_service.performLabelAction(
+ {'xsi_type': 'DeactivateLabels'}, statement.ToStatement())
+ if result and int(result['numChanges']) > 0:
+ labels_deactivated += int(result['numChanges'])
+ statement.offset += statement.limit
+ else:
+ break
+
+ # Display results.
+ if labels_deactivated > 0:
+ print('Number of labels deactivated: %s' % labels_deactivated)
+ else:
+ print('No labels were deactivated.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/label_service/get_active_labels.py b/examples/ad_manager/v202208/label_service/get_active_labels.py
new file mode 100755
index 00000000..359ad418
--- /dev/null
+++ b/examples/ad_manager/v202208/label_service/get_active_labels.py
@@ -0,0 +1,50 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all active labels.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ label_service = client.GetService('LabelService', version='v202208')
+ # Create a statement to select labels.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('isActive = :isActive')
+ .WithBindVariable('isActive', True))
+
+ # Retrieve a small amount of labels at a time, paging
+ # through until all labels have been retrieved.
+ while True:
+ response = label_service.getLabelsByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for label in response['results']:
+ # Print out some information for each label.
+ print('Label with ID "%d" and name "%s" was found.\n' % (label['id'],
+ label['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/label_service/get_all_labels.py b/examples/ad_manager/v202208/label_service/get_all_labels.py
new file mode 100755
index 00000000..ff953e51
--- /dev/null
+++ b/examples/ad_manager/v202208/label_service/get_all_labels.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all labels.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ label_service = client.GetService('LabelService', version='v202208')
+
+ # Create a statement to select labels.
+ statement = ad_manager.StatementBuilder(version='v202208')
+
+ # Retrieve a small amount of labels at a time, paging
+ # through until all labels have been retrieved.
+ while True:
+ response = label_service.getLabelsByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for label in response['results']:
+ # Print out some information for each label.
+ print('Label with ID "%d" and name "%s" was found.\n' % (label['id'],
+ label['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/label_service/update_labels.py b/examples/ad_manager/v202208/label_service/update_labels.py
new file mode 100755
index 00000000..2a192fbb
--- /dev/null
+++ b/examples/ad_manager/v202208/label_service/update_labels.py
@@ -0,0 +1,63 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates the description of a single label.
+
+To determine which labels exist, run get_all_labels.py. This feature is only
+available to Ad Manager 360 solution networks.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+LABEL_ID = 'INSERT_LABEL_ID_HERE'
+
+
+def main(client, label_id):
+ # Initialize appropriate service.
+ label_service = client.GetService('LabelService', version='v202208')
+
+ # Create a statement to select only active labels.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('id = :labelId')
+ .WithBindVariable('labelId', int(label_id)))
+
+ # Get labels by filter.
+ response = label_service.getLabelsByStatement(statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ # Update each local label object by changing the description.
+ updated_labels = []
+ for label in response['results']:
+ label['description'] = 'These labels are updated.'
+ updated_labels.append(label)
+
+ # Update labels remotely.
+ labels = label_service.updateLabels(updated_labels)
+
+ for label in labels:
+ print('Label with id "%s" and name "%s" was updated.'
+ % (label['id'], label['name']))
+ else:
+ print('No labels found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, LABEL_ID)
+
diff --git a/examples/ad_manager/v202208/line_item_creative_association_service/__init__.py b/examples/ad_manager/v202208/line_item_creative_association_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202208/line_item_creative_association_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202208/line_item_creative_association_service/create_licas.py b/examples/ad_manager/v202208/line_item_creative_association_service/create_licas.py
new file mode 100755
index 00000000..cf715333
--- /dev/null
+++ b/examples/ad_manager/v202208/line_item_creative_association_service/create_licas.py
@@ -0,0 +1,57 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new line item creative associations (LICAs) for an
+existing line item and a set of creative ids.
+
+To determine which LICAs exist, run get_all_licas.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the line item ID and creative IDs to associate.
+LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
+CREATIVE_IDS = ['INSERT_CREATIVE_IDS_HERE']
+
+
+def main(client, line_item_id, creative_ids):
+ # Initialize appropriate service.
+ lica_service = client.GetService(
+ 'LineItemCreativeAssociationService', version='v202208')
+
+ licas = []
+ for creative_id in creative_ids:
+ licas.append({'creativeId': creative_id,
+ 'lineItemId': line_item_id})
+
+ # Create the LICAs remotely.
+ licas = lica_service.createLineItemCreativeAssociations(licas)
+
+ # Display results.
+ if licas:
+ for lica in licas:
+ print('LICA with line item id "%s", creative id "%s", and '
+ 'status "%s" was created.' %
+ (lica['lineItemId'], lica['creativeId'], lica['status']))
+ else:
+ print('No LICAs created.')
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, LINE_ITEM_ID, CREATIVE_IDS)
diff --git a/examples/ad_manager/v202208/line_item_creative_association_service/deactivate_licas.py b/examples/ad_manager/v202208/line_item_creative_association_service/deactivate_licas.py
new file mode 100755
index 00000000..397c981c
--- /dev/null
+++ b/examples/ad_manager/v202208/line_item_creative_association_service/deactivate_licas.py
@@ -0,0 +1,73 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example deactivates all LICAs for the line item.
+
+To determine which LICAs exist, run get_all_licas.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the id of the line item in which to deactivate LICAs.
+LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
+
+
+def main(client, line_item_id):
+ # Initialize appropriate service.
+ lica_service = client.GetService(
+ 'LineItemCreativeAssociationService', version='v202208')
+
+ # Create query.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('lineItemId = :lineItemId AND status = :status')
+ .WithBindVariable('status', 'ACTIVE')
+ .WithBindVariable('lineItemId', int(line_item_id)))
+
+ num_deactivated_licas = 0
+
+ # Get LICAs by statement.
+ while True:
+ response = lica_service.getLineItemCreativeAssociationsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for lica in response['results']:
+ print('LICA with line item id "%s", creative id "%s", and status'
+ ' "%s" will be deactivated.' %
+ (lica['lineItemId'], lica['creativeId'], lica['status']))
+
+ # Perform action.
+ result = lica_service.performLineItemCreativeAssociationAction(
+ {'xsi_type': 'DeactivateLineItemCreativeAssociations'},
+ statement.ToStatement())
+ if result and int(result['numChanges']) > 0:
+ num_deactivated_licas += int(result['numChanges'])
+ statement.offset += statement.limit
+ else:
+ break
+
+ # Display results.
+ if num_deactivated_licas > 0:
+ print('Number of LICAs deactivated: %s' % num_deactivated_licas)
+ else:
+ print('No LICAs were deactivated.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, LINE_ITEM_ID)
diff --git a/examples/ad_manager/v202208/line_item_creative_association_service/get_all_licas.py b/examples/ad_manager/v202208/line_item_creative_association_service/get_all_licas.py
new file mode 100755
index 00000000..919d0d1a
--- /dev/null
+++ b/examples/ad_manager/v202208/line_item_creative_association_service/get_all_licas.py
@@ -0,0 +1,57 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all line item creative associations.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ lica_service = client.GetService(
+ 'LineItemCreativeAssociationService', version='v202208')
+
+ # Create a statement to select line item creative associations.
+ statement = ad_manager.StatementBuilder(version='v202208')
+
+ # Retrieve a small amount of line item creative associations at a time, paging
+ # through until all line item creative associations have been retrieved.
+ while True:
+ response = lica_service.getLineItemCreativeAssociationsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for lica in response['results']:
+ # Print out some information for each line item creative association.
+ if 'creativeSetId' in lica:
+ print('LICA with line item ID "%s", creative set ID "%s", and '
+ 'status "%s" was found.' %
+ (lica['lineItemId'], lica['creativeSetId'], lica['status']))
+ else:
+ print('Line item creative association with line item ID "%d" and '
+ 'creative ID "%d" was found.\n' %
+ (lica['lineItemId'], lica['creativeId']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/line_item_creative_association_service/get_licas_for_line_item.py b/examples/ad_manager/v202208/line_item_creative_association_service/get_licas_for_line_item.py
new file mode 100755
index 00000000..86e1e5b2
--- /dev/null
+++ b/examples/ad_manager/v202208/line_item_creative_association_service/get_licas_for_line_item.py
@@ -0,0 +1,60 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all line item creative associations for a given line item.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
+
+
+def main(client, line_item_id):
+ # Initialize appropriate service.
+ lica_service = client.GetService(
+ 'LineItemCreativeAssociationService', version='v202208')
+ # Create a statement to select line item creative associations.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('lineItemId = :lineItemId')
+ .WithBindVariable('lineItemId', line_item_id))
+
+ # Retrieve a small amount of line item creative associations at a time, paging
+ # through until all line item creative associations have been retrieved.
+ while True:
+ response = lica_service.getLineItemCreativeAssociationsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for lica in response['results']:
+ # Print out some information for each line item creative association.
+ if 'creativeSetId' in lica:
+ print('LICA with line item ID "%s", creative set ID "%s", and '
+ 'status "%s" was found.' %
+ (lica['lineItemId'], lica['creativeSetId'], lica['status']))
+ else:
+ print('Line item creative association with line item ID "%d" and '
+ 'creative ID "%d" was found.\n' %
+ (lica['lineItemId'], lica['creativeId']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, LINE_ITEM_ID)
diff --git a/examples/ad_manager/v202208/line_item_creative_association_service/push_creative_to_devices.py b/examples/ad_manager/v202208/line_item_creative_association_service/push_creative_to_devices.py
new file mode 100755
index 00000000..eb646c82
--- /dev/null
+++ b/examples/ad_manager/v202208/line_item_creative_association_service/push_creative_to_devices.py
@@ -0,0 +1,61 @@
+#!/usr/bin/env python
+#
+# Copyright 2021, Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example pushes a LICA to a linked device for preview.
+
+To determine which linked devices exist, use the PublisherQueryLanguageService
+linked_device table.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the associated line item id and creative id to push, and set the linked
+# device id where it will be pushed.
+LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
+CREATIVE_ID = 'INSERT_CREATIVE_ID_HERE'
+LINKED_DEVICE_ID = 'INSERT_LINKED_DEVICE_ID_HERE'
+
+
+def main(client, line_item_id, creative_id, linked_device_id):
+ # Initialize appropriate service.
+ lica_service = client.GetService(
+ 'LineItemCreativeAssociationService', version='v202208')
+
+ # Create query to select a single linked device.
+ # Linked devices can be read from the linked_device PQL table.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('id = :linkedDeviceId')
+ .WithBindVariable('linkedDeviceId', int(linked_device_id)))
+
+ # Make call to push creatives to devices.
+ result = lica_service.pushCreativeToDevices(statement.ToStatement(), {
+ 'lineItemId': line_item_id,
+ 'creativeId': creative_id
+ })
+
+ # Display results.
+ if result and int(result['numChanges']) > 0:
+ print('Pushed creatives to %s devices.' % result['numChanges'])
+ else:
+ print('No creatives were pushed.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, LINE_ITEM_ID, CREATIVE_ID, LINKED_DEVICE_ID)
diff --git a/examples/ad_manager/v202208/line_item_creative_association_service/update_licas.py b/examples/ad_manager/v202208/line_item_creative_association_service/update_licas.py
new file mode 100755
index 00000000..44afbc9d
--- /dev/null
+++ b/examples/ad_manager/v202208/line_item_creative_association_service/update_licas.py
@@ -0,0 +1,66 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates the destination URL of all line item creative
+associations (LICA).
+
+To determine which LICAs exist, run get_all_licas.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ lica_service = client.GetService(
+ 'LineItemCreativeAssociationService', version='v202208')
+
+ # Create statement object to get all LICAs.
+ statement = ad_manager.StatementBuilder(version='v202208')
+
+ while True:
+ # Get LICAs by statement.
+ response = lica_service.getLineItemCreativeAssociationsByStatement(
+ statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ # Update each local LICA object by changing its destination URL.
+ updated_licas = []
+ for lica in response['results']:
+ lica['destinationUrl'] = 'http://news.google.com'
+ updated_licas.append(lica)
+
+ # Update LICAs remotely.
+ licas = lica_service.updateLineItemCreativeAssociations(updated_licas)
+
+ # Display results.
+ for lica in licas:
+ print('LICA with line item id "%s", creative id "%s", and status '
+ '"%s" was updated.' % (lica['lineItemId'], lica['creativeId'],
+ lica['status']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ if response['totalResultSetSize'] == 0:
+ print('No LICAs found to update.')
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/line_item_service/__init__.py b/examples/ad_manager/v202208/line_item_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202208/line_item_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202208/line_item_service/activate_line_items.py b/examples/ad_manager/v202208/line_item_service/activate_line_items.py
new file mode 100755
index 00000000..a9a34126
--- /dev/null
+++ b/examples/ad_manager/v202208/line_item_service/activate_line_items.py
@@ -0,0 +1,75 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example activates all line items for the given order.
+
+To be activated, line items need to be in the approved state and have at least
+one creative associated with them. To approve line items, approve the order to
+which they belong by running approve_orders.py. To create LICAs, run
+create_licas.py. To determine which line items exist, run
+get_all_line_items.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the id of the order to get line items from.
+ORDER_ID = 'INSERT_ORDER_ID_HERE'
+
+
+def main(client, order_id):
+ # Initialize appropriate service.
+ line_item_service = client.GetService('LineItemService', version='v202208')
+
+ # Create query.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('orderId = :orderId AND status = :status')
+ .WithBindVariable('status', 'NEEDS_CREATIVES')
+ .WithBindVariable('orderId', int(order_id)))
+
+ line_items_activated = 0
+
+ # Get line items by statement.
+ while True:
+ response = line_item_service.getLineItemsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for line_item in response['results']:
+ print('Line item with id "%s", belonging to order id "%s", and '
+ 'name "%s" will be activated.' %
+ (line_item['id'], line_item['orderId'], line_item['name']))
+
+ # Perform action.
+ result = line_item_service.performLineItemAction(
+ {'xsi_type': 'ActivateLineItems'}, statement.ToStatement())
+ if result and int(result['numChanges']) > 0:
+ line_items_activated += int(result['numChanges'])
+ statement.offset += statement.limit
+ else:
+ break
+
+ # Display results.
+ if line_items_activated > 0:
+ print('Number of line items activated: %s' % line_items_activated)
+ else:
+ print('No line items were activated.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ORDER_ID)
diff --git a/examples/ad_manager/v202208/line_item_service/create_line_items.py b/examples/ad_manager/v202208/line_item_service/create_line_items.py
new file mode 100755
index 00000000..722772e3
--- /dev/null
+++ b/examples/ad_manager/v202208/line_item_service/create_line_items.py
@@ -0,0 +1,165 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new line items.
+
+To determine which line items exist, run get_all_line_items.py. To determine
+which orders exist, run get_all_orders.py. To determine which placements exist,
+run get_all_placements.py.
+"""
+
+
+import datetime
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+import pytz
+
+# Set order that the created line item will belong to and add the id of a
+# placement containing ad units to target.
+ORDER_ID = 'INSERT_ORDER_ID_HERE'
+TARGETED_PLACEMENT_IDS = ['INSERT_PLACEMENT_IDS_HERE']
+
+
+def main(client, order_id, targeted_placement_ids):
+ # Initialize appropriate service.
+ line_item_service = client.GetService('LineItemService', version='v202208')
+
+ end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York'))
+ end_datetime += datetime.timedelta(days=365)
+
+ # Create line item objects.
+ line_items = []
+ for _ in range(5):
+ line_item = {
+ 'name': 'Line item #%s' % uuid.uuid4(),
+ 'orderId': order_id,
+ 'targeting': {
+ 'inventoryTargeting': {
+ 'targetedPlacementIds': targeted_placement_ids
+ },
+ 'geoTargeting': {
+ 'targetedLocations': [
+ {
+ 'id': '2840',
+ 'displayName': 'US'
+ },
+ {
+ 'id': '20133',
+ 'displayName': 'Geneva'
+ },
+ {
+ 'id': '9000093',
+ 'displayName': 'B3P',
+ }
+ ],
+ 'excludedLocations': [
+ {
+ 'id': '1016367',
+ 'displayName': 'Chicago',
+ },
+ {
+ 'id': '200501',
+ 'displayName': 'New York NY'
+ }
+ ]
+ },
+ 'dayPartTargeting': {
+ 'dayParts': [
+ {
+ 'dayOfWeek': 'SATURDAY',
+ 'startTime': {
+ 'hour': '0',
+ 'minute': 'ZERO'
+ },
+ 'endTime': {
+ 'hour': '24',
+ 'minute': 'ZERO'
+ }
+ },
+ {
+ 'dayOfWeek': 'SUNDAY',
+ 'startTime': {
+ 'hour': '0',
+ 'minute': 'ZERO'
+ },
+ 'endTime': {
+ 'hour': '24',
+ 'minute': 'ZERO'
+ }
+ }
+ ],
+ 'timeZone': 'BROWSER'
+ },
+ 'userDomainTargeting': {
+ 'domains': ['usa.gov'],
+ 'targeted': 'false'
+ },
+ 'technologyTargeting': {
+ 'browserTargeting': {
+ 'browsers': [{'id': '500072'}],
+ 'isTargeted': 'true'
+ }
+ }
+ },
+ 'creativePlaceholders': [
+ {
+ 'size': {
+ 'width': '300',
+ 'height': '250'
+ }
+ },
+ {
+ 'size': {
+ 'width': '120',
+ 'height': '600'
+ }
+ }
+ ],
+ 'startDateTimeType': 'IMMEDIATELY',
+ 'lineItemType': 'STANDARD',
+ 'endDateTime': end_datetime,
+ 'costType': 'CPM',
+ 'costPerUnit': {
+ 'currencyCode': 'USD',
+ 'microAmount': '2000000'
+ },
+ 'primaryGoal': {
+ 'units': '50',
+ 'unitType': 'IMPRESSIONS',
+ 'goalType': 'LIFETIME'
+ },
+ 'contractedUnitsBought': '100',
+ 'creativeRotationType': 'EVEN',
+ 'discountType': 'PERCENTAGE',
+ 'allowOverbook': 'true'
+ }
+ line_items.append(line_item)
+
+ # Add line items.
+ line_items = line_item_service.createLineItems(line_items)
+
+ # Display results.
+ for line_item in line_items:
+ print('Line item with id "%s", belonging to order id "%s", and named '
+ '"%s" was created.' % (line_item['id'], line_item['orderId'],
+ line_item['name']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ORDER_ID, TARGETED_PLACEMENT_IDS)
diff --git a/examples/ad_manager/v202208/line_item_service/create_video_line_item.py b/examples/ad_manager/v202208/line_item_service/create_video_line_item.py
new file mode 100755
index 00000000..ecca4d31
--- /dev/null
+++ b/examples/ad_manager/v202208/line_item_service/create_video_line_item.py
@@ -0,0 +1,135 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates a new line item to serve to video content.
+
+This feature is only available to Ad Manager 360 solution networks.
+"""
+
+import datetime
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+import pytz
+
+# Set order that all created line item will belong to and the video ad unit id
+# to target.
+ORDER_ID = 'INSERT_ORDER_ID_HERE'
+TARGETED_VIDEO_AD_UNIT_ID = 'INSERT_TARGETED_VIDEO_AD_UNIT_ID_HERE'
+
+# Set the video content to target.
+CONTENT_ID = 'INSERT_CONTENT_ID_HERE'
+# Set the video content bundle to target.
+CONTENT_BUNDLE_ID = 'INSERT_CONTENT_BUNDLE_ID_HERE'
+# Set the CMS metadata value to target.
+CMS_METADATA_VALUE_ID = 'INSERT_CMS_METADATA_VALUE_ID_HERE'
+
+
+def main(client, order_id, targeted_video_ad_unit_id, content_id,
+ content_bundle_id, cms_metadata_value_id):
+ # Initialize appropriate service.
+ line_item_service = client.GetService('LineItemService', version='v202208')
+
+ end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York'))
+ end_datetime += datetime.timedelta(days=365)
+
+ # Create line item object.
+ line_item = {
+ 'name': 'Line item #%s' % uuid.uuid4(),
+ 'orderId': order_id,
+ 'targeting': {
+ 'contentTargeting': {
+ 'targetedContentIds': [content_id],
+ 'targetedVideoContentBundleIds': [content_bundle_id]
+ },
+ 'customTargeting': {
+ 'logicalOperator': 'AND',
+ 'children': [{
+ 'xsi_type': 'CmsMetadataCriteria',
+ 'cmsMetadataValueIds': [cms_metadata_value_id],
+ 'operator': 'EQUALS'
+ }]
+ },
+ 'inventoryTargeting': {
+ 'targetedAdUnits': [{
+ 'adUnitId': targeted_video_ad_unit_id,
+ 'includeDescendants': 'true'
+ }]
+ },
+ 'requestPlatformTargeting': {
+ 'targetedRequestPlatforms': ['VIDEO_PLAYER']
+ },
+ 'videoPositionTargeting': {
+ 'targetedPositions': [{
+ 'videoPosition': {
+ 'positionType': 'PREROLL'
+ }
+ }]
+ }
+ },
+ 'creativePlaceholders': [{
+ 'size': {
+ 'width': '400',
+ 'height': '300'
+ },
+ 'companions': [{
+ 'size': {
+ 'width': '300',
+ 'height': '250'
+ },
+ }, {
+ 'size': {
+ 'width': '728',
+ 'height': '90'
+ },
+ }]
+ }],
+ 'environmentType': 'VIDEO_PLAYER',
+ 'companionDeliveryOption': 'OPTIONAL',
+ 'videoMaxDuration': 15000,
+ 'startDateTimeType': 'IMMEDIATELY',
+ 'lineItemType': 'SPONSORSHIP',
+ 'endDateTime': end_datetime,
+ 'costType': 'CPM',
+ 'costPerUnit': {
+ 'currencyCode': 'USD',
+ 'microAmount': '2000000'
+ },
+ 'primaryGoal': {
+ 'units': '50',
+ 'unitType': 'IMPRESSIONS',
+ 'goalType': 'DAILY'
+ },
+ 'contractedUnitsBought': '100',
+ 'creativeRotationType': 'OPTIMIZED',
+ 'discountType': 'PERCENTAGE',
+ 'allowOverbook': 'true'
+ }
+
+ # Add line item.
+ line_item = line_item_service.createLineItems([line_item])[0]
+
+ # Display results.
+ print('Video line item with id "%s", belonging to order id "%s", and '
+ 'named "%s" was created.' % (line_item['id'], line_item['orderId'],
+ line_item['name']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ORDER_ID, TARGETED_VIDEO_AD_UNIT_ID, CONTENT_ID,
+ CONTENT_BUNDLE_ID, CMS_METADATA_VALUE_ID)
diff --git a/examples/ad_manager/v202208/line_item_service/get_all_line_items.py b/examples/ad_manager/v202208/line_item_service/get_all_line_items.py
new file mode 100755
index 00000000..3e96a6eb
--- /dev/null
+++ b/examples/ad_manager/v202208/line_item_service/get_all_line_items.py
@@ -0,0 +1,50 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all line items.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ line_item_service = client.GetService('LineItemService', version='v202208')
+
+ # Create a statement to select line items.
+ statement = ad_manager.StatementBuilder(version='v202208')
+
+ # Retrieve a small amount of line items at a time, paging
+ # through until all line items have been retrieved.
+ while True:
+ response = line_item_service.getLineItemsByStatement(statement.ToStatement(
+ ))
+ if 'results' in response and len(response['results']):
+ for line_item in response['results']:
+ # Print out some information for each line item.
+ print('Line item with ID "%d" and name "%s" was found.\n' %
+ (line_item['id'], line_item['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/line_item_service/get_line_items_that_need_creatives.py b/examples/ad_manager/v202208/line_item_service/get_line_items_that_need_creatives.py
new file mode 100755
index 00000000..14ee9e9f
--- /dev/null
+++ b/examples/ad_manager/v202208/line_item_service/get_line_items_that_need_creatives.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all line items that are missing creatives.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ line_item_service = client.GetService('LineItemService', version='v202208')
+ # Create a statement to select line items.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('isMissingCreatives = :isMissingCreatives')
+ .WithBindVariable('isMissingCreatives', True))
+
+ # Retrieve a small amount of line items at a time, paging
+ # through until all line items have been retrieved.
+ while True:
+ response = line_item_service.getLineItemsByStatement(statement.ToStatement(
+ ))
+ if 'results' in response and len(response['results']):
+ for line_item in response['results']:
+ # Print out some information for each line item.
+ print('Line item with ID "%d" and name "%s" was found.\n' %
+ (line_item['id'], line_item['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/line_item_service/get_recently_updated_line_items.py b/examples/ad_manager/v202208/line_item_service/get_recently_updated_line_items.py
new file mode 100755
index 00000000..882f0c56
--- /dev/null
+++ b/examples/ad_manager/v202208/line_item_service/get_recently_updated_line_items.py
@@ -0,0 +1,59 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets only recently updated line items.
+"""
+
+# Import appropriate modules from the client library.
+from datetime import datetime
+from datetime import timedelta
+
+from googleads import ad_manager
+import pytz
+
+
+def main(client):
+ # Initialize appropriate service.
+ line_item_service = client.GetService('LineItemService', version='v202208')
+
+ last_modified = (datetime.now(tz=pytz.timezone('America/New_York'))
+ - timedelta(days=1))
+
+ # Create a statement to select line items.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('lastModifiedDateTime >= :lastModifiedDateTime')
+ .WithBindVariable('lastModifiedDateTime', last_modified))
+
+ # Retrieve a small amount of line items at a time, paging
+ # through until all line items have been retrieved.
+ while True:
+ response = line_item_service.getLineItemsByStatement(statement.ToStatement(
+ ))
+ if 'results' in response and len(response['results']):
+ for line_item in response['results']:
+ # Print out some information for each line item.
+ print('Line item with ID "%d" and name "%s" was found.\n' %
+ (line_item['id'], line_item['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/line_item_service/pause_line_items.py b/examples/ad_manager/v202208/line_item_service/pause_line_items.py
new file mode 100755
index 00000000..15229319
--- /dev/null
+++ b/examples/ad_manager/v202208/line_item_service/pause_line_items.py
@@ -0,0 +1,74 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example pauses a line item.
+
+Line items must be paused before they can be updated. To determine which line
+items exist, run get_all_line_items.py
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the ID of the line item to pause.
+LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
+
+
+def main(client):
+ # Initialize appropriate service.
+ line_item_service = client.GetService('LineItemService', version='v202208')
+
+ # Create a statement to select the line item.
+ # Change this to operate on more than one Line Item.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('id = :id')
+ .OrderBy('id', ascending=True)
+ .WithBindVariable('id', LINE_ITEM_ID))
+
+ result_set_size = 0
+ should_continue = True
+
+ # Iterate over paged results from the statement.
+ while should_continue:
+ page = line_item_service.getLineItemsByStatement(statement.ToStatement())
+ if 'results' in page and len(page['results']):
+ result_set_size = page['totalResultSetSize']
+ # Iterate over individual results in the page.
+ for line_item in page['results']:
+ print('Pausing line item with ID %d' % line_item['id'])
+ # Update statement for next page.
+ statement.offset += statement.limit
+ should_continue = statement.offset < result_set_size
+
+ print('Pausing %d line item(s)' % result_set_size)
+
+ if result_set_size > 0:
+ statement.offset = None
+ statement.limit = None
+
+ # Perform Pause action on all Line Items that match the statement.
+ update_result = line_item_service.performLineItemAction(
+ {'xsi_type': 'PauseLineItems'}, statement.ToStatement())
+
+ if update_result and update_result['numChanges'] > 0:
+ print('Updated %d line item(s)' % update_result['numChanges'])
+ else:
+ print('No line items were paused')
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/line_item_service/target_custom_criteria.py b/examples/ad_manager/v202208/line_item_service/target_custom_criteria.py
new file mode 100755
index 00000000..112e0845
--- /dev/null
+++ b/examples/ad_manager/v202208/line_item_service/target_custom_criteria.py
@@ -0,0 +1,110 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example updates a line item to add custom criteria targeting.
+
+To determine which line items exist, run get_all_line_items.py. To determine
+which custom targeting keys and values exist, run
+get_all_custom_targeting_keys_and_values.py.
+"""
+
+
+import pprint
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
+KEY_ID1 = 'INSERT_TARGETING_KEY_ID_HERE'
+KEY_ID2 = 'INSERT_TARGETING_KEY_ID_HERE'
+KEY_ID3 = 'INSERT_TARGETING_KEY_ID_HERE'
+
+VALUE_ID1 = 'INSERT_TARGETING_VALUE_ID_HERE'
+VALUE_ID2 = 'INSERT_TARGETING_VALUE_ID_HERE'
+VALUE_ID3 = 'INSERT_TARGETING_VALUE_ID_HERE'
+
+
+def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2,
+ value_id3):
+ # Initialize appropriate service.
+ line_item_service = client.GetService('LineItemService', version='v202208')
+
+ # create custom criterias
+ custom_criteria1 = {
+ 'xsi_type': 'CustomCriteria',
+ 'keyId': key_id1,
+ 'valueIds': [value_id1],
+ 'operator': 'IS'
+ }
+
+ custom_criteria2 = {
+ 'xsi_type': 'CustomCriteria',
+ 'keyId': key_id2,
+ 'valueIds': [value_id2],
+ 'operator': 'IS_NOT'
+ }
+
+ custom_criteria3 = {
+ 'xsi_type': 'CustomCriteria',
+ 'keyId': key_id3,
+ 'valueIds': [value_id3],
+ 'operator': 'IS'
+ }
+
+ # Create the custom criteria set that will resemble:
+ # (custom_criteria1.key == custom_criteria1.value OR
+ # (custom_criteria2.key != custom_criteria2.value AND
+ # custom_criteria13.key == custom_criteria3.value))
+ sub_set = {
+ 'xsi_type': 'CustomCriteriaSet',
+ 'logicalOperator': 'AND',
+ 'children': [custom_criteria2, custom_criteria3]
+ }
+
+ top_set = {
+ 'xsi_type': 'CustomCriteriaSet',
+ 'logicalOperator': 'OR',
+ 'children': [custom_criteria1, sub_set]
+ }
+
+ # Create statement to get the line item
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('id = :lineItemId')
+ .WithBindVariable('lineItemId', int(line_item_id))
+ .Limit(1))
+
+ # Set custom criteria targeting on the line item.
+ line_item = line_item_service.getLineItemsByStatement(
+ statement.ToStatement())['results'][0]
+ line_item['targeting']['customTargeting'] = top_set
+
+ # Update line item.
+ line_item = line_item_service.updateLineItems([line_item])[0]
+
+ # Display results.
+ if line_item:
+ print('Line item with id "%s" updated with custom criteria targeting:'
+ % line_item['id'])
+ pprint.pprint(line_item['targeting']['customTargeting'])
+ else:
+ print('No line items were updated.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, LINE_ITEM_ID, KEY_ID1, KEY_ID2, KEY_ID3, VALUE_ID1,
+ VALUE_ID2, VALUE_ID3)
diff --git a/examples/ad_manager/v202208/line_item_service/update_line_items.py b/examples/ad_manager/v202208/line_item_service/update_line_items.py
new file mode 100755
index 00000000..a093452b
--- /dev/null
+++ b/examples/ad_manager/v202208/line_item_service/update_line_items.py
@@ -0,0 +1,74 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates the delivery rate of all line items in an order.
+
+To determine which line items exist, run get_all_line_items.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set id of the order to get line items from.
+ORDER_ID = 'INSERT_ORDER_ID_HERE'
+
+
+def main(client, order_id):
+ # Initialize appropriate service.
+ line_item_service = client.GetService('LineItemService', version='v202208')
+
+ # Create statement object to only select line items with even delivery rates.
+
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where(('deliveryRateType = :deliveryRateType AND '
+ 'orderId = :orderId'))
+ .WithBindVariable('orderId', int(order_id))
+ .WithBindVariable('deliveryRateType', 'EVENLY')
+ .Limit(500))
+
+ # Get line items by statement.
+ response = line_item_service.getLineItemsByStatement(
+ statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ # Update each local line item by changing its delivery rate type.
+ updated_line_items = []
+ for line_item in response['results']:
+ if not line_item['isArchived']:
+ line_item['deliveryRateType'] = 'AS_FAST_AS_POSSIBLE'
+ updated_line_items.append(line_item)
+
+ # Update line items remotely.
+ line_items = line_item_service.updateLineItems(updated_line_items)
+
+ # Display results.
+ if line_items:
+ for line_item in line_items:
+ print('Line item with id "%s", belonging to order id "%s", named '
+ '"%s", and delivery rate "%s" was updated.'
+ % (line_item['id'], line_item['orderId'], line_item['name'],
+ line_item['deliveryRateType']))
+ else:
+ print('No line items were updated.')
+ else:
+ print('No line items found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ORDER_ID)
diff --git a/examples/ad_manager/v202208/live_stream_event_service/activate_live_stream_events.py b/examples/ad_manager/v202208/live_stream_event_service/activate_live_stream_events.py
new file mode 100755
index 00000000..c124aa52
--- /dev/null
+++ b/examples/ad_manager/v202208/live_stream_event_service/activate_live_stream_events.py
@@ -0,0 +1,71 @@
+#!/usr/bin/env python
+#
+# Copyright 2018 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example activates paused live stream events."""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the id of the LiveStreamEvent to get live stream events from.
+LIVE_STREAM_EVENT_ID = 'INSERT_LIVE_STREAM_EVENT_ID_HERE'
+
+
+def main(client, live_stream_event_id):
+ # Initialize appropriate service.
+ live_stream_event_service = client.GetService(
+ 'LiveStreamEventService', version='v202208')
+
+ # Create query to find paused live stream events.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where(('id = :id AND '
+ 'status = :status'))
+ .WithBindVariable('status', 'PAUSED')
+ .WithBindVariable('id', int(live_stream_event_id))
+ .Limit(500))
+
+ live_stream_events_activated = 0
+
+ # Get live stream events by statement.
+ while True:
+ response = live_stream_event_service.getLiveStreamEventsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for live_stream_event in response['results']:
+ print('live stream event with id "%s" and name "%s" will be activated.'
+ % (live_stream_event['id'], live_stream_event['name']))
+
+ # Perform action.
+ result = live_stream_event_service.performLiveStreamEventAction({
+ 'xsi_type': 'ActivateLiveStreamEvents'
+ }, statement.ToStatement())
+ if result and int(result['numChanges']) > 0:
+ live_stream_events_activated += int(result['numChanges'])
+ statement.offset += ad_manager.SUGGESTED_PAGE_LIMIT
+ else:
+ break
+
+ # Display results.
+ if live_stream_events_activated > 0:
+ print('# of live stream events activated: %s' % (
+ live_stream_events_activated))
+ else:
+ print('No live stream events were activated.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, LIVE_STREAM_EVENT_ID)
diff --git a/examples/ad_manager/v202208/live_stream_event_service/create_live_stream_events.py b/examples/ad_manager/v202208/live_stream_event_service/create_live_stream_events.py
new file mode 100755
index 00000000..d4d2f081
--- /dev/null
+++ b/examples/ad_manager/v202208/live_stream_event_service/create_live_stream_events.py
@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+#
+# Copyright 2018 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new live stream events.
+
+To determine which live stream events exist, run get_all_live_stream_events.py.
+To determine which cdn configurations exist, run get_cdn_configurations.py.
+"""
+
+import datetime
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+import pytz
+
+# Set content urls and adTags to use
+CONTENT_URLS = ['INSERT_CONTENT_URLS_HERE']
+AD_TAGS = ['INSERT_AD_TAGS_HERE']
+
+
+def main(client, content_urls, ad_tags):
+ # Initialize appropriate services.
+ live_events_service = client.GetService(
+ 'LiveStreamEventService', version='v202208')
+
+ # Stream will play for 365 days
+ start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York'))
+ end_datetime = start_datetime + datetime.timedelta(days=365)
+
+ # Create live stream event objects
+ live_stream_events = [{
+ 'name': 'Live Stream Event #%s' % uuid.uuid4(),
+ 'startDateTime': start_datetime,
+ 'endDateTime': end_datetime,
+ 'contentUrls': content_urls,
+ 'adTags': ad_tags
+ }]
+
+ # Add live stream events.
+ live_stream_events = live_events_service.createLiveStreamEvents(
+ live_stream_events)
+
+ # Display results.
+ for live_stream_event in live_stream_events:
+ print(
+ 'Live stream event with id "%s", named "%s" and status %s was created.'
+ % (live_stream_event['id'], live_stream_event['name'],
+ live_stream_event['status']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CONTENT_URLS, AD_TAGS)
diff --git a/examples/ad_manager/v202208/live_stream_event_service/get_all_live_stream_events.py b/examples/ad_manager/v202208/live_stream_event_service/get_all_live_stream_events.py
new file mode 100755
index 00000000..5d514bad
--- /dev/null
+++ b/examples/ad_manager/v202208/live_stream_event_service/get_all_live_stream_events.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2018 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all live stream events.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ live_stream_event_service = client.GetService(
+ 'LiveStreamEventService', version='v202208')
+
+ # Create a statement to select live stream events.
+ statement = ad_manager.StatementBuilder(version='v202208')
+
+ # Retrieve a small amount of live stream events at a time, paging
+ # through until all live stream events have been retrieved.
+ while True:
+ response = live_stream_event_service.getLiveStreamEventsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for live_stream_event in response['results']:
+ # Print out some information for each live stream event.
+ print('live stream event with id "%d" and name "%s" was found.' %
+ (live_stream_event['id'], live_stream_event['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/live_stream_event_service/register_sessions_for_monitoring.py b/examples/ad_manager/v202208/live_stream_event_service/register_sessions_for_monitoring.py
new file mode 100755
index 00000000..d7a92251
--- /dev/null
+++ b/examples/ad_manager/v202208/live_stream_event_service/register_sessions_for_monitoring.py
@@ -0,0 +1,45 @@
+#!/usr/bin/env python
+#
+# Copyright 2018 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example registers all live stream event-sessions ids for monitoring."""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# List of session ids
+SESSION_IDS = ['INSERT_SESSION_IDS_HERE']
+
+
+def main(client, session_ids):
+ # Initialize appropriate service.
+ live_stream_event_service = client.GetService(
+ 'LiveStreamEventService', version='v202208')
+
+ # Retrieve all sessions id that are being monitored
+ session_ids = live_stream_event_service.registerSessionsForMonitoring(
+ session_ids)
+ if session_ids:
+ for session_id in session_ids:
+ # Print out some information for each live stream event.
+ print('Session with ID "%s" registered for monitoring.' % (session_id))
+
+ print('\nNumber of results found: %s' % session_ids.size)
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, SESSION_IDS)
diff --git a/examples/ad_manager/v202208/live_stream_event_service/update_live_stream_events.py b/examples/ad_manager/v202208/live_stream_event_service/update_live_stream_events.py
new file mode 100755
index 00000000..3642457d
--- /dev/null
+++ b/examples/ad_manager/v202208/live_stream_event_service/update_live_stream_events.py
@@ -0,0 +1,69 @@
+#!/usr/bin/env python
+#
+# Copyright 2018 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates live stream events.
+
+To determine which live stream events exist, run get_all_live_stream_events.py.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set ID of the LiveStreamEvent to get live stream events from.
+LIVE_STREAM_EVENT_ID = 'INSERT_LIVE_STREAM_EVENT_ID_HERE'
+
+
+def main(client, live_stream_event_id):
+ # Initialize appropriate services.
+ live_stream_events_service = client.GetService(
+ 'LiveStreamEventService', version='v202208')
+
+ # Create statement object to only select matching live stream event.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where(('Id = :id'))
+ .WithBindVariable('id', int(live_stream_event_id))
+ .Limit(500))
+
+ # Get live stream events by statement.
+ response = live_stream_events_service.getLiveStreamEventsByStatement(
+ statement.ToStatement())
+
+ # Set adTags to be updated.
+ new_ad_tags = ['INSERT_NEW_AD_TAGS_HERE']
+
+ if 'results' in response and len(response['results']):
+ # Update each local live stream event by changing its attributes.
+ updated_live_stream_events = []
+ for live_stream_event in response['results']:
+ live_stream_event['startDateTimeType'] = 'IMMEDIATELY'
+ live_stream_event['adTags'] = new_ad_tags
+ updated_live_stream_events.append(live_stream_event)
+
+ # Update live stream events.
+ live_stream_events = live_stream_events_service.updateLiveStreamEvents(
+ updated_live_stream_events)
+
+ # Display results.
+ for live_stream_event in live_stream_events:
+ print('Live stream event with id "%s", named "%s" and status %s was '
+ 'updated.' % (live_stream_event['id'], live_stream_event['name'],
+ live_stream_event['status']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, LIVE_STREAM_EVENT_ID)
diff --git a/examples/ad_manager/v202208/native_style_service/__init__.py b/examples/ad_manager/v202208/native_style_service/__init__.py
new file mode 100755
index 00000000..473ddba1
--- /dev/null
+++ b/examples/ad_manager/v202208/native_style_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202208/native_style_service/create_native_styles.py b/examples/ad_manager/v202208/native_style_service/create_native_styles.py
new file mode 100755
index 00000000..793f14f5
--- /dev/null
+++ b/examples/ad_manager/v202208/native_style_service/create_native_styles.py
@@ -0,0 +1,178 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Creates a native app install ad."""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+# This is the creative template ID for the system-defined native app install ad
+# format, which we will create the native style from. Use
+# CreativeTemplateService.getCreativeTemplateByStatement() and
+# CreativeTemplate.isNativeEligible() to get other native ad formats available
+# in your network.
+CREATIVE_TEMPLATE_ID = 10004400
+WIDTH = 300
+HEIGHT = 345
+
+HTML_SNIPPET = """
+"""
+
+CSS_SNIPPET = """body {
+ background-color: rgba(255, 255, 255, 1);
+ font-family: "Roboto-Regular", sans-serif;
+ font-weight: normal;
+ font-size: 12px;
+ line-height: 14px;
+}
+.attribution {
+ background-color: rgba(236, 182, 0, 1);
+ color: rgba(255, 255, 255, 1);
+ font-size: 13px;
+ display: table;
+ margin: 4px 8px;
+ padding: 0 3px;
+ border-radius: 2px;
+}
+.image {
+ text-align: center;
+ margin: 8px;
+}
+.image img,
+.image-link {
+ width: 100%;
+}
+.app-icon {
+ float: left;
+ margin: 0 8px 4px 8px;
+ height: 40px;
+ width: 40px;
+ background-color: transparent;
+}
+.app-icon img {
+ height: 100%;
+ width: 100%;
+ border-radius: 20%;
+}
+.title {
+ font-weight: bold;
+ font-size: 14px;
+ line-height: 20px;
+ margin: 8px 8px 4px 8px;
+}
+.title a {
+ color: rgba(112, 112, 112, 1);
+ text-decoration: none;
+}
+.reviews {
+ float: left;
+}
+.reviews svg {
+ fill: rgba(0, 0, 0, 0.7);
+}
+.body {
+ clear: left;
+ margin: 8px;
+}
+.body a {
+ color: rgba(110, 110, 110, 1);
+ text-decoration: none;
+}
+.price {
+ display: none;
+}
+.button {
+ font-size: 14px;
+ font-weight: bold;
+ float: right;
+ margin: 0px 16px 16px 0px;
+ white-space: nowrap;
+}
+.button a {
+ color: #2196F3;
+ text-decoration: none;
+}
+.button svg {
+ display: none;
+}
+"""
+
+
+def main(client, html_snippet, css_snippet, creative_template_id, width,
+ height):
+ # Initialize appropriate service.
+ native_style_service = client.GetService('NativeStyleService',
+ version='v202208')
+
+ native_style = {
+ 'name': 'Native style #%d' % uuid.uuid4(),
+ 'htmlSnippet': html_snippet,
+ 'cssSnippet': css_snippet,
+ 'creativeTemplateId': creative_template_id,
+ 'size': {
+ 'width': width,
+ 'height': height,
+ 'isAspectRatio': False
+ }
+ }
+
+ # Create the native style on the server.
+ native_styles = native_style_service.createNativeStyles([native_style])
+
+ # Display results.
+ for native_style in native_styles:
+ print('A Native style with ID "%s", name "%s", and creative template ID'
+ '"%d" was created.' % (native_style['id'], native_style['name'],
+ native_style['creativeTemplateId']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, HTML_SNIPPET, CSS_SNIPPET, CREATIVE_TEMPLATE_ID,
+ WIDTH, HEIGHT)
diff --git a/examples/ad_manager/v202208/native_style_service/get_all_native_styles.py b/examples/ad_manager/v202208/native_style_service/get_all_native_styles.py
new file mode 100755
index 00000000..f49fa8da
--- /dev/null
+++ b/examples/ad_manager/v202208/native_style_service/get_all_native_styles.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all native styles."""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ native_style_service = client.GetService('NativeStyleService',
+ version='v202208')
+
+ # Create a statement to select native styles.
+ statement = ad_manager.StatementBuilder(version='v202208')
+
+ # Retrieve a small amount of native styles at a time, paging
+ # through until all native styles have been retrieved.
+ while True:
+ response = native_style_service.getNativeStylesByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for native_style in response['results']:
+ # Print out some information for each native style.
+ print('Native style with ID "%d" and name "%s" was found.\n' %
+ (native_style['id'], native_style['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/network_service/__init__.py b/examples/ad_manager/v202208/network_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202208/network_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202208/network_service/get_all_networks.py b/examples/ad_manager/v202208/network_service/get_all_networks.py
new file mode 100755
index 00000000..4691fc06
--- /dev/null
+++ b/examples/ad_manager/v202208/network_service/get_all_networks.py
@@ -0,0 +1,40 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all networks.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ network_service = client.GetService('NetworkService', version='v202208')
+
+ networks = network_service.getAllNetworks()
+
+ # Print out some information for each network.
+ for network in networks:
+ print('Network with network code "%s" and display name "%s" was found.'
+ % (network['networkCode'], network['displayName']))
+
+ print('\nNumber of results found: %s' % len(networks))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/network_service/get_current_network.py b/examples/ad_manager/v202208/network_service/get_current_network.py
new file mode 100755
index 00000000..03346f28
--- /dev/null
+++ b/examples/ad_manager/v202208/network_service/get_current_network.py
@@ -0,0 +1,37 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets the current network."""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ network_service = client.GetService('NetworkService', version='v202208')
+
+ current_network = network_service.getCurrentNetwork()
+
+ print("Current network has network code '%s' and display name '%s'." %
+ (current_network['networkCode'], current_network['displayName']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/network_service/get_default_third_party_data_declaration.py b/examples/ad_manager/v202208/network_service/get_default_third_party_data_declaration.py
new file mode 100755
index 00000000..997a4c55
--- /dev/null
+++ b/examples/ad_manager/v202208/network_service/get_default_third_party_data_declaration.py
@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+#
+# Copyright 2020, Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets the network's default third party data declarations."""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate services.
+ network_service = client.GetService('NetworkService', version='v202208')
+ pql_service = client.GetService('PublisherQueryLanguageService',
+ version='v202208')
+
+ # Fetch the default third party data declarations.
+ declarations = network_service.getDefaultThirdPartyDataDeclaration()
+
+ # Display the results.
+ if declarations is None:
+ print('No default ad technology partners have been set on this network.')
+ elif (declarations['declarationType'] == 'NONE' or
+ not declarations['thirdPartyCompanyIds']):
+ print('This network has specified that there are no ad technology providers'
+ ' associated with its reservation creatives by default.')
+ else:
+ print('This network has specified %d ad technology provider(s) associated'
+ ' with its reservation creatives by default:' %
+ len(declarations['thirdPartyCompanyIds']))
+
+ # In this case, there are third party companies to be displayed, so fetch
+ # the company names from the Rich_Media_Ad_Company PQL table.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Select('Id, Name')
+ .From('Rich_Media_Ad_Company')
+ .Where('Id IN (:company_ids)')
+ .WithBindVariable('company_ids',
+ declarations['thirdPartyCompanyIds']))
+
+ while True:
+ response = pql_service.select(statement.ToStatement())
+ if 'rows' in response and len(response['rows']):
+ for company in response['rows']:
+ print('Name: %s, id: %s' % (company['values'][1]['value'],
+ company['values'][0]['value']))
+ statement.offset += statement.limit
+ else:
+ break
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/network_service/make_test_network.py b/examples/ad_manager/v202208/network_service/make_test_network.py
new file mode 100755
index 00000000..ef44fb51
--- /dev/null
+++ b/examples/ad_manager/v202208/network_service/make_test_network.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example creates a test network.
+
+You do not need to have an Ad Manager account to run this example, but you do
+need to have a Google account (created at
+http://www.google.com/accounts/newaccount if you currently don't have one) that
+is not associated with any other Ad Manager test networks. Once this network is
+created, you can supply the network code in your settings to make calls to
+other services.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ network_service = client.GetService('NetworkService', version='v202208')
+
+ # Create a test network.
+ network = network_service.makeTestNetwork()
+
+ # Display results.
+ print('Test network with network code "%s" and display name "%s" '
+ 'created.' % (network['networkCode'], network['displayName']))
+ print('You may now sign in at '
+ 'http://www.google.com/admanager/main?networkCode=%s'
+ % network['networkCode'])
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/order_service/__init__.py b/examples/ad_manager/v202208/order_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202208/order_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202208/order_service/approve_orders.py b/examples/ad_manager/v202208/order_service/approve_orders.py
new file mode 100755
index 00000000..65d86cc4
--- /dev/null
+++ b/examples/ad_manager/v202208/order_service/approve_orders.py
@@ -0,0 +1,67 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example approves all eligible draft and pending orders.
+
+To determine which orders exist, run get_all_orders.py.
+"""
+
+
+import datetime
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ order_service = client.GetService('OrderService', version='v202208')
+
+ # Create a filter statement.
+ today = datetime.date.today()
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where(('status in (\'DRAFT\', \'PENDING_APPROVAL\') '
+ 'AND endDateTime >= :today AND isArchived = FALSE'))
+ .WithBindVariable('today', today))
+ orders_approved = 0
+
+ # Get orders by statement.
+ while True:
+ response = order_service.getOrdersByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ # Display results.
+ for order in response['results']:
+ print('Order with id "%s", name "%s", and status "%s" will be '
+ 'approved.' % (order['id'], order['name'], order['status']))
+ # Perform action.
+ result = order_service.performOrderAction(
+ {'xsi_type': 'ApproveOrders'}, statement.ToStatement())
+ if result and int(result['numChanges']) > 0:
+ orders_approved += int(result['numChanges'])
+ statement.offset += statement.limit
+ else:
+ break
+
+ # Display results.
+ if orders_approved > 0:
+ print('Number of orders approved: %s' % orders_approved)
+ else:
+ print('No orders were approved.')
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/order_service/create_orders.py b/examples/ad_manager/v202208/order_service/create_orders.py
new file mode 100755
index 00000000..91f5f874
--- /dev/null
+++ b/examples/ad_manager/v202208/order_service/create_orders.py
@@ -0,0 +1,59 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new orders.
+
+To determine which orders exist, run get_all_orders.py.
+"""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
+SALESPERSON_ID = 'INSERT_SALESPERSON_ID_HERE'
+TRAFFICKER_ID = 'INSERT_TRAFFICKER_ID_HERE'
+
+
+def main(client, company_id, salesperson_id, trafficker_id):
+ # Initialize appropriate service.
+ order_service = client.GetService('OrderService', version='v202208')
+
+ # Create order objects.
+ orders = []
+ for _ in range(5):
+ order = {
+ 'name': 'Order #%s' % uuid.uuid4(),
+ 'advertiserId': company_id,
+ 'salespersonId': salesperson_id,
+ 'traffickerId': trafficker_id
+ }
+ orders.append(order)
+
+ # Add orders.
+ orders = order_service.createOrders(orders)
+
+ # Display results.
+ for order in orders:
+ print('Order with id "%s" and name "%s" was created.'
+ % (order['id'], order['name']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, COMPANY_ID, SALESPERSON_ID, TRAFFICKER_ID)
diff --git a/examples/ad_manager/v202208/order_service/get_all_orders.py b/examples/ad_manager/v202208/order_service/get_all_orders.py
new file mode 100755
index 00000000..ab1e61d2
--- /dev/null
+++ b/examples/ad_manager/v202208/order_service/get_all_orders.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all orders.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ order_service = client.GetService('OrderService', version='v202208')
+
+ # Create a statement to select orders.
+ statement = ad_manager.StatementBuilder(version='v202208')
+
+ # Retrieve a small amount of orders at a time, paging
+ # through until all orders have been retrieved.
+ while True:
+ response = order_service.getOrdersByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for order in response['results']:
+ # Print out some information for each order.
+ print('Order with ID "%d" and name "%s" was found.\n' % (order['id'],
+ order['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/order_service/get_orders_starting_soon.py b/examples/ad_manager/v202208/order_service/get_orders_starting_soon.py
new file mode 100755
index 00000000..2341f672
--- /dev/null
+++ b/examples/ad_manager/v202208/order_service/get_orders_starting_soon.py
@@ -0,0 +1,60 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all orders that are starting soon.
+"""
+
+# Import appropriate modules from the client library.
+from datetime import datetime
+from datetime import timedelta
+
+from googleads import ad_manager
+import pytz
+
+
+def main(client):
+ # Initialize appropriate service.
+ order_service = client.GetService('OrderService', version='v202208')
+ now = datetime.now(tz=pytz.timezone('America/New_York'))
+ soon = now + timedelta(days=5)
+
+ # Create a statement to select orders.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where(('status = :status AND startDateTime >= :now '
+ 'AND startDateTime <= :soon'))
+ .WithBindVariable('status', 'APPROVED')
+ .WithBindVariable('now', now)
+ .WithBindVariable('soon', soon))
+
+ # Retrieve a small amount of orders at a time, paging
+ # through until all orders have been retrieved.
+ while True:
+ response = order_service.getOrdersByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for order in response['results']:
+ # Print out some information for each order.
+ print('Order with ID "%d" and name "%s" was found.\n' % (order['id'],
+ order['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/order_service/update_orders.py b/examples/ad_manager/v202208/order_service/update_orders.py
new file mode 100755
index 00000000..267979c9
--- /dev/null
+++ b/examples/ad_manager/v202208/order_service/update_orders.py
@@ -0,0 +1,71 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates the notes of a single order specified by ID.
+
+To determine which orders exist, run get_all_orders.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+ORDER_ID = 'INSERT_ORDER_ID_HERE'
+
+
+def main(client, order_id):
+ # Initialize appropriate service.
+ order_service = client.GetService('OrderService', version='v202208')
+
+ # Create statement object to select a single order by an ID.
+
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('id = :orderId')
+ .WithBindVariable('orderId', int(order_id)))
+
+ # Get orders by statement.
+ response = order_service.getOrdersByStatement(statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ # Update each local order object by changing its notes.
+ updated_orders = []
+ for order in response['results']:
+ # Archived orders cannot be updated.
+ if not order['isArchived']:
+ order['notes'] = 'Spoke to advertiser. All is well.'
+ updated_orders.append(order)
+
+ # Update orders remotely.
+ orders = order_service.updateOrders(updated_orders)
+
+ # Display results.
+ if orders:
+ for order in orders:
+ print('Order with id "%s", name "%s", advertiser id "%s", and '
+ 'notes "%s" was updated.'
+ % (order['id'], order['name'], order['advertiserId'],
+ order['notes']))
+ else:
+ print('No orders were updated.')
+ else:
+ print('No orders found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ORDER_ID)
+
diff --git a/examples/ad_manager/v202208/placement_service/create_placements.py b/examples/ad_manager/v202208/placement_service/create_placements.py
new file mode 100755
index 00000000..d46b84f7
--- /dev/null
+++ b/examples/ad_manager/v202208/placement_service/create_placements.py
@@ -0,0 +1,108 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new placements for various ad unit sizes.
+
+To determine which placements exist, run get_all_placements.py.
+"""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ placement_service = client.GetService('PlacementService', version='v202208')
+ inventory_service = client.GetService('InventoryService', version='v202208')
+
+ # Create placement object to store medium rectangle ad units.
+ medium_rectangle_ad_unit_placement = {
+ 'name': 'Medium rectangle AdUnit Placement #%s' % uuid.uuid4(),
+ 'description': 'Contains ad units that hold creatives of size 300x250',
+ 'targetedAdUnitIds': []
+ }
+
+ # Create placement object to store skyscraper ad units.
+ skyscraper_ad_unit_placement = {
+ 'name': 'Skyscraper AdUnit Placement #%s' % uuid.uuid4(),
+ 'description': 'Contains ad units that hold creatives of size 120x600',
+ 'targetedAdUnitIds': []
+ }
+
+ # Create placement object to store banner ad units.
+ banner_ad_unit_placement = {
+ 'name': 'Banner AdUnit Placement #%s' % uuid.uuid4(),
+ 'description': 'Contains ad units that hold creatives of size 468x60',
+ 'targetedAdUnitIds': []
+ }
+
+ placement_list = []
+
+ # Create statement to get all the ad units.
+ statement = ad_manager.StatementBuilder(version='v202208')
+
+ while True:
+ response = inventory_service.getAdUnitsByStatement(
+ statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ # Separate the ad units by size.
+ for ad_unit in response['results']:
+ if 'adUnitSizes' in ad_unit:
+ for ad_unit_size in ad_unit['adUnitSizes']:
+ size = ad_unit_size['size']
+ if size['width'] == '300' and size['height'] == '250':
+ medium_rectangle_ad_unit_placement['targetedAdUnitIds'].append(
+ ad_unit['id'])
+ elif size['width'] == '120' and size['height'] == '600':
+ skyscraper_ad_unit_placement['targetedAdUnitIds'].append(
+ ad_unit['id'])
+ elif size['width'] == '468' and size['height'] == '60':
+ banner_ad_unit_placement['targetedAdUnitIds'].append(
+ ad_unit['id'])
+ statement.offset += statement.limit
+ else:
+ break
+
+ # Only create placements with one or more ad unit.
+ if medium_rectangle_ad_unit_placement['targetedAdUnitIds']:
+ placement_list.append(medium_rectangle_ad_unit_placement)
+
+ if skyscraper_ad_unit_placement['targetedAdUnitIds']:
+ placement_list.append(skyscraper_ad_unit_placement)
+
+ if banner_ad_unit_placement['targetedAdUnitIds']:
+ placement_list.append(banner_ad_unit_placement)
+
+ # Add placements.
+ placements = placement_service.createPlacements(placement_list)
+
+ # Display results.
+ for placement in placements:
+ ad_unit_ids = ''
+ if 'targetedAdUnitIds' in placement:
+ ad_unit_ids = ', '.join(placement['targetedAdUnitIds'])
+ print('A Placement with ID "%s", name "%s", and containing ad units '
+ '{%s} was created.' % (placement['id'], placement['name'],
+ ad_unit_ids))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/placement_service/deactivate_placements.py b/examples/ad_manager/v202208/placement_service/deactivate_placements.py
new file mode 100755
index 00000000..1a8753d9
--- /dev/null
+++ b/examples/ad_manager/v202208/placement_service/deactivate_placements.py
@@ -0,0 +1,62 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example deactivates all active placements.
+
+To determine which placements exist, run get_all_placements.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+PLACEMENT_ID = 'INSERT_PLACEMENT_ID_HERE'
+
+
+def main(client, placement_id):
+ # Initialize appropriate service.
+ placement_service = client.GetService('PlacementService', version='v202208')
+
+ # Create query.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('id = :placementId')
+ .WithBindVariable('placementId', int(placement_id))
+ .Limit(1))
+
+ # Get placements by statement.
+ placements = placement_service.getPlacementsByStatement(
+ statement.ToStatement())
+
+ for placement in placements:
+ print('Placement with id "%s", name "%s", and status "%s" will be '
+ 'deactivated.' % (placement['id'], placement['name'],
+ placement['status']))
+
+ # Perform action.
+ result = placement_service.performPlacementAction(
+ {'xsi_type': 'DeactivatePlacements'}, statement.ToStatement())
+
+ # Display results.
+ if result and int(result['numChanges']) > 0:
+ print('Number of placements deactivated: %s' % result['numChanges'])
+ else:
+ print('No placements were deactivated.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, PLACEMENT_ID)
diff --git a/examples/ad_manager/v202208/placement_service/get_active_placements.py b/examples/ad_manager/v202208/placement_service/get_active_placements.py
new file mode 100755
index 00000000..77e6ff29
--- /dev/null
+++ b/examples/ad_manager/v202208/placement_service/get_active_placements.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all active placements.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ placement_service = client.GetService('PlacementService', version='v202208')
+ # Create a statement to select placements.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('status = :status')
+ .WithBindVariable('status', 'ACTIVE'))
+
+ # Retrieve a small amount of placements at a time, paging
+ # through until all placements have been retrieved.
+ while True:
+ response = placement_service.getPlacementsByStatement(statement.ToStatement(
+ ))
+ if 'results' in response and len(response['results']):
+ for placement in response['results']:
+ # Print out some information for each placement.
+ print('Placement with ID "%d" and name "%s" was found.\n' %
+ (placement['id'], placement['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/placement_service/get_all_placements.py b/examples/ad_manager/v202208/placement_service/get_all_placements.py
new file mode 100755
index 00000000..2406d1d7
--- /dev/null
+++ b/examples/ad_manager/v202208/placement_service/get_all_placements.py
@@ -0,0 +1,50 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all placements.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ placement_service = client.GetService('PlacementService', version='v202208')
+
+ # Create a statement to select placements.
+ statement = ad_manager.StatementBuilder(version='v202208')
+
+ # Retrieve a small amount of placements at a time, paging
+ # through until all placements have been retrieved.
+ while True:
+ response = placement_service.getPlacementsByStatement(statement.ToStatement(
+ ))
+ if 'results' in response and len(response['results']):
+ for placement in response['results']:
+ # Print out some information for each placement.
+ print('Placement with ID "%d" and name "%s" was found.\n' %
+ (placement['id'], placement['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/placement_service/update_placements.py b/examples/ad_manager/v202208/placement_service/update_placements.py
new file mode 100755
index 00000000..b0697537
--- /dev/null
+++ b/examples/ad_manager/v202208/placement_service/update_placements.py
@@ -0,0 +1,58 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates a single placement to allow for AdSense targeting.
+
+To determine which placements exist, run get_all_placements.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+PLACEMENT_ID = 'INSERT_PLACEMENT_ID_HERE'
+
+
+def main(client, placement_id):
+ # Initialize appropriate service.
+ placement_service = client.GetService('PlacementService', version='v202208')
+
+ # Create query.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('id = :id')
+ .OrderBy('id', ascending=True)
+ .Limit(1)
+ .WithBindVariable('id', placement_id))
+
+ # Get placements by statement.
+ page = placement_service.getPlacementsByStatement(
+ statement.ToStatement())
+
+ placement = page['results'][0]
+
+ placement['description'] = 'This placement contains all leaderboards.'
+
+ # Update placements remotely.
+ updated_placements = placement_service.updatePlacements([placement])
+
+ for placement in updated_placements:
+ print('Placement with id "%s" and name "%s" was updated.'
+ % (placement['id'], placement['name']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, PLACEMENT_ID)
diff --git a/examples/ad_manager/v202208/proposal_line_item_service/__init__.py b/examples/ad_manager/v202208/proposal_line_item_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202208/proposal_line_item_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202208/proposal_line_item_service/archive_proposal_line_items.py b/examples/ad_manager/v202208/proposal_line_item_service/archive_proposal_line_items.py
new file mode 100755
index 00000000..bcc9af63
--- /dev/null
+++ b/examples/ad_manager/v202208/proposal_line_item_service/archive_proposal_line_items.py
@@ -0,0 +1,76 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example archives a proposal line item.
+
+To determine which proposal line items exist, run
+get_all_proposal_line_items.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the id of the proposal line item to archive.
+PROPOSAL_LINE_ITEM_ID = 'INSERT_PROPOSAL_LINE_ITEM_ID_HERE'
+
+
+def main(client, proposal_line_item_id):
+ # Initialize appropriate service.
+ proposal_line_item_service = client.GetService(
+ 'ProposalLineItemService', version='v202208')
+
+ # Create query.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('id = :id')
+ .WithBindVariable('id', int(proposal_line_item_id))
+ .Limit(1))
+
+ proposal_line_items_archived = 0
+
+ # Get proposal line items by statement.
+ while True:
+ response = proposal_line_item_service.getProposalLineItemsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for proposal_line_item in response['results']:
+ print('Proposal line item with id "%s", '
+ 'belonging to proposal id "%s", and '
+ 'name "%s" will be archived.' %
+ (proposal_line_item['id'], proposal_line_item['proposalId'],
+ proposal_line_item['name']))
+
+ # Perform action.
+ result = proposal_line_item_service.performProposalLineItemAction(
+ {'xsi_type': 'ArchiveProposalLineItems'}, statement.ToStatement())
+ if result and int(result['numChanges']) > 0:
+ proposal_line_items_archived += int(result['numChanges'])
+ statement.offset += statement.limit
+ else:
+ break
+
+ # Display results.
+ if proposal_line_items_archived > 0:
+ print('Number of proposal line items '
+ 'archived: %s' % proposal_line_items_archived)
+ else:
+ print('No proposal line items were archived.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, PROPOSAL_LINE_ITEM_ID)
diff --git a/examples/ad_manager/v202208/proposal_line_item_service/create_proposal_line_items.py b/examples/ad_manager/v202208/proposal_line_item_service/create_proposal_line_items.py
new file mode 100755
index 00000000..0d579f98
--- /dev/null
+++ b/examples/ad_manager/v202208/proposal_line_item_service/create_proposal_line_items.py
@@ -0,0 +1,108 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Creates a proposal line item."""
+
+
+import datetime
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+import pytz
+
+# Set proposal that the created proposal line item will belong to.
+PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE'
+
+
+def main(client, proposal_id):
+ proposal_line_item_service = client.GetService(
+ 'ProposalLineItemService', version='v202208')
+ network_service = client.GetService('NetworkService', version='v202208')
+
+ start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York'))
+ end_datetime = start_datetime + datetime.timedelta(days=365)
+
+ # Get the root ad unit to target.
+ root_ad_unit_id = (
+ network_service.getCurrentNetwork()['effectiveRootAdUnitId'])
+
+ # Create a single programmatic proposal line item.
+ proposal_line_item = {
+ # Setting common required fields for proposal line items.
+ 'name': 'Proposal line item #%s' % uuid.uuid4(),
+ 'proposalId': proposal_id,
+ 'targeting': {
+ 'inventoryTargeting': {
+ 'targetedAdUnits': {
+ 'adUnitId': root_ad_unit_id
+ }
+ },
+ 'requestPlatformTargeting': {
+ 'targetedRequestPlatforms': ['BROWSER']
+ },
+ # Target Display environment by excluding Mobile Apps.
+ # DeviceCapabilities can be obtained though the Device_Capability PQL
+ # table:
+ # https://developers.google.com/ad-manager/api/reference/latest/PublisherQueryLanguageService
+ 'technologyTargeting': {
+ 'deviceCapabilityTargeting': [{'id': 5005}]
+ }
+ },
+ 'startDateTime': start_datetime,
+ 'endDateTime': end_datetime,
+ 'creativePlaceholders': [
+ {
+ 'size': {
+ 'width': '300',
+ 'height': '250'
+ }
+ },
+ {
+ 'size': {
+ 'width': '120',
+ 'height': '600'
+ }
+ }
+ ],
+ 'goal': {
+ 'units': '1000',
+ 'unitType': 'IMPRESSIONS',
+ },
+ 'netRate': {
+ 'currencyCode': 'USD',
+ 'microAmount': '2000000'
+ },
+ 'rateType': 'CPM',
+ }
+
+ # Add proposal line items.
+ proposal_line_items = proposal_line_item_service.createProposalLineItems(
+ [proposal_line_item])
+
+ # Display results.
+ for proposal_line_item in proposal_line_items:
+ print('Proposal line item with id "%s", belonging to proposal with id "%s",'
+ ' and named "%s" was created.' % (proposal_line_item['id'],
+ proposal_line_item['proposalId'],
+ proposal_line_item['name']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, PROPOSAL_ID)
+
diff --git a/examples/ad_manager/v202208/proposal_line_item_service/get_all_proposal_line_items.py b/examples/ad_manager/v202208/proposal_line_item_service/get_all_proposal_line_items.py
new file mode 100755
index 00000000..d34164bd
--- /dev/null
+++ b/examples/ad_manager/v202208/proposal_line_item_service/get_all_proposal_line_items.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all proposal line items.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ proposal_line_item_service = client.GetService(
+ 'ProposalLineItemService', version='v202208')
+
+ # Create a statement to select proposal line items.
+ statement = ad_manager.StatementBuilder(version='v202208')
+
+ # Retrieve a small amount of proposal line items at a time, paging
+ # through until all proposal line items have been retrieved.
+ while True:
+ response = proposal_line_item_service.getProposalLineItemsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for proposal_line_item in response['results']:
+ # Print out some information for each proposal line item.
+ print('Proposal line item with ID "%d" and name "%s" was found.\n' %
+ (proposal_line_item['id'], proposal_line_item['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/ad_manager/v202208/proposal_line_item_service/get_proposal_line_items_for_proposal.py
new file mode 100755
index 00000000..ac127ebc
--- /dev/null
+++ b/examples/ad_manager/v202208/proposal_line_item_service/get_proposal_line_items_for_proposal.py
@@ -0,0 +1,54 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all proposal line items belonging to a specific proposal.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE'
+
+
+def main(client, proposal_id):
+ # Initialize appropriate service.
+ proposal_line_item_service = client.GetService(
+ 'ProposalLineItemService', version='v202208')
+ # Create a statement to select proposal line items.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('proposalId = :proposalId')
+ .WithBindVariable('proposalId', proposal_id))
+
+ # Retrieve a small amount of proposal line items at a time, paging
+ # through until all proposal line items have been retrieved.
+ while True:
+ response = proposal_line_item_service.getProposalLineItemsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for proposal_line_item in response['results']:
+ # Print out some information for each proposal line item.
+ print('Proposal line item with ID "%d" and name "%s" was found.\n' %
+ (proposal_line_item['id'], proposal_line_item['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, PROPOSAL_ID)
diff --git a/examples/ad_manager/v202208/proposal_line_item_service/update_proposal_line_items.py b/examples/ad_manager/v202208/proposal_line_item_service/update_proposal_line_items.py
new file mode 100755
index 00000000..887c9ee3
--- /dev/null
+++ b/examples/ad_manager/v202208/proposal_line_item_service/update_proposal_line_items.py
@@ -0,0 +1,72 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates a proposal line item's notes.
+
+To determine which proposal line items exist,
+run get_all_proposal_line_items.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set id of the proposal line item to update.
+PROPOSAL_LINE_ITEM_ID = 'INSERT_PROPOSAL_LINE_ITEM_ID_HERE'
+
+
+def main(client, proposal_line_item_id):
+ # Initialize appropriate service.
+ proposal_line_item_service = client.GetService(
+ 'ProposalLineItemService', version='v202208')
+
+ # Create statement to select a proposal line item.
+
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('id = :id')
+ .WithBindVariable('id', int(proposal_line_item_id))
+ .Limit(1))
+
+ # Get proposal line items by statement.
+ response = proposal_line_item_service.getProposalLineItemsByStatement(
+ statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ # Update each the proposal line item's notes field.
+ proposal_line_item = response['results'][0]
+ proposal_line_item['internalNotes'] = 'Proposal line is ready to submit.'
+
+ # Update proposal line items remotely.
+ proposal_line_items = proposal_line_item_service.updateProposalLineItems(
+ [proposal_line_item])
+
+ # Display results.
+ if proposal_line_items:
+ for proposal_line_item in proposal_line_items:
+ print('Line item with id "%s", belonging to proposal id "%s" and,'
+ ' named "%s" was updated.' % (
+ proposal_line_item['id'], proposal_line_item['proposalId'],
+ proposal_line_item['name']))
+ else:
+ print('No proposal line items were updated.')
+ else:
+ print('No proposal line items found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, PROPOSAL_LINE_ITEM_ID)
diff --git a/examples/ad_manager/v202208/proposal_service/__init__.py b/examples/ad_manager/v202208/proposal_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202208/proposal_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202208/proposal_service/create_proposals.py b/examples/ad_manager/v202208/proposal_service/create_proposals.py
new file mode 100755
index 00000000..b4360ccc
--- /dev/null
+++ b/examples/ad_manager/v202208/proposal_service/create_proposals.py
@@ -0,0 +1,60 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example creates a proposal."""
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+PROGRAMMATIC_BUYER_ID = 'INSERT_BUYER_ID_FROM_PQL_TABLE_HERE'
+PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE'
+PRIMARY_TRAFFICKER_ID = 'INSERT_PRIMARY_TRAFFICKER_ID_HERE'
+
+
+def main(client, programmatic_buyer_id, primary_salesperson_id,
+ primary_trafficker_id):
+ proposal_service = client.GetService('ProposalService', version='v202208')
+
+ proposal = {
+ # Setting required Marketplace information.
+ 'isProgrammatic': 'true',
+ 'marketplaceInfo': {
+ 'buyerAccountId': programmatic_buyer_id,
+ },
+ # Set common required fields for proposals.
+ 'name': 'Proposal #%s' % uuid.uuid4(),
+ 'primarySalesperson': {
+ 'userId': primary_salesperson_id,
+ },
+ 'primaryTraffickerId': primary_trafficker_id,
+ 'probabilityOfClose': '100000',
+ }
+
+ proposals = proposal_service.createProposals([proposal])
+
+ # Display results.
+ for proposal in proposals:
+ print('Proposal with id "%s" and name "%s" was created.' %
+ (proposal['id'], proposal['name']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, PROGRAMMATIC_BUYER_ID, PRIMARY_SALESPERSON_ID,
+ PRIMARY_TRAFFICKER_ID)
diff --git a/examples/ad_manager/v202208/proposal_service/get_all_proposals.py b/examples/ad_manager/v202208/proposal_service/get_all_proposals.py
new file mode 100755
index 00000000..fe88df3b
--- /dev/null
+++ b/examples/ad_manager/v202208/proposal_service/get_all_proposals.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all proposals.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ proposal_service = client.GetService('ProposalService', version='v202208')
+
+ # Create a statement to select proposals.
+ statement = ad_manager.StatementBuilder(version='v202208')
+
+ # Retrieve a small amount of proposals at a time, paging
+ # through until all proposals have been retrieved.
+ while True:
+ response = proposal_service.getProposalsByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for proposal in response['results']:
+ # Print out some information for each proposal.
+ print('Proposal with ID "%d" and name "%s" was found.\n' %
+ (proposal['id'], proposal['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/proposal_service/get_marketplace_comments.py b/examples/ad_manager/v202208/proposal_service/get_marketplace_comments.py
new file mode 100755
index 00000000..e8c263f5
--- /dev/null
+++ b/examples/ad_manager/v202208/proposal_service/get_marketplace_comments.py
@@ -0,0 +1,56 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets the Marketplace comments for a programmatic proposal."""
+
+# Import appropriate modules from the client library.
+from datetime import datetime
+
+from googleads import ad_manager
+
+
+PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE'
+
+
+def main(client, proposal_id):
+ # Initialize appropriate service.
+ marketplace_comment_service = client.GetService(
+ 'ProposalService', version='v202208')
+ query = 'WHERE proposalId = %s' % proposal_id
+ # Create a statement to select marketplace comments.
+ statement = {'query': query}
+
+ response = marketplace_comment_service.getMarketplaceCommentsByStatement(
+ statement)
+
+ # Print out some information for each marketplace comment.
+ for marketplace_comment in response['results']:
+ date_time = marketplace_comment['creationTime']
+ date_time_string = datetime(date_time['date']['year'],
+ date_time['date']['month'],
+ date_time['date']['day'], date_time['hour'],
+ date_time['minute'],
+ date_time['second']).isoformat()
+ print('Marketplace comment with creation time "%s"and comment "%s" was '
+ 'found.\n' % (date_time_string, marketplace_comment['comment']))
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, PROPOSAL_ID)
diff --git a/examples/ad_manager/v202208/proposal_service/get_proposals_awaiting_seller_review.py b/examples/ad_manager/v202208/proposal_service/get_proposals_awaiting_seller_review.py
new file mode 100755
index 00000000..41e433ef
--- /dev/null
+++ b/examples/ad_manager/v202208/proposal_service/get_proposals_awaiting_seller_review.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all proposals awaiting seller review."""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ proposal_service = client.GetService('ProposalService', version='v202208')
+ # Create a statement to select proposals.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('negotiationStatus = :negotiationStatus')
+ .WithBindVariable('negotiationStatus', 'AWAITING_SELLER_REVIEW'))
+
+ # Retrieve a small amount of proposals at a time, paging
+ # through until all proposals have been retrieved.
+ while True:
+ response = proposal_service.getProposalsByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for proposal in response['results']:
+ # Print out some information for each proposal.
+ print('Proposal with ID "%d" and name "%s" was found.\n' %
+ (proposal['id'], proposal['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/proposal_service/request_buyers_acceptance.py b/examples/ad_manager/v202208/proposal_service/request_buyers_acceptance.py
new file mode 100755
index 00000000..e232d171
--- /dev/null
+++ b/examples/ad_manager/v202208/proposal_service/request_buyers_acceptance.py
@@ -0,0 +1,67 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example requests buyer acceptance for a single proposal.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE'
+
+
+def main(client, proposal_id):
+ # Initialize appropriate service.
+ proposal_service = client.GetService('ProposalService', version='v202208')
+
+ # Create query.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('id = :proposalId')
+ .WithBindVariable('proposalId', proposal_id))
+ proposals_pushed_to_marketplace = 0
+
+ # Get proposals by statement.
+ while True:
+ response = proposal_service.getProposalsByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ # Display results.
+ for proposal in response['results']:
+ print('Programmatic proposal with id "%s", name "%s", and status '
+ '"%s" will be pushed to Marketplace.' % (proposal['id'],
+ proposal['name'],
+ proposal['status']))
+ # Perform action.
+ result = proposal_service.performProposalAction(
+ {'xsi_type': 'RequestBuyerAcceptance'}, statement.ToStatement())
+ if result and int(result['numChanges']) > 0:
+ proposals_pushed_to_marketplace += int(result['numChanges'])
+ statement.offset += statement.limit
+ else:
+ break
+
+ # Display results.
+ if proposals_pushed_to_marketplace > 0:
+ print('\nNumber of programmatic proposals pushed to Marketplace: %s'
+ % proposals_pushed_to_marketplace)
+ else:
+ print('\nNo programmatic proposals were pushed to Marketplace.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, PROPOSAL_ID)
diff --git a/examples/ad_manager/v202208/proposal_service/update_proposals.py b/examples/ad_manager/v202208/proposal_service/update_proposals.py
new file mode 100755
index 00000000..85324acd
--- /dev/null
+++ b/examples/ad_manager/v202208/proposal_service/update_proposals.py
@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates the notes of a single proposal specified by ID.
+
+To determine which proposals exist, run get_all_proposals.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE'
+
+
+def main(client, proposal_id):
+ # Initialize appropriate service.
+ proposal_service = client.GetService('ProposalService', version='v202208')
+
+ # Create statement object to select a single proposal by an ID.
+
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('id = :proposalId')
+ .WithBindVariable('proposalId', int(proposal_id))
+ .Limit(1))
+
+ # Get proposals by statement.
+ response = proposal_service.getProposalsByStatement(statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ # Update each local proposal object by changing its notes.
+ updated_proposals = []
+ for proposal in response['results']:
+ proposal['internalNotes'] = 'Proposal needs review before approval.'
+ updated_proposals.append(proposal)
+
+ # Update proposals remotely.
+ proposals = proposal_service.updateProposals(updated_proposals)
+
+ # Display results.
+ if proposals:
+ for proposal in proposals:
+ print('Proposal with id "%s", name "%s", and '
+ 'notes "%s" was updated.'
+ % (proposal['id'], proposal['name'], proposal['internalNotes']))
+ else:
+ print('No proposals were updated.')
+ else:
+ print('No proposals found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, PROPOSAL_ID)
diff --git a/examples/ad_manager/v202208/publisher_query_language_service/__init__.py b/examples/ad_manager/v202208/publisher_query_language_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202208/publisher_query_language_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202208/publisher_query_language_service/fetch_match_tables.py b/examples/ad_manager/v202208/publisher_query_language_service/fetch_match_tables.py
new file mode 100755
index 00000000..1b62f000
--- /dev/null
+++ b/examples/ad_manager/v202208/publisher_query_language_service/fetch_match_tables.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example fetches data from PQL tables and creates match table files."""
+
+
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize a report downloader.
+ report_downloader = client.GetDataDownloader(version='v202208')
+
+ line_items_file = tempfile.NamedTemporaryFile(
+ prefix='line_items_', suffix='.csv', mode='w', delete=False)
+ ad_units_file = tempfile.NamedTemporaryFile(
+ prefix='ad_units_', suffix='.csv', mode='w', delete=False)
+
+ line_items_pql_query = ('SELECT Name, Id, Status FROM Line_Item ORDER BY Id '
+ 'ASC')
+ ad_units_pql_query = 'SELECT Name, Id FROM Ad_Unit ORDER BY Id ASC'
+
+ # Downloads the response from PQL select statement to the specified file
+ report_downloader.DownloadPqlResultToCsv(
+ line_items_pql_query, line_items_file)
+ report_downloader.DownloadPqlResultToCsv(
+ ad_units_pql_query, ad_units_file)
+
+ line_items_file.close()
+ ad_units_file.close()
+
+ print('Saved line items to... %s' % line_items_file.name)
+ print('Saved ad units to... %s' % ad_units_file.name)
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/publisher_query_language_service/get_all_browsers.py b/examples/ad_manager/v202208/publisher_query_language_service/get_all_browsers.py
new file mode 100755
index 00000000..bb05432c
--- /dev/null
+++ b/examples/ad_manager/v202208/publisher_query_language_service/get_all_browsers.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all browsers available to target from the Browser table.
+
+Other tables include 'Bandwidth_Group', 'Browser_Language',
+'Device_Capability', 'Operating_System', etc...
+
+A full list of available criteria tables can be found at
+https://developers.google.com/doubleclick-publishers/docs/reference/v201708/PublisherQueryLanguageService
+"""
+
+
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize a report downloader.
+ report_downloader = client.GetDataDownloader(version='v202208')
+
+ with tempfile.NamedTemporaryFile(
+ prefix='browser_data_',
+ suffix='.csv', mode='w', delete=False) as browser_data_file:
+
+ browser_pql_query = ('SELECT Id, BrowserName, MajorVersion, MinorVersion '
+ 'FROM Browser '
+ 'ORDER BY BrowserName ASC')
+
+ # Downloads the response from PQL select statement to the specified file
+ report_downloader.DownloadPqlResultToCsv(
+ browser_pql_query, browser_data_file)
+
+ print('Saved browser data to... %s' % browser_data_file.name)
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/ad_manager/v202208/publisher_query_language_service/get_all_programmatic_buyers.py
new file mode 100755
index 00000000..41b72a98
--- /dev/null
+++ b/examples/ad_manager/v202208/publisher_query_language_service/get_all_programmatic_buyers.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example fetches programmatic buyer information from the PQL table."""
+
+
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize a report downloader.
+ data_downloader = client.GetDataDownloader(version='v202208')
+
+ programmatic_buyers_file = tempfile.NamedTemporaryFile(
+ prefix='programmatic_buyers_', suffix='.csv', mode='w', delete=False)
+
+ programmatic_buyers_query = ('SELECT BuyerAccountId, Name '
+ 'FROM Programmatic_Buyer '
+ 'ORDER BY BuyerAccountId ASC')
+
+ # Downloads the response from PQL select statement to the specified file
+ data_downloader.DownloadPqlResultToCsv(
+ programmatic_buyers_query, programmatic_buyers_file)
+
+ programmatic_buyers_file.close()
+
+ print('Saved programmatic buyers to... %s' % programmatic_buyers_file.name)
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/publisher_query_language_service/get_geo_targets.py b/examples/ad_manager/v202208/publisher_query_language_service/get_geo_targets.py
new file mode 100755
index 00000000..8cd68c0e
--- /dev/null
+++ b/examples/ad_manager/v202208/publisher_query_language_service/get_geo_targets.py
@@ -0,0 +1,53 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example downloads geo targeting constants using PQL."""
+
+
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the type of geo target to query for.
+GEO_TARGET_TYPE = 'City'
+
+
+def main(client):
+ # Initialize a report downloader.
+ report_downloader = client.GetDataDownloader(version='v202208')
+
+ with tempfile.NamedTemporaryFile(
+ prefix='geo_data_',
+ suffix='.csv', mode='w', delete=False) as geo_data_file:
+
+ geo_pql_query = ('SELECT Id, Name, CanonicalParentId, ParentIds, '
+ 'CountryCode, Type '
+ 'FROM Geo_Target '
+ 'WHERE Type = :type AND Targetable = true '
+ 'ORDER BY CountryCode ASC, Name ASC')
+
+ # Downloads the response from PQL select statement to the specified file
+ report_downloader.DownloadPqlResultToCsv(
+ geo_pql_query, geo_data_file, {'type': geo_target_type})
+
+ print('Saved geo data to... %s' % geo_data_file.name)
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, GEO_TARGET_TYPE)
diff --git a/examples/ad_manager/v202208/publisher_query_language_service/get_line_items_named_like.py b/examples/ad_manager/v202208/publisher_query_language_service/get_line_items_named_like.py
new file mode 100755
index 00000000..54a3a5ba
--- /dev/null
+++ b/examples/ad_manager/v202208/publisher_query_language_service/get_line_items_named_like.py
@@ -0,0 +1,48 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example fetches line items from the pql table with a LIKE clause."""
+
+
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize a report downloader.
+ report_downloader = client.GetDataDownloader(version='v202208')
+
+ with tempfile.NamedTemporaryFile(
+ prefix='line_items_',
+ suffix='.csv', mode='w', delete=False) as line_items_file:
+
+ line_items_pql_query = ("SELECT Id, Name, Status FROM Line_Item "
+ "WHERE Name LIKE 'line item%' "
+ "ORDER BY Id ASC")
+
+ # Downloads the response from PQL select statement to the specified file
+ report_downloader.DownloadPqlResultToCsv(
+ line_items_pql_query, line_items_file)
+
+ print('Saved line items to... %s' % line_items_file.name)
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/publisher_query_language_service/get_mcm_earnings.py b/examples/ad_manager/v202208/publisher_query_language_service/get_mcm_earnings.py
new file mode 100755
index 00000000..503c707b
--- /dev/null
+++ b/examples/ad_manager/v202208/publisher_query_language_service/get_mcm_earnings.py
@@ -0,0 +1,58 @@
+#!/usr/bin/env python
+#
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets Multiple Customer Management earnings for the prior month.
+"""
+
+import datetime
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize a report downloader.
+ data_downloader = client.GetDataDownloader(version='v202208')
+
+ with tempfile.NamedTemporaryFile(
+ prefix='mcm_earnings_',
+ suffix='.csv', mode='w', delete=False) as mcm_earnings_file:
+
+ this_month_start = datetime.date.today().replace(day=1)
+ last_month_end = this_month_start - datetime.timedelta(days=1)
+ last_month_start = last_month_end.replace(day=1)
+
+ mcm_earnings_query = ('SELECT Month, ChildName, ChildNetworkCode, '
+ 'TotalEarningsCurrencyCode, TotalEarningsMicros, '
+ 'ParentPaymentCurrencyCode, ParentPaymentMicros, '
+ 'ChildPaymentCurrencyCode, ChildPaymentMicros, '
+ 'DeductionsMicros '
+ 'FROM Mcm_Earnings '
+ 'WHERE Month = :month '
+ 'ORDER BY ChildNetworkCode')
+
+ # Downloads the response from PQL select statement to the specified file
+ data_downloader.DownloadPqlResultToCsv(
+ mcm_earnings_query, mcm_earnings_file, {'month': last_month_start})
+
+ print('Saved MCM earnings to... %s' % mcm_earnings_file.name)
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/publisher_query_language_service/get_recent_changes.py b/examples/ad_manager/v202208/publisher_query_language_service/get_recent_changes.py
new file mode 100755
index 00000000..275fbd21
--- /dev/null
+++ b/examples/ad_manager/v202208/publisher_query_language_service/get_recent_changes.py
@@ -0,0 +1,156 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Gets recent changes in your network using the Change_History table.
+
+A full list of available tables can be found at:
+https://developers.google.com/doubleclick-publishers/docs/reference/latest/PublisherQueryLanguageService
+"""
+
+from datetime import date
+from datetime import datetime
+from datetime import timedelta
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+import pytz
+
+
+def main(client):
+ # Initialize appropriate service.
+ pql_service = client.GetService('PublisherQueryLanguageService', 'v202208')
+
+ end_date = datetime.now(tz=pytz.timezone('America/New_York'))
+ start_date = end_date - timedelta(days=1)
+ initial_query = ('ChangeDateTime > :startDateTime '
+ 'AND ChangeDateTime < :endDateTime')
+ pagination_query = 'Id < :id AND ' + initial_query
+
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Select(('Id, ChangeDateTime, EntityId, EntityType, '
+ 'Operation, UserId'))
+ .From('Change_History')
+ .Where(initial_query)
+ .OrderBy('ChangeDateTime', ascending=False)
+ .WithBindVariable('startDateTime', start_date)
+ .WithBindVariable('endDateTime', end_date))
+
+ keep_iterating = True
+ i = 0
+ total_rows = []
+
+ while keep_iterating:
+ response = pql_service.select(statement.ToStatement())
+ column_types = ([column_type['labelName']
+ for column_type in response['columnTypes']])
+ rows = response['rows']
+ rows_length = len(rows)
+ total_rows.extend(rows)
+
+ if rows and rows_length > 0:
+ # Get the earliest change ID in the result set.
+ last_row = rows[-1]
+ last_id = last_row['values'][0]['value']
+ i += 1
+
+ # Update the statement using the earliest row in the previous result.
+ statement.Where(pagination_query)
+ statement.WithBindVariable('id', last_id)
+
+ print('%d) %d changes prior to ID "%s" were found.\n'
+ % (i, rows_length, last_id))
+
+ keep_iterating = rows and len(rows) == statement.limit
+
+ # Print out columns header
+ print(','.join(column_types))
+
+ # Print out every row
+ for row in total_rows:
+ print(ConvertValueForCsv(row))
+
+
+def ConvertValueForCsv(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.
+ """
+ if 'value' in pql_value:
+ field = pql_value['value']
+ elif 'values' in pql_value:
+ field = pql_value['values']
+ else:
+ field = None
+
+ if field:
+ if isinstance(field, list):
+ return ','.join(['"%s"' % str(ConvertValueForCsv(single_field))
+ for single_field in field])
+ else:
+ class_type = ad_manager.AdManagerClassType(pql_value)
+
+ if class_type == 'TextValue':
+ return field.replace('"', '""').encode('UTF8')
+ elif class_type == 'NumberValue':
+ return float(field) if '.' in field else int(field)
+ elif class_type == 'DateTimeValue':
+ return ConvertDateTimeToOffset(field)
+ elif class_type == 'DateValue':
+ return date(int(field['date']['year']),
+ int(field['date']['month']),
+ int(field['date']['day'])).isoformat()
+ else:
+ return field
+ else:
+ return '-'
+
+
+def ConvertDateTimeToOffset(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 of the date time value uniform to
+ ReportService.
+ """
+ date_time_obj = datetime(int(date_time_value['date']['year']),
+ int(date_time_value['date']['month']),
+ int(date_time_value['date']['day']),
+ int(date_time_value['hour']),
+ int(date_time_value['minute']),
+ int(date_time_value['second']))
+ date_time_str = pytz.timezone(
+ date_time_value['timeZoneId']).localize(date_time_obj).isoformat()
+
+ if date_time_str[-5:] == '00:00':
+ return date_time_str[:-6] + 'Z'
+ else:
+ return date_time_str
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/report_service/__init__.py b/examples/ad_manager/v202208/report_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202208/report_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202208/report_service/run_delivery_report.py b/examples/ad_manager/v202208/report_service/run_delivery_report.py
new file mode 100755
index 00000000..3e371886
--- /dev/null
+++ b/examples/ad_manager/v202208/report_service/run_delivery_report.py
@@ -0,0 +1,88 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Runs a report similar to the "Orders report" on the Ad Manager website.
+
+Includes additional attributes and can filter to include just one order.
+"""
+
+from datetime import datetime
+from datetime import timedelta
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+from googleads import errors
+
+ORDER_ID = 'INSERT_ORDER_ID_HERE'
+
+
+def main(client, order_id):
+ # Create statement object to filter for an order.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('ORDER_ID = :id')
+ .WithBindVariable('id', int(order_id))
+ .Limit(None) # No limit or offset for reports
+ .Offset(None))
+
+ # Set the start and end dates of the report to run (past 8 days).
+ end_date = datetime.now().date()
+ start_date = end_date - timedelta(days=8)
+
+ # Create report job.
+ report_job = {
+ 'reportQuery': {
+ 'dimensions': ['ORDER_ID', 'ORDER_NAME'],
+ 'dimensionAttributes': ['ORDER_TRAFFICKER', 'ORDER_START_DATE_TIME',
+ 'ORDER_END_DATE_TIME'],
+ 'statement': statement.ToStatement(),
+ 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS',
+ 'AD_SERVER_CTR', 'AD_SERVER_CPM_AND_CPC_REVENUE',
+ 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'],
+ 'dateRangeType': 'CUSTOM_DATE',
+ 'startDate': start_date,
+ 'endDate': end_date
+ }
+ }
+
+ # Initialize a DataDownloader.
+ report_downloader = client.GetDataDownloader(version='v202208')
+
+ try:
+ # Run the report and wait for it to finish.
+ report_job_id = report_downloader.WaitForReport(report_job)
+ except errors.AdManagerReportError as e:
+ print('Failed to generate report. Error was: %s' % e)
+
+ # Change to your preferred export format.
+ export_format = 'CSV_DUMP'
+
+ report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
+
+ # Download report data.
+ report_downloader.DownloadReportToFile(
+ report_job_id, export_format, report_file)
+
+ report_file.close()
+
+ # Display results.
+ print('Report job with id "%s" downloaded to:\n%s' % (
+ report_job_id, report_file.name))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, ORDER_ID)
diff --git a/examples/ad_manager/v202208/report_service/run_inventory_report.py b/examples/ad_manager/v202208/report_service/run_inventory_report.py
new file mode 100755
index 00000000..4f746de6
--- /dev/null
+++ b/examples/ad_manager/v202208/report_service/run_inventory_report.py
@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example runs a typical daily inventory report."""
+
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+from googleads import errors
+
+
+def main(client):
+ # Initialize a DataDownloader.
+ report_downloader = client.GetDataDownloader(version='v202208')
+
+ # Create report job.
+ report_job = {
+ 'reportQuery': {
+ 'dimensions': ['DATE', 'AD_UNIT_NAME'],
+ 'adUnitView': 'HIERARCHICAL',
+ 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS',
+ 'AD_EXCHANGE_LINE_ITEM_LEVEL_IMPRESSIONS',
+ 'AD_EXCHANGE_LINE_ITEM_LEVEL_CLICKS',
+ 'TOTAL_LINE_ITEM_LEVEL_IMPRESSIONS',
+ 'TOTAL_LINE_ITEM_LEVEL_CPM_AND_CPC_REVENUE'],
+ 'dateRangeType': 'LAST_WEEK'
+ }
+ }
+
+ try:
+ # Run the report and wait for it to finish.
+ report_job_id = report_downloader.WaitForReport(report_job)
+ except errors.AdManagerReportError as e:
+ print('Failed to generate report. Error was: %s' % e)
+
+ # Change to your preferred export format.
+ export_format = 'CSV_DUMP'
+
+ report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
+
+ # Download report data.
+ report_downloader.DownloadReportToFile(
+ report_job_id, export_format, report_file)
+
+ report_file.close()
+
+ # Display results.
+ print('Report job with id "%s" downloaded to:\n%s' % (
+ report_job_id, report_file.name))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/report_service/run_reach_report.py b/examples/ad_manager/v202208/report_service/run_reach_report.py
new file mode 100755
index 00000000..7114e4da
--- /dev/null
+++ b/examples/ad_manager/v202208/report_service/run_reach_report.py
@@ -0,0 +1,65 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example runs a reach report."""
+
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+from googleads import errors
+
+
+def main(client):
+ # Initialize a DataDownloader.
+ report_downloader = client.GetDataDownloader(version='v202208')
+
+ # Create report job.
+ report_job = {
+ 'reportQuery': {
+ 'dimensions': ['COUNTRY_NAME', 'LINE_ITEM_ID', 'LINE_ITEM_NAME'],
+ 'columns': ['UNIQUE_REACH_FREQUENCY', 'UNIQUE_REACH_IMPRESSIONS',
+ 'UNIQUE_REACH'],
+ 'dateRangeType': 'REACH_LIFETIME'
+ }
+ }
+
+ try:
+ # Run the report and wait for it to finish.
+ report_job_id = report_downloader.WaitForReport(report_job)
+ except errors.AdManagerReportError as e:
+ print('Failed to generate report. Error was: %s' % e)
+
+ # Change to your preferred export format.
+ export_format = 'CSV_DUMP'
+
+ report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
+
+ # Download report data.
+ report_downloader.DownloadReportToFile(
+ report_job_id, export_format, report_file)
+
+ report_file.close()
+
+ # Display results.
+ print('Report job with id "%s" downloaded to:\n%s' % (
+ report_job_id, report_file.name))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/report_service/run_reach_report_with_ad_unit_dimensions.py b/examples/ad_manager/v202208/report_service/run_reach_report_with_ad_unit_dimensions.py
new file mode 100755
index 00000000..fd703b06
--- /dev/null
+++ b/examples/ad_manager/v202208/report_service/run_reach_report_with_ad_unit_dimensions.py
@@ -0,0 +1,69 @@
+#!/usr/bin/env python
+#
+# Copyright 2021 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example runs a reach report."""
+
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+from googleads import errors
+
+
+def main(client):
+ # Initialize a DataDownloader.
+ report_downloader = client.GetDataDownloader(version='v202208')
+
+ # Create report job.
+ report_job = {
+ 'reportQuery': {
+ # For Reach reports with AD_UNIT_ID or AD_UNIT_NAME in the dimensions
+ # list, adUnitView must be set to 'FLAT' or 'HIERARCHICAL'.
+ 'adUnitView': 'FLAT',
+ 'dimensions': ['MONTH_AND_YEAR', 'COUNTRY_NAME', 'AD_UNIT_ID',
+ 'AD_UNIT_NAME'],
+ 'columns': ['UNIQUE_REACH_FREQUENCY', 'UNIQUE_REACH_IMPRESSIONS',
+ 'UNIQUE_REACH'],
+ 'dateRangeType': 'LAST_MONTH'
+ }
+ }
+
+ try:
+ # Run the report and wait for it to finish.
+ report_job_id = report_downloader.WaitForReport(report_job)
+ except errors.AdManagerReportError as e:
+ print('Failed to generate report. Error was: %s' % e)
+
+ # Change to your preferred export format.
+ export_format = 'CSV_DUMP'
+
+ report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
+
+ # Download report data.
+ report_downloader.DownloadReportToFile(
+ report_job_id, export_format, report_file)
+
+ report_file.close()
+
+ # Display results.
+ print('Report job with id "%s" downloaded to:\n%s' % (
+ report_job_id, report_file.name))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/report_service/run_report_and_create_match_table.py b/examples/ad_manager/v202208/report_service/run_report_and_create_match_table.py
new file mode 100755
index 00000000..094b5071
--- /dev/null
+++ b/examples/ad_manager/v202208/report_service/run_report_and_create_match_table.py
@@ -0,0 +1,88 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Runs a report for LineItems with additional data from a PQL table.
+
+Fetches a basic report over a network's LineItems and then adds some
+extra columns which might be useful for future analysis, such as
+LineItemType, from the PQL Line_Item table, creating a match table.
+"""
+
+from datetime import date
+from datetime import timedelta
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+from googleads import errors
+
+try:
+ import pandas
+except ImportError:
+ raise ImportError('This example requires the pandas library to be installed.')
+
+
+def main(client):
+ # Set the start and end dates of the report to run (past 8 days).
+ end_date = date.today()
+ start_date = end_date - timedelta(days=8)
+
+ # Create report job.
+ report_job = {
+ 'reportQuery': {
+ 'dimensions': ['LINE_ITEM_ID', 'LINE_ITEM_NAME'],
+ 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS',
+ 'AD_SERVER_CTR', 'AD_SERVER_CPM_AND_CPC_REVENUE',
+ 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'],
+ 'dateRangeType': 'CUSTOM_DATE',
+ 'startDate': start_date,
+ 'endDate': end_date
+ }
+ }
+
+ # Initialize a DataDownloader.
+ report_downloader = client.GetDataDownloader(version='v202208')
+
+ try:
+ # Run the report and wait for it to finish.
+ report_job_id = report_downloader.WaitForReport(report_job)
+ except errors.AdManagerReportError as e:
+ print('Failed to generate report. Error was: %s' % e)
+
+ with tempfile.NamedTemporaryFile(
+ suffix='.csv.gz', mode='wb', delete=False) as report_file:
+ # Download report data.
+ report_downloader.DownloadReportToFile(
+ report_job_id, 'CSV_DUMP', report_file)
+
+ # Create a PQL query to fetch the line item data
+ line_items_pql_query = ('SELECT Id, LineItemType, Status FROM LineItem')
+
+ # Download the response from PQL select statement
+ line_items = report_downloader.DownloadPqlResultToList(line_items_pql_query)
+
+ # Use pandas to join the two csv files into a match table
+ report = pandas.read_csv(report_file.name)
+ line_items = pandas.DataFrame(data=line_items[1:], columns=line_items[0])
+ merged_result = pandas.merge(report, line_items,
+ left_on='Dimension.LINE_ITEM_ID', right_on='id')
+ merged_result.to_csv('~/complete_line_items_report.csv', index=False)
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/report_service/run_report_with_custom_fields.py b/examples/ad_manager/v202208/report_service/run_report_with_custom_fields.py
new file mode 100755
index 00000000..986d252d
--- /dev/null
+++ b/examples/ad_manager/v202208/report_service/run_report_with_custom_fields.py
@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Runs a report with custom fields found in the line items of an order."""
+
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+from googleads import errors
+
+CUSTOM_FIELD_ID = 'INSERT_CUSTOM_FIELD_ID'
+CUSTOM_DIMENSION_KEY_ID = 'INSERT_CUSTOM_DIMENSION_KEY_ID'
+
+
+def main(client, custom_field_id, custom_dimension_key_id):
+ # Initialize a DataDownloader.
+ report_downloader = client.GetDataDownloader(version='v202208')
+
+ # Create report job.
+ report_job = {
+ 'reportQuery': {
+ 'dimensions': ['CUSTOM_DIMENSION', 'LINE_ITEM_ID', 'LINE_ITEM_NAME'],
+ 'columns': ['AD_SERVER_IMPRESSIONS'],
+ 'dateRangeType': 'LAST_MONTH',
+ 'customFieldIds': [custom_field_id],
+ 'customDimensionKeyIds': [custom_dimension_key_id]
+ }
+ }
+
+ try:
+ # Run the report and wait for it to finish.
+ report_job_id = report_downloader.WaitForReport(report_job)
+ except errors.AdManagerReportError as e:
+ print('Failed to generate report. Error was: %s' % e)
+
+ # Change to your preferred export format.
+ export_format = 'CSV_DUMP'
+
+ report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
+
+ # Download report data.
+ report_downloader.DownloadReportToFile(
+ report_job_id, export_format, report_file)
+
+ report_file.close()
+
+ # Display results.
+ print('Report job with id "%s" downloaded to:\n%s' % (
+ report_job_id, report_file.name))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, CUSTOM_FIELD_ID, CUSTOM_DIMENSION_KEY_ID)
diff --git a/examples/ad_manager/v202208/report_service/run_sales_report.py b/examples/ad_manager/v202208/report_service/run_sales_report.py
new file mode 100755
index 00000000..2a74d033
--- /dev/null
+++ b/examples/ad_manager/v202208/report_service/run_sales_report.py
@@ -0,0 +1,64 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Runs a report equal to the 'Sales by salespersons report'."""
+
+import tempfile
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+from googleads import errors
+
+
+def main(client):
+ # Initialize a DataDownloader.
+ report_downloader = client.GetDataDownloader(version='v202208')
+
+ # Create report job.
+ report_job = {
+ 'reportQuery': {
+ 'dimensions': ['SALESPERSON_ID', 'SALESPERSON_NAME'],
+ 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CPM_AND_CPC_REVENUE',
+ 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'],
+ 'dateRangeType': 'LAST_MONTH'
+ }
+ }
+
+ try:
+ # Run the report and wait for it to finish.
+ report_job_id = report_downloader.WaitForReport(report_job)
+ except errors.AdManagerReportError as e:
+ print('Failed to generate report. Error was: %s' % e)
+
+ # Change to your preferred export format.
+ export_format = 'CSV_DUMP'
+
+ report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
+
+ # Download report data.
+ report_downloader.DownloadReportToFile(
+ report_job_id, export_format, report_file)
+
+ report_file.close()
+
+ # Display results.
+ print('Report job with id "%s" downloaded to:\n%s' % (
+ report_job_id, report_file.name))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/report_service/run_saved_query.py b/examples/ad_manager/v202208/report_service/run_saved_query.py
new file mode 100755
index 00000000..46f321a9
--- /dev/null
+++ b/examples/ad_manager/v202208/report_service/run_saved_query.py
@@ -0,0 +1,80 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example runs a report from a saved query.
+"""
+
+# Import appropriate modules from the client library.
+import tempfile
+
+from googleads import ad_manager
+from googleads import errors
+
+SAVED_QUERY_ID = 'INSERT_SAVED_QUERY_ID_HERE'
+
+
+def main(client, saved_query_id):
+ # Initialize appropriate service.
+ report_service = client.GetService('ReportService', version='v202208')
+
+ # Initialize a DataDownloader.
+ report_downloader = client.GetDataDownloader(version='v202208')
+
+ # Create statement object to filter for an order.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('id = :id')
+ .WithBindVariable('id', int(saved_query_id))
+ .Limit(1))
+
+ response = report_service.getSavedQueriesByStatement(
+ statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ saved_query = response['results'][0]
+
+ if saved_query['isCompatibleWithApiVersion']:
+ report_job = {}
+
+ # Set report query and optionally modify it.
+ report_job['reportQuery'] = saved_query['reportQuery']
+
+ try:
+ # Run the report and wait for it to finish.
+ report_job_id = report_downloader.WaitForReport(report_job)
+ except errors.AdManagerReportError as e:
+ print('Failed to generate report. Error was: %s' % e)
+ # Change to your preferred export format.
+ export_format = 'CSV_DUMP'
+
+ report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
+
+ # Download report data.
+ report_downloader.DownloadReportToFile(
+ report_job_id, export_format, report_file)
+
+ report_file.close()
+
+ # Display results.
+ print('Report job with id "%s" downloaded to:\n%s' % (
+ report_job_id, report_file.name))
+ else:
+ print('The query specified is not compatible with the API version.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, SAVED_QUERY_ID)
diff --git a/examples/ad_manager/v202208/site_service/create_sites.py b/examples/ad_manager/v202208/site_service/create_sites.py
new file mode 100755
index 00000000..2414a792
--- /dev/null
+++ b/examples/ad_manager/v202208/site_service/create_sites.py
@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+#
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example creates a Site for Multiple Customer Management."""
+
+# Import appropriate modules from the client library.
+import sys
+from googleads import ad_manager
+
+# Set the URL and child network code for the Site.
+URL = 'INSERT_URL_HERE'
+CHILD_NETWORK_CODE = 'INSERT_CHILD_NETWORK_CODE_HERE'
+
+
+def main(client, url, child_network_code):
+ # Initialize appropriate services.
+ network_service = client.GetService('NetworkService', version='v202208')
+ site_service = client.GetService('SiteService', version='v202208')
+
+ # Check that the child network code is approved for MANAGE_INVENTORY by this
+ # network.
+ current_network = network_service.getCurrentNetwork()
+ child_network = None
+ for child in current_network['childPublishers']:
+ if child['childNetworkCode'] == child_network_code:
+ child_network = child
+
+ if child_network is None:
+ print(('Child network %s not found on the current network (%s). Cannot '
+ 'create site.') % (child_network_code,
+ current_network['networkCode']))
+ sys.exit(1)
+
+ if child_network['approvedDelegationType'] != 'MANAGE_INVENTORY':
+ print(('Child network %s has not approved for the current network (%s) '
+ 'to manage its inventory. Cannot create site.') % (
+ child_network_code, current_network['networkCode']))
+ sys.exit(1)
+
+ # Create site object.
+ site = {'url': url, 'childNetworkCode': child_network_code}
+
+ # Create the site on the server.
+ created_sites = site_service.createSites([site])
+
+ # Display results.
+ for site in created_sites:
+ print('Site with id %d and URL "%s" was created for child network %s.' % (
+ site['id'], site['url'], site['childNetworkCode']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, URL, CHILD_NETWORK_CODE)
diff --git a/examples/ad_manager/v202208/site_service/get_all_sites.py b/examples/ad_manager/v202208/site_service/get_all_sites.py
new file mode 100755
index 00000000..98e0ec20
--- /dev/null
+++ b/examples/ad_manager/v202208/site_service/get_all_sites.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+#
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all Sites."""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ site_service = client.GetService('SiteService', version='v202208')
+
+ # Create a statement to select Sites.
+ statement = ad_manager.StatementBuilder(version='v202208')
+
+ # Retrieve a small number of sites at a time, paging through until all sites
+ # have been retrieved.
+ while True:
+ response = site_service.getSitesByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for site in response['results']:
+ # Print out some information for each site.
+ print('Site with Id %d and URL "%s" was found.' %
+ (site['id'], site['url']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/site_service/get_sites_requiring_approval.py b/examples/ad_manager/v202208/site_service/get_sites_requiring_approval.py
new file mode 100755
index 00000000..ede12b20
--- /dev/null
+++ b/examples/ad_manager/v202208/site_service/get_sites_requiring_approval.py
@@ -0,0 +1,50 @@
+#!/usr/bin/env python
+#
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets Sites under MCM requiring review."""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ site_service = client.GetService('SiteService', version='v202208')
+
+ # Create a statement to select Sites needing approval.
+ statement = ad_manager.StatementBuilder(version='v202208').Where(
+ "approvalStatus = 'REQUIRES_REVIEW'")
+
+ # Retrieve a small number of sites at a time, paging through until all sites
+ # have been retrieved.
+ while True:
+ response = site_service.getSitesByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for site in response['results']:
+ # Print out some information for each site.
+ print('Site with Id %d and URL "%s" was found.' %
+ (site['id'], site['url']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/site_service/submit_sites_for_approval.py b/examples/ad_manager/v202208/site_service/submit_sites_for_approval.py
new file mode 100755
index 00000000..9f96fa9a
--- /dev/null
+++ b/examples/ad_manager/v202208/site_service/submit_sites_for_approval.py
@@ -0,0 +1,44 @@
+#!/usr/bin/env python
+#
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example submits a Site for approval."""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+# Set the id of the site to submit for approval.
+SITE_ID = 'INSERT_SITE_ID_HERE'
+
+
+def main(client):
+ # Initialize appropriate service.
+ site_service = client.GetService('SiteService', version='v202208')
+
+ # Create a statement to select Site.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('id = :id')
+ .WithBindVariable('id', SITE_ID))
+
+ response = site_service.performSiteAction(
+ {'xsi_type': 'SubmitSiteForApproval'}, statement.ToStatement())
+
+ print('\nNumber of sites changed: %s' % response['numChanges'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/suggested_ad_unit_service/__init__.py b/examples/ad_manager/v202208/suggested_ad_unit_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202208/suggested_ad_unit_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202208/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/ad_manager/v202208/suggested_ad_unit_service/approve_all_suggested_ad_units.py
new file mode 100755
index 00000000..87b1b830
--- /dev/null
+++ b/examples/ad_manager/v202208/suggested_ad_unit_service/approve_all_suggested_ad_units.py
@@ -0,0 +1,70 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example approves all suggested ad units with 50 or more requests.
+
+This feature is only available to Ad Manager 360 solution networks.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+THRESHOLD_NUMBER_OF_REQUESTS = '50'
+
+
+def main(client):
+ # Initialize appropriate service.
+ suggested_ad_unit_service = client.GetService(
+ 'SuggestedAdUnitService', version='v202208')
+
+ # Create a filter statement.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('numRequests > :numRequests')
+ .WithBindVariable('numRequests', THRESHOLD_NUMBER_OF_REQUESTS))
+ num_approved_suggested_ad_units = 0
+
+ # Get suggested ad units by statement.
+ while True:
+ response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ # Print suggested ad units that will be approved.
+ for suggested_ad_unit in response['results']:
+ print('Suggested ad unit with id "%s", and number of requests "%s"'
+ ' will be approved.' % (suggested_ad_unit['id'],
+ suggested_ad_unit['numRequests']))
+
+ # Approve suggested ad units.
+ result = suggested_ad_unit_service.performSuggestedAdUnitAction(
+ {'xsi_type': 'ApproveSuggestedAdUnits'},
+ statement.ToStatement())
+ if result and int(result['numChanges']) > 0:
+ num_approved_suggested_ad_units += int(result['numChanges'])
+ else:
+ break
+
+ if num_approved_suggested_ad_units > 0:
+ print('Number of suggested ad units approved: %s' %
+ num_approved_suggested_ad_units)
+ else:
+ print('No suggested ad units were approved.')
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
+
diff --git a/examples/ad_manager/v202208/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/ad_manager/v202208/suggested_ad_unit_service/get_all_suggested_ad_units.py
new file mode 100755
index 00000000..2f0a0ac5
--- /dev/null
+++ b/examples/ad_manager/v202208/suggested_ad_unit_service/get_all_suggested_ad_units.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all suggested ad units.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ suggested_ad_unit_service = client.GetService(
+ 'SuggestedAdUnitService', version='v202208')
+
+ # Create a statement to select suggested ad units.
+ statement = ad_manager.StatementBuilder(version='v202208')
+
+ # Retrieve a small amount of suggested ad units at a time, paging
+ # through until all suggested ad units have been retrieved.
+ while True:
+ response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for suggested_ad_unit in response['results']:
+ # Print out some information for each suggested ad unit.
+ print(
+ 'Suggested ad unit with ID "%s" and num requests "%d" was found.\n'
+ % (suggested_ad_unit['id'], suggested_ad_unit['numRequests']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/ad_manager/v202208/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py
new file mode 100755
index 00000000..3dcfaa48
--- /dev/null
+++ b/examples/ad_manager/v202208/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all highly requested suggested ad units.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+NUM_REQUESTS = 'INSERT_NUM_REQUESTS_HERE'
+
+
+def main(client, num_requests):
+ # Initialize appropriate service.
+ suggested_ad_unit_service = client.GetService(
+ 'SuggestedAdUnitService', version='v202208')
+ # Create a statement to select suggested ad units.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('numRequests >= :numRequests')
+ .WithBindVariable('numRequests', int(num_requests)))
+
+ # Retrieve a small amount of suggested ad units at a time, paging
+ # through until all suggested ad units have been retrieved.
+ while True:
+ response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for suggested_ad_unit in response['results']:
+ # Print out some information for each suggested ad unit.
+ print(
+ 'Suggested ad unit with ID "%s" and num requests "%d" was found.\n'
+ % (suggested_ad_unit['id'], suggested_ad_unit['numRequests']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, NUM_REQUESTS)
diff --git a/examples/ad_manager/v202208/targeting_preset_service/__init__.py b/examples/ad_manager/v202208/targeting_preset_service/__init__.py
new file mode 100755
index 00000000..6d126cce
--- /dev/null
+++ b/examples/ad_manager/v202208/targeting_preset_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2019 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202208/targeting_preset_service/get_all_targeting_presets.py b/examples/ad_manager/v202208/targeting_preset_service/get_all_targeting_presets.py
new file mode 100755
index 00000000..665ca95e
--- /dev/null
+++ b/examples/ad_manager/v202208/targeting_preset_service/get_all_targeting_presets.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2019 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all targeting presets.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ targeting_preset_service = client.GetService(
+ 'TargetingPresetService', version='v202208')
+
+ # Create a statement to select suggested ad units.
+ statement = ad_manager.StatementBuilder(version='v202208')
+
+ # Retrieve a small number of targeting presets at a time, paging
+ # through until all targeting presets have been retrieved.
+ while True:
+ response = targeting_preset_service.getTargetingPresetsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for targeting_preset in response['results']:
+ # Print out some information for each targeting preset.
+ print(
+ 'Targeting preset with ID "%d" and name "%s" was found.\n'
+ % (targeting_preset['id'], targeting_preset['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/team_service/__init__.py b/examples/ad_manager/v202208/team_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202208/team_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202208/team_service/create_teams.py b/examples/ad_manager/v202208/team_service/create_teams.py
new file mode 100755
index 00000000..ef39302a
--- /dev/null
+++ b/examples/ad_manager/v202208/team_service/create_teams.py
@@ -0,0 +1,60 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example creates new teams.
+
+To determine which teams exist, run get_all_teams.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+"""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ team_service = client.GetService('TeamService', version='v202208')
+
+ # Create team objects.
+ teams = []
+ for _ in range(5):
+ team = {
+ 'name': 'Team %s' % uuid.uuid4(),
+ 'hasAllCompanies': 'false',
+ 'hasAllInventory': 'false',
+ 'teamAccessType': 'READ_WRITE'
+ }
+ teams.append(team)
+
+ # Add Teams.
+ teams = team_service.createTeams(teams)
+
+ # Display results.
+ for team in teams:
+ print('Team with ID "%s" and name "%s" was created.'
+ % (team['id'], team['name']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/team_service/get_all_teams.py b/examples/ad_manager/v202208/team_service/get_all_teams.py
new file mode 100755
index 00000000..8895dcad
--- /dev/null
+++ b/examples/ad_manager/v202208/team_service/get_all_teams.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all teams.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ team_service = client.GetService('TeamService', version='v202208')
+
+ # Create a statement to select teams.
+ statement = ad_manager.StatementBuilder(version='v202208')
+
+ # Retrieve a small amount of teams at a time, paging
+ # through until all teams have been retrieved.
+ while True:
+ response = team_service.getTeamsByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for team in response['results']:
+ # Print out some information for each team.
+ print('Team with ID "%d" and name "%s" was found.\n' % (team['id'],
+ team['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/team_service/update_teams.py b/examples/ad_manager/v202208/team_service/update_teams.py
new file mode 100755
index 00000000..8a92c0e6
--- /dev/null
+++ b/examples/ad_manager/v202208/team_service/update_teams.py
@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example updates teams by changing its description.
+
+To determine which teams exist, run get_all_teams.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+TEAM_ID = 'INSERT_TEAM_ID_HERE'
+
+
+def main(client, team_id):
+ # Initialize appropriate service.
+ team_service = client.GetService('TeamService', version='v202208')
+
+ # Create a filter statement to select a single team by ID.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('id = :teamId')
+ .WithBindVariable('teamId', int(team_id)))
+
+ # Get teams by statement.
+ response = team_service.getTeamsByStatement(statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ updated_teams = []
+ # Update each local team object by changing its description.
+ for team in response['results']:
+ team['description'] = 'this team is great!'
+ updated_teams.append(team)
+
+ # Update teams on the server.
+ teams = team_service.updateTeams(updated_teams)
+
+ # Display results.
+ for team in teams:
+ print('Team with id "%s" and name "%s" was updated.'
+ % (team['id'], team['name']))
+ else:
+ print('No teams found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, TEAM_ID)
diff --git a/examples/ad_manager/v202208/user_service/__init__.py b/examples/ad_manager/v202208/user_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202208/user_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202208/user_service/create_users.py b/examples/ad_manager/v202208/user_service/create_users.py
new file mode 100755
index 00000000..62ca5a33
--- /dev/null
+++ b/examples/ad_manager/v202208/user_service/create_users.py
@@ -0,0 +1,57 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example creates new users.
+
+To determine which users exist, run get_all_users.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+NEW_USER_EMAIL_ADDRESS = 'INSERT_EMAIL_ADDRESS_HERE'
+NEW_USER_NAME = 'INSERT_NAME_HERE'
+
+
+def main(client, email, name):
+ # Initialize appropriate service.
+ user_service = client.GetService('UserService', version='v202208')
+
+ # Create user objects.
+ users = [
+ {
+ 'email': email,
+ 'name': name,
+ }
+ ]
+ for user in users:
+ # Set the system defined ID of the trafficker role.
+ # To determine what other roles exist, run get_all_roles.py.
+ user['roleId'] = '-7'
+
+ # Add users.
+ users = user_service.createUsers(users)
+
+ # Display results.
+ for user in users:
+ print('User with id "%s", email "%s", and role "%s" was created.'
+ % (user['id'], user['email'], user['roleName']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, NEW_USER_EMAIL_ADDRESS, NEW_USER_NAME)
diff --git a/examples/ad_manager/v202208/user_service/deactivate_users.py b/examples/ad_manager/v202208/user_service/deactivate_users.py
new file mode 100755
index 00000000..65af930a
--- /dev/null
+++ b/examples/ad_manager/v202208/user_service/deactivate_users.py
@@ -0,0 +1,65 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example deactivates a user.
+
+Deactivated users can no longer make requests to the API. The user making the
+request cannot deactivate itself. To determine which users exist, run
+get_all_users.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+USER_ID = 'INSERT_USER_ID_TO_DEACTIVATE_HERE'
+
+
+def main(client, user_id):
+ # Initialize appropriate service.
+ user_service = client.GetService('UserService', version='v202208')
+
+ # Create query.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('id = :userId')
+ .WithBindVariable('userId', int(user_id)))
+
+ # Get users by statement.
+ response = user_service.getUsersByStatement(statement.ToStatement())
+ users = response['results'] if 'results' in response else []
+
+ for user in users:
+ print('User with id "%s", email "%s", and status "%s" will be '
+ 'deactivated.'
+ % (user['id'], user['email'],
+ {'true': 'ACTIVE', 'false': 'INACTIVE'}[user['isActive']]))
+ print('Number of users to be deactivated: %s' % len(users))
+
+ # Perform action.
+ result = user_service.performUserAction({'xsi_type': 'DeactivateUsers'},
+ statement.ToStatement())
+
+ # Display results.
+ if result and int(result['numChanges']) > 0:
+ print('Number of users deactivated: %s' % result['numChanges'])
+ else:
+ print('No users were deactivated.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, USER_ID)
diff --git a/examples/ad_manager/v202208/user_service/get_all_roles.py b/examples/ad_manager/v202208/user_service/get_all_roles.py
new file mode 100755
index 00000000..f22b9006
--- /dev/null
+++ b/examples/ad_manager/v202208/user_service/get_all_roles.py
@@ -0,0 +1,40 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all roles.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ user_service = client.GetService('UserService', version='v202208')
+
+ roles = user_service.getAllRoles()
+
+ # Print out some information for each role.
+ for role in roles:
+ print('Role with id "%s" and name "%s" was found.' %
+ (role['id'], role['name']))
+
+ print('\nNumber of results found: %s' % len(roles))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/user_service/get_all_users.py b/examples/ad_manager/v202208/user_service/get_all_users.py
new file mode 100755
index 00000000..895af9d7
--- /dev/null
+++ b/examples/ad_manager/v202208/user_service/get_all_users.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all users.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ user_service = client.GetService('UserService', version='v202208')
+
+ # Create a statement to select users.
+ statement = ad_manager.StatementBuilder(version='v202208')
+
+ # Retrieve a small amount of users at a time, paging
+ # through until all users have been retrieved.
+ while True:
+ response = user_service.getUsersByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for user in response['results']:
+ # Print out some information for each user.
+ print('User with ID "%d" and name "%s" was found.\n' % (user['id'],
+ user['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/user_service/get_current_user.py b/examples/ad_manager/v202208/user_service/get_current_user.py
new file mode 100755
index 00000000..b193dbac
--- /dev/null
+++ b/examples/ad_manager/v202208/user_service/get_current_user.py
@@ -0,0 +1,38 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets the current user."""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ user_service = client.GetService('UserService', version='v202208')
+
+ # Get current user.
+ user = user_service.getCurrentUser()
+
+ print('User with ID %d, name "%s", email "%s", and role "%s" '
+ 'is the current user.' % (
+ user.id, user.name, user.email, user.roleName))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/user_service/get_user_by_email_address.py b/examples/ad_manager/v202208/user_service/get_user_by_email_address.py
new file mode 100755
index 00000000..5c58a665
--- /dev/null
+++ b/examples/ad_manager/v202208/user_service/get_user_by_email_address.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets users by email.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+EMAIL_ADDRESS = 'INSERT_EMAIL_ADDRESS_HERE'
+
+
+def main(client, email_address):
+ # Initialize appropriate service.
+ user_service = client.GetService('UserService', version='v202208')
+ # Create a statement to select users.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('email = :email')
+ .WithBindVariable('email', email_address))
+
+ # Retrieve a small amount of users at a time, paging
+ # through until all users have been retrieved.
+ while True:
+ response = user_service.getUsersByStatement(statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for user in response['results']:
+ # Print out some information for each user.
+ print('User with ID "%d" and name "%s" was found.\n' % (user['id'],
+ user['name']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, EMAIL_ADDRESS)
diff --git a/examples/ad_manager/v202208/user_service/update_users.py b/examples/ad_manager/v202208/user_service/update_users.py
new file mode 100755
index 00000000..12446965
--- /dev/null
+++ b/examples/ad_manager/v202208/user_service/update_users.py
@@ -0,0 +1,58 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example updates a user by adding " Sr." to the end of their name.
+
+To determine which users exist, run get_all_users.py.
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+USER_ID = 'INSERT_USER_ID_TO_UPDATE_HERE'
+
+
+def main(client, user_id):
+ # Initialize appropriate service.
+ user_service = client.GetService('UserService', version='v202208')
+
+ # Create query.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('id = :userId')
+ .WithBindVariable('userId', int(user_id)))
+
+ # Get users by statement.
+ response = user_service.getUsersByStatement(statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ users = response['results']
+ for user in users:
+ user['name'] += ' Sr.'
+
+ # Update users on server.
+ users = user_service.updateUsers(users)
+ for user in users:
+ print('User with id "%s" and name "%s" was updated.'
+ % (user['id'], user['name']))
+ else:
+ print('No users found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, USER_ID)
diff --git a/examples/ad_manager/v202208/user_team_association_service/__init__.py b/examples/ad_manager/v202208/user_team_association_service/__init__.py
new file mode 100755
index 00000000..3746cd33
--- /dev/null
+++ b/examples/ad_manager/v202208/user_team_association_service/__init__.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/examples/ad_manager/v202208/user_team_association_service/create_user_team_associations.py b/examples/ad_manager/v202208/user_team_association_service/create_user_team_associations.py
new file mode 100755
index 00000000..6e675a13
--- /dev/null
+++ b/examples/ad_manager/v202208/user_team_association_service/create_user_team_associations.py
@@ -0,0 +1,67 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example adds a user to a team by creating an association between them.
+
+To determine which teams exists, run get_all_teams.py. To determine which
+users exist, run get_all_users.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+TEAM_ID = 'INSERT_TEAM_ID_HERE'
+USER_IDS = ['INSERT_USER_IDS_TO_ASSOCIATE_TO_TEAM_HERE']
+
+
+def main(client, team_id, user_ids):
+ # Initialize appropriate service.
+ user_team_association_service = client.GetService(
+ 'UserTeamAssociationService', version='v202208')
+
+ user_team_associations = []
+ for user_id in user_ids:
+ user_team_associations.append(
+ {
+ 'teamId': team_id,
+ 'userId': user_id
+ })
+
+ # Create the user team association on the server.
+ user_team_associations = (
+ user_team_association_service.createUserTeamAssociations(
+ user_team_associations))
+
+ # Display results.
+ if user_team_associations:
+ for user_team_association in user_team_associations:
+ print('A user team association between user with ID "%s" and team with'
+ ' ID "%s"was created.' % (user_team_association['userId'],
+ user_team_association['teamId']))
+ else:
+ print('No user team associations created.')
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, TEAM_ID, USER_IDS)
diff --git a/examples/ad_manager/v202208/user_team_association_service/delete_user_team_associations.py b/examples/ad_manager/v202208/user_team_association_service/delete_user_team_associations.py
new file mode 100755
index 00000000..e21f623d
--- /dev/null
+++ b/examples/ad_manager/v202208/user_team_association_service/delete_user_team_associations.py
@@ -0,0 +1,77 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example removes the user from all its teams.
+
+To determine which users exist, run get_all_users.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+USER_ID = 'INSERT_USER_ID_HERE'
+
+
+def main(client, user_id):
+ # Initialize appropriate service.
+ user_team_association_service = client.GetService(
+ 'UserTeamAssociationService', version='v202208')
+
+ # Create filter text to select user team associations by the user ID.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('userId = :userId')
+ .WithBindVariable('userId', int(user_id)))
+
+ # Get user team associations by statement.
+ response = user_team_association_service.getUserTeamAssociationsByStatement(
+ statement.ToStatement())
+ user_team_associations = response['results'] if 'results' in response else []
+
+ for user_team_association in user_team_associations:
+ print('User team association between user with ID "%s" and team with '
+ 'ID "%s" will be deleted.' % (user_team_association['userId'],
+ user_team_association['teamId']))
+ print('Number of teams that the user will be removed from: %s' %
+ len(user_team_associations))
+
+ # Action doesn't require limit/offset
+ statement.limit = None
+ statement.offset = None
+
+ # Perform action.
+ result = user_team_association_service.performUserTeamAssociationAction(
+ {'xsi_type': 'DeleteUserTeamAssociations'},
+ statement.ToStatement())
+
+ # Display results.
+ if result and int(result['numChanges']) > 0:
+ print('Number of teams that the user was removed from: %s'
+ % result['numChanges'])
+ else:
+ print('No user team associations were deleted.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, USER_ID)
diff --git a/examples/ad_manager/v202208/user_team_association_service/get_all_user_team_associations.py b/examples/ad_manager/v202208/user_team_association_service/get_all_user_team_associations.py
new file mode 100755
index 00000000..88295627
--- /dev/null
+++ b/examples/ad_manager/v202208/user_team_association_service/get_all_user_team_associations.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all user team associations.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+
+def main(client):
+ # Initialize appropriate service.
+ user_team_association_service = client.GetService(
+ 'UserTeamAssociationService', version='v202208')
+
+ # Create a statement to select user team associations.
+ statement = ad_manager.StatementBuilder(version='v202208')
+
+ # Retrieve a small amount of user team associations at a time, paging
+ # through until all user team associations have been retrieved.
+ while True:
+ response = user_team_association_service.getUserTeamAssociationsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for user_team_association in response['results']:
+ # Print out some information for each user team association.
+ print('User team association with team id "%d" and user id "%d" was '
+ 'found.\n' % (user_team_association['teamId'],
+ user_team_association['userId']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client)
diff --git a/examples/ad_manager/v202208/user_team_association_service/get_user_team_associations_for_user.py b/examples/ad_manager/v202208/user_team_association_service/get_user_team_associations_for_user.py
new file mode 100755
index 00000000..bd1b7bba
--- /dev/null
+++ b/examples/ad_manager/v202208/user_team_association_service/get_user_team_associations_for_user.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""This example gets all user team associations (i.e. teams) for a given user.
+"""
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+USER_ID = 'INSERT_USER_ID_HERE'
+
+
+def main(client, user_id):
+ # Initialize appropriate service.
+ user_team_association_service = client.GetService(
+ 'UserTeamAssociationService', version='v202208')
+ # Create a statement to select user team associations.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('userId = :userId')
+ .WithBindVariable('userId', int(user_id)))
+
+ # Retrieve a small amount of user team associations at a time, paging
+ # through until all user team associations have been retrieved.
+ while True:
+ response = user_team_association_service.getUserTeamAssociationsByStatement(
+ statement.ToStatement())
+ if 'results' in response and len(response['results']):
+ for user_team_association in response['results']:
+ # Print out some information for each user team association.
+ print('User team association with user ID "%d" and team ID "%d" was '
+ 'found.\n' % (user_team_association['userId'],
+ user_team_association['teamId']))
+ statement.offset += statement.limit
+ else:
+ break
+
+ print('\nNumber of results found: %s' % response['totalResultSetSize'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, USER_ID)
diff --git a/examples/ad_manager/v202208/user_team_association_service/update_user_team_associations.py b/examples/ad_manager/v202208/user_team_association_service/update_user_team_associations.py
new file mode 100755
index 00000000..a781778d
--- /dev/null
+++ b/examples/ad_manager/v202208/user_team_association_service/update_user_team_associations.py
@@ -0,0 +1,78 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example updates user team associations.
+
+It updates a user team association by setting the overridden access type to read
+only for all teams that the user belongs to. To determine which users exists,
+run get_all_users.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import ad_manager
+
+USER_ID = 'INSERT_USER_ID_TO_UPDATE_HERE'
+
+
+def main(client, user_id):
+ # Initialize appropriate service.
+ user_team_association_service = client.GetService(
+ 'UserTeamAssociationService', version='v202208')
+
+ # Create filter text to select user team associations by the user ID.
+ statement = (ad_manager.StatementBuilder(version='v202208')
+ .Where('userId = :userId')
+ .WithBindVariable('userId', int(user_id)))
+
+ # Get user team associations by statement.
+ response = user_team_association_service.getUserTeamAssociationsByStatement(
+ statement.ToStatement())
+
+ if 'results' in response and len(response['results']):
+ updated_user_team_associations = []
+ # Update each local user team association to read only access.
+ for user_team_association in response['results']:
+ user_team_association['overriddenTeamAccessType'] = 'READ_ONLY'
+ updated_user_team_associations.append(user_team_association)
+
+ # Update user team associations on the server.
+ user_team_associations = (
+ user_team_association_service.updateUserTeamAssociations(
+ updated_user_team_associations))
+
+ # Display results.
+ if user_team_associations:
+ for user_team_association in user_team_associations:
+ print('User team association between user with ID "%s" and team with'
+ ' ID "%s" was updated.' % (user_team_association['userId'],
+ user_team_association['teamId']))
+ else:
+ print('No user team associations were updated.')
+ else:
+ print('No user team associations found to update.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
+ main(ad_manager_client, USER_ID)
diff --git a/examples/adwords/adwords_appengine_demo/COPYING b/examples/adwords/adwords_appengine_demo/COPYING
old mode 100644
new mode 100755
diff --git a/examples/adwords/adwords_appengine_demo/ChangeLog b/examples/adwords/adwords_appengine_demo/ChangeLog
old mode 100644
new mode 100755
index d2856ece..122ba206
--- a/examples/adwords/adwords_appengine_demo/ChangeLog
+++ b/examples/adwords/adwords_appengine_demo/ChangeLog
@@ -1,6 +1,14 @@
-1.0.1 - 1/5/2015
-- Updated dependencies listed in README, for the changes introduced in googleads
- 3.0.0.
+1.0.3 -- 5/15/18:
+- Fixed issue #273:
+ https://github.com/googleads/googleads-python-lib/issues/273
+
+1.0.2 -- 6/21/16:
+- Fixed issue #171:
+ https://github.com/googleads/googleads-python-lib/issues/171
+
+1.0.1 -- 1/5/15:
+- Updated dependencies listed in README, for the changes introduced in
+ googleads 3.0.0.
1.0.0:
-- Initial release of the demo.
\ No newline at end of file
+- Initial release of the demo.
diff --git a/examples/adwords/adwords_appengine_demo/README b/examples/adwords/adwords_appengine_demo/README
deleted file mode 100644
index 6885f0e6..00000000
--- a/examples/adwords/adwords_appengine_demo/README
+++ /dev/null
@@ -1,114 +0,0 @@
-# Python AdWords App Engine Demo
-
-Google's AdWords API lets developers design computer programs that
-interact directly with the AdWords platform. With these applications,
-advertisers and third parties can more efficiently—and creatively—manage
-their large or complex AdWords accounts and campaigns.
-
-App Engine offers a complete development stack that uses familiar technologies
-to build and host web applications.
-
-In order for the web application to communicate with AdWords API, we will use
-the [Google Ads Python Client Library](https://github.com/googleads/googleads-python-lib).
-
-In this demo, a user signs in and provides their MCC Client Customer Id and
-other credentials that are used to access the AdWords API and provide the
-following functionality:
-
-* Retrieve and list client accounts.
-* Retrieve and list the Campaigns for a given client account.
-* Add new campaigns to a given client account.
-* Retrieve and list the AdGroups for a given Campaign.
-* Add new AdGroups to a given Campaign.
-* Modify the Budget for a given campaign.
-
-SOAP requests can take some time to complete - longer than Google App Engine
-will allow. For production-grade web applications, we recommend using the
-Task Queue API to handle requests asynchronously. You can read more about this
-[here](https://developers.google.com/appengine/docs/python/taskqueue/).
-
-
-## Step-by-step guide for using AdWords API demo on App Engine:
-
-This guide assumes that you have already set up your AdWords account and have
-prepared your OAuth2 Credentials via the Google Developers Console.
-
-1. Install Python v2.7, which you can get
- [here](https://www.python.org/downloads).
-
-2. Install [pip](http://pip.readthedocs.org/en/latest/installing.html),
- if you have not done so already.
-
-3. If you don't have one already,
- [sign up for a Google Account](https://www.google.com/accounts/NewAccount).
- This account will be used to access your AdWords credentials used in making
- API requests.
-
-4. Download the latest version of the
- [App Engine SDK](https://developers.google.com/appengine/downloads) and
- unpack its content. This demo should be compatible with v1.9.11+.
-
-5. Install googleads with the following command:
-
- `$ pip install googleads`
-
- Then copy the googleads package from your Python installation's
- dist-packages directory into this project. The installation of googleads
- should also have installed the dependencies referred to in the following
- steps.
-
-6. Copy the httplib2 package from your Python installation's dist-packages
- directory into this project.
-
-7. Copy the oauth2client package from your Python installation's dist-packages
- directory into this project.
-
-8. Copy the pytz package from your Python installation's dist-packages
- directory into this project.
-
-9. Copy socks.py from the PySocks tarball found in your Python installation's
- dist-packages directory into this project.
-
-10. Copy the suds package from your Python installation's dist-packages
- directory into this project.
-
-11. Create an App Engine application in the
- [Google App Engine Console](https://appengine.google.com/).
-
-12. Go to this project's app.yaml, and enter in your application name for the
- "application" field.
-
-13. You can now deploy this project by running the following command:
-
- `python $APPENGINE_SDK_DIR/appcfg --oauth2 update .`
-
-14. When you go to your App for the first time, you will need to log in and
- provide OAuth2 and AdWords API credentials. You can use credentials
- generated via the generate_refresh_token.py example.
-
-15. With all information entered, you can now use the UI to view and modify
- your account details.
-
-
-## Where do I submit bug reports and/or feature requests?
-
-Submit bug reports or feature requests to our
-[issue tracker](https://github.com/googleads/googleads-python-lib/issues).
-
-
-## External Dependencies:
-
-* [Python v2.7](https://www.python.org/downloads/)
-* [httplib2 v0.9+](https://pypi.python.org/pypi/httplib2)
-* [oauth2client v1.4.5+](https://pypi.python.org/pypi/oauth2client/)
-* [pysocks v1.5.0+](https://pypi.python.org/pypi/PySocks/)
-* [pytz 2014.7+](https://pypi.python.org/pypi/pytz)
-* [suds-jurko 0.6+](https://pypi.python.org/pypi/suds-jurko)
-* [App Engine SDK v1.9.11+](https://developers.google.com/appengine/downloads)
-* [Google Ads Python Client Library v2.1.0+](https://github.com/googleads/googleads-python-lib)
-* [Google Account](https://www.google.com/accounts/NewAccount)
-
-
-### Author:
-
-api.msaniscalchi@gmail.com (Mark Saniscalchi)
\ No newline at end of file
diff --git a/examples/adwords/adwords_appengine_demo/README.md b/examples/adwords/adwords_appengine_demo/README.md
new file mode 100755
index 00000000..fd25c97e
--- /dev/null
+++ b/examples/adwords/adwords_appengine_demo/README.md
@@ -0,0 +1,102 @@
+# Python AdWords App Engine Demo
+
+Google's AdWords API lets developers design computer programs that
+interact directly with the AdWords platform. With these applications,
+advertisers and third parties can more efficiently—and creatively—manage
+their large or complex AdWords accounts and campaigns.
+
+App Engine offers a complete development stack that uses familiar technologies
+to build and host web applications.
+
+In order for the web application to communicate with AdWords API, we will use
+the [Google Ads Python Client Library](https://github.com/googleads/googleads-python-lib).
+
+In this demo, a user signs in and provides their AdWords manager account id and
+other credentials that are used to access the AdWords API and provide the
+following functionality:
+
+* Retrieve and list client accounts.
+* Retrieve and list the Campaigns for a given client account.
+* Add new campaigns to a given client account.
+* Retrieve and list the AdGroups for a given Campaign.
+* Add new AdGroups to a given Campaign.
+* Modify the Budget for a given campaign.
+
+SOAP requests can take some time to complete - longer than Google App Engine
+will allow. For production-grade web applications, we recommend using the
+Task Queue API to handle requests asynchronously. You can read more about this
+[here](https://developers.google.com/appengine/docs/python/taskqueue/).
+
+
+## Step-by-step guide for using AdWords API demo on App Engine:
+
+This guide assumes that you have already set up your AdWords account and have
+prepared your OAuth2 Credentials via the Google Developers Console.
+
+1. Install Python v3.6 or higher, which you can get
+ [here](https://www.python.org/downloads).
+
+1. Install [pip](http://pip.readthedocs.org/en/latest/installing.html),
+ if you have not done so already.
+
+1. If you don't have one already,
+ [sign up for a Google Account](https://www.google.com/accounts/NewAccount).
+ This account will be used to access your AdWords credentials used in making
+ API requests.
+
+1. Install the [Google Cloud SDK](https://cloud.google.com/sdk/downloads).
+
+1. Install googleads ands its dependencies locally with the following command,
+ executed from this file's parent directory:
+
+ `$ pip install -r requirements.txt -t lib`
+
+1. If you don't already have one, create a new project in the
+ [Google Cloud Console](https://console.cloud.google.com). Note the Project
+ ID, which you will need in the next step.
+
+1. Configure the Google Cloud SDK with the following steps:
+
+ * While logged into the Google Account you used to create your project, run
+ the following command:
+
+ `gcloud auth login`
+
+ * Set your project as the current project with the following command:
+
+ `gcloud config set project ENTER_PROJECT_ID_HERE`
+
+1. You can now deploy this application by running the following command:
+
+ `gcloud app deploy app.yaml -v v1`
+
+1. To view your application in your web browser, run the following command:
+
+ `gcloud app browse`
+
+1. When you go to your App for the first time, you will need to log in and
+ provide OAuth2 and AdWords API credentials. You can use credentials
+ generated via the generate_refresh_token.py example.
+
+1. With all information entered, you can now use the UI to view and modify
+ your account details.
+
+
+## Where do I submit bug reports and/or feature requests?
+
+Submit bug reports or feature requests to our
+[issue tracker](https://github.com/googleads/googleads-python-lib/issues).
+
+
+## External Dependencies:
+
+* [Python v3.6+](https://www.python.org/downloads/)
+* [httplib2 v0.9+](https://pypi.python.org/pypi/httplib2)
+* [oauth2client v4.0.0+](https://pypi.python.org/pypi/oauth2client/)
+* [pysocks v1.5.0+](https://pypi.python.org/pypi/PySocks/)
+* [pytz 2014.7+](https://pypi.python.org/pypi/pytz)
+* [PyYAML 3.11+](https://pypi.python.org/pypi/PyYAML)
+* [xmltodict 0.9.2+](https://pypi.python.org/pypi/xmltodict)
+* [App Engine SDK v1.9.11+](https://developers.google.com/appengine/downloads)
+* [Google Ads Python Client Library v10.1.0+](https://github.com/googleads/googleads-python-lib)
+* [Google Account](https://www.google.com/accounts/NewAccount)
diff --git a/examples/adwords/adwords_appengine_demo/__init__.py b/examples/adwords/adwords_appengine_demo/__init__.py
index be307921..38deb3b8 100755
--- a/examples/adwords/adwords_appengine_demo/__init__.py
+++ b/examples/adwords/adwords_appengine_demo/__init__.py
@@ -1,4 +1,4 @@
-#!/usr/bin/python
+#!/usr/bin/env python
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
diff --git a/examples/adwords/adwords_appengine_demo/app.yaml b/examples/adwords/adwords_appengine_demo/app.yaml
old mode 100644
new mode 100755
index 4649e559..9f42af24
--- a/examples/adwords/adwords_appengine_demo/app.yaml
+++ b/examples/adwords/adwords_appengine_demo/app.yaml
@@ -1,5 +1,4 @@
-application: INSERT_APP_NAME_HERE
-version: 1
+service: default
runtime: python27
api_version: 1
threadsafe: false
@@ -13,3 +12,9 @@ handlers:
script: demo.main.app
login: required
secure: always
+
+libraries:
+- name: ssl
+ version: latest
+- name: lxml
+ version: latest
diff --git a/examples/adwords/adwords_appengine_demo/appengine_config.py b/examples/adwords/adwords_appengine_demo/appengine_config.py
new file mode 100755
index 00000000..80144509
--- /dev/null
+++ b/examples/adwords/adwords_appengine_demo/appengine_config.py
@@ -0,0 +1,24 @@
+#!/usr/bin/env python
+#
+# Copyright 2018 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Configuration module for the AdWords App Engine demo."""
+
+
+import os
+from google.appengine.ext import vendor
+
+# Add any libraries installed in the "lib" folder to the path.
+vendor.add(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'lib'))
diff --git a/examples/adwords/adwords_appengine_demo/demo/__init__.py b/examples/adwords/adwords_appengine_demo/demo/__init__.py
index 71de3769..cb442cd4 100755
--- a/examples/adwords/adwords_appengine_demo/demo/__init__.py
+++ b/examples/adwords/adwords_appengine_demo/demo/__init__.py
@@ -1,4 +1,4 @@
-#!/usr/bin/python
+#!/usr/bin/env python
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
@@ -15,8 +15,5 @@
# limitations under the License.
"""AdWords App Engine demo web application."""
-__author__ = 'Mark Saniscalchi'
-
-
DEBUG = False # Enable to see debug logs in the App Engine console.
-VERSION = '1.0.0'
+VERSION = '1.0.3'
diff --git a/examples/adwords/adwords_appengine_demo/demo/main.py b/examples/adwords/adwords_appengine_demo/demo/main.py
index b0890637..466a788c 100755
--- a/examples/adwords/adwords_appengine_demo/demo/main.py
+++ b/examples/adwords/adwords_appengine_demo/demo/main.py
@@ -1,4 +1,4 @@
-#!/usr/bin/python
+#!/usr/bin/env python
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
@@ -18,9 +18,9 @@
Configures the web application that will display the AdWords UI.
"""
-__author__ = 'Mark Saniscalchi'
from demo import DEBUG
+from requests_toolbelt.adapters import appengine
from views import AddAdGroup
from views import AddCampaign
from views import InitView
@@ -33,6 +33,8 @@
from views import UpdateCredentials
import webapp2
+# Patch requests library for use on App Engine.
+appengine.monkeypatch()
app = webapp2.WSGIApplication([('/', InitView),
('/showCredentials', ShowCredentials),
diff --git a/examples/adwords/adwords_appengine_demo/handlers/__init__.py b/examples/adwords/adwords_appengine_demo/handlers/__init__.py
index 0f5dabe3..a186d331 100755
--- a/examples/adwords/adwords_appengine_demo/handlers/__init__.py
+++ b/examples/adwords/adwords_appengine_demo/handlers/__init__.py
@@ -1,4 +1,4 @@
-#!/usr/bin/python
+#!/usr/bin/env python
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
diff --git a/examples/adwords/adwords_appengine_demo/handlers/api_handler.py b/examples/adwords/adwords_appengine_demo/handlers/api_handler.py
index f69cb0d0..51578742 100755
--- a/examples/adwords/adwords_appengine_demo/handlers/api_handler.py
+++ b/examples/adwords/adwords_appengine_demo/handlers/api_handler.py
@@ -1,4 +1,4 @@
-#!/usr/bin/python
+#!/usr/bin/env python
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
@@ -15,13 +15,12 @@
# limitations under the License.
"""Handler to make calls against the AdWords API."""
-__author__ = 'Mark Saniscalchi'
import time
-
from demo import VERSION
from googleads.adwords import AdWordsClient
+from googleads.common import ZeepServiceProxy
from googleads.errors import GoogleAdsError
from googleads.oauth2 import GoogleRefreshTokenClient
@@ -32,21 +31,22 @@ class APIHandler(object):
# The user-agent sent in requests from this demo.
_USER_AGENT = 'AppEngine Googleads Demo v%s' % VERSION
- def __init__(self, client_id, client_secret, refresh_token, mcc_cid,
- dev_token):
+ def __init__(self, client_id, client_secret, refresh_token,
+ manager_account_id, dev_token):
"""Initializes an APIHandler.
Args:
client_id: The client customer id retrieved from the Developers Console.
client_secret: The client secret retrieved from the Developers Console.
refresh_token: The refresh token retrieved with generate_refresh_token.py.
- mcc_cid: The AdWords MCC Account Client Customer Id.
+ manager_account_id: The AdWords manager account Id.
dev_token: The AdWords Developer Token.
"""
credentials = GoogleRefreshTokenClient(client_id, client_secret,
refresh_token)
self.client = AdWordsClient(dev_token, credentials, self._USER_AGENT,
- mcc_cid)
+ client_customer_id=manager_account_id,
+ cache=ZeepServiceProxy.NO_CACHE)
def AddAdGroup(self, client_customer_id, campaign_id, name, status):
"""Create a new ad group.
@@ -88,7 +88,6 @@ def AddBudget(self, client_customer_id, micro_amount):
'operator': 'ADD',
'operand': {
'name': 'Budget #%s' % time.time(),
- 'period': 'DAILY',
'amount': {
'microAmount': micro_amount
},
@@ -134,7 +133,7 @@ def AddCampaign(self, client_customer_id, campaign_name, ad_channel_type,
campaign_service.mutate(operations)
def GetAccounts(self):
- """Return the client accounts associated with the user's MCC account.
+ """Return the client accounts associated with the user's manager account.
Returns:
list List of ManagedCustomer data objects.
@@ -225,7 +224,7 @@ def GetCampaigns(self, client_customer_id):
# and is taking too long.
max_tries = 3
today = time.strftime('%Y%m%d', time.localtime())
- for i in xrange(1, max_tries + 1):
+ for i in range(1, max_tries + 1):
try:
selector = {
'fields': ['Id', 'Name', 'Status', 'BudgetId', 'Amount'],
@@ -246,7 +245,7 @@ def GetCampaigns(self, client_customer_id):
return campaigns['entries']
else:
return None
- except Exception, e:
+ except Exception as e:
if i == max_tries:
raise GoogleAdsError(e)
continue
diff --git a/examples/adwords/adwords_appengine_demo/handlers/ndb_handler.py b/examples/adwords/adwords_appengine_demo/handlers/ndb_handler.py
index 1524c61e..897f82da 100755
--- a/examples/adwords/adwords_appengine_demo/handlers/ndb_handler.py
+++ b/examples/adwords/adwords_appengine_demo/handlers/ndb_handler.py
@@ -1,4 +1,4 @@
-#!/usr/bin/python
+#!/usr/bin/env python
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
@@ -16,7 +16,6 @@
"""Handler for ndb transactions."""
-__author__ = 'Mark Saniscalchi'
from models.app_user import AppUser
@@ -43,15 +42,15 @@ def InitUser():
return app_user
-def UpdateUserCredentials(client_id, client_secret, refresh_token, mcc_cid,
- developer_token):
+def UpdateUserCredentials(client_id, client_secret, refresh_token,
+ adwords_manager_cid, developer_token):
"""Update the credentials associated with application user.
Args:
client_id: str Client Id retrieved from the developer's console.
client_secret: str Client Secret retrieved from the developer's console.
refresh_token: str Refresh token generated with the above client id/secret.
- mcc_cid: str Customer Id for the AdWords MCC account.
+ adwords_manager_cid: str Customer Id for the AdWords manager account.
developer_token: str Developer Token for the AdWords account.
"""
app_user = AppUser.query(AppUser.user == users.get_current_user()).fetch()[0]
@@ -59,7 +58,7 @@ def UpdateUserCredentials(client_id, client_secret, refresh_token, mcc_cid,
app_user.client_id = client_id
app_user.client_secret = client_secret
app_user.refresh_token = refresh_token
- app_user.mcc_cid = mcc_cid
+ app_user.adwords_manager_cid = adwords_manager_cid
app_user.developer_token = developer_token
app_user.put()
diff --git a/examples/adwords/adwords_appengine_demo/js/scripts.js b/examples/adwords/adwords_appengine_demo/js/scripts.js
old mode 100644
new mode 100755
diff --git a/examples/adwords/adwords_appengine_demo/models/__init__.py b/examples/adwords/adwords_appengine_demo/models/__init__.py
index af1c9f8f..2eba7921 100755
--- a/examples/adwords/adwords_appengine_demo/models/__init__.py
+++ b/examples/adwords/adwords_appengine_demo/models/__init__.py
@@ -1,4 +1,4 @@
-#!/usr/bin/python
+#!/usr/bin/env python
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
diff --git a/examples/adwords/adwords_appengine_demo/models/app_user.py b/examples/adwords/adwords_appengine_demo/models/app_user.py
index ef710c3a..56004b17 100755
--- a/examples/adwords/adwords_appengine_demo/models/app_user.py
+++ b/examples/adwords/adwords_appengine_demo/models/app_user.py
@@ -1,4 +1,4 @@
-#!/usr/bin/python
+#!/usr/bin/env python
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
@@ -16,7 +16,6 @@
"""Model representing a user of the application."""
-__author__ = 'Mark Saniscalchi'
from google.appengine.ext import ndb
@@ -33,5 +32,5 @@ class AppUser(ndb.Model):
client_id = ndb.StringProperty(required=False)
client_secret = ndb.StringProperty(required=False)
refresh_token = ndb.StringProperty(required=False)
- mcc_cid = ndb.StringProperty(required=False)
+ adwords_manager_cid = ndb.StringProperty(required=False)
developer_token = ndb.StringProperty(required=False)
diff --git a/examples/adwords/adwords_appengine_demo/requirements.txt b/examples/adwords/adwords_appengine_demo/requirements.txt
new file mode 100755
index 00000000..64e96f18
--- /dev/null
+++ b/examples/adwords/adwords_appengine_demo/requirements.txt
@@ -0,0 +1 @@
+googleads==12.0.0
diff --git a/examples/adwords/adwords_appengine_demo/stylesheets/styles.css b/examples/adwords/adwords_appengine_demo/stylesheets/styles.css
old mode 100644
new mode 100755
diff --git a/examples/adwords/adwords_appengine_demo/templates/base_template.html b/examples/adwords/adwords_appengine_demo/templates/base_template.html
old mode 100644
new mode 100755
diff --git a/examples/adwords/adwords_appengine_demo/templates/show_accounts.html b/examples/adwords/adwords_appengine_demo/templates/show_accounts.html
old mode 100644
new mode 100755
diff --git a/examples/adwords/adwords_appengine_demo/templates/show_adgroups.html b/examples/adwords/adwords_appengine_demo/templates/show_adgroups.html
old mode 100644
new mode 100755
diff --git a/examples/adwords/adwords_appengine_demo/templates/show_budget.html b/examples/adwords/adwords_appengine_demo/templates/show_budget.html
old mode 100644
new mode 100755
diff --git a/examples/adwords/adwords_appengine_demo/templates/show_campaigns.html b/examples/adwords/adwords_appengine_demo/templates/show_campaigns.html
old mode 100644
new mode 100755
diff --git a/examples/adwords/adwords_appengine_demo/templates/show_credentials.html b/examples/adwords/adwords_appengine_demo/templates/show_credentials.html
old mode 100644
new mode 100755
index 3acafc8f..f7edda4a
--- a/examples/adwords/adwords_appengine_demo/templates/show_credentials.html
+++ b/examples/adwords/adwords_appengine_demo/templates/show_credentials.html
@@ -23,9 +23,9 @@
value="{{ refresh_token }}"/>
-
-
+
+
@@ -39,4 +39,4 @@
-{% endblock %}
\ No newline at end of file
+{% endblock %}
diff --git a/examples/adwords/adwords_appengine_demo/templates/toggle_menu_template.html b/examples/adwords/adwords_appengine_demo/templates/toggle_menu_template.html
old mode 100644
new mode 100755
diff --git a/examples/adwords/adwords_appengine_demo/views/__init__.py b/examples/adwords/adwords_appengine_demo/views/__init__.py
index 42f315ed..eadfba45 100755
--- a/examples/adwords/adwords_appengine_demo/views/__init__.py
+++ b/examples/adwords/adwords_appengine_demo/views/__init__.py
@@ -1,4 +1,4 @@
-#!/usr/bin/python
+#!/usr/bin/env python
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
@@ -16,7 +16,6 @@
"""Views for the web application."""
-__author__ = 'Mark Saniscalchi'
from add_adgroup_view import AddAdGroup
from add_campaign_view import AddCampaign
diff --git a/examples/adwords/adwords_appengine_demo/views/add_adgroup_view.py b/examples/adwords/adwords_appengine_demo/views/add_adgroup_view.py
index 011f5553..7660cb0e 100755
--- a/examples/adwords/adwords_appengine_demo/views/add_adgroup_view.py
+++ b/examples/adwords/adwords_appengine_demo/views/add_adgroup_view.py
@@ -1,4 +1,4 @@
-#!/usr/bin/python
+#!/usr/bin/env python
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
@@ -16,7 +16,6 @@
"""Handles request to add an AdGroup to a Campaign."""
-__author__ = 'Mark Saniscalchi'
import os
@@ -50,7 +49,7 @@ def post(self):
handler = APIHandler(app_user.client_id,
app_user.client_secret,
app_user.refresh_token,
- app_user.mcc_cid,
+ app_user.adwords_manager_cid,
app_user.developer_token)
# Create new ad group.
@@ -59,7 +58,7 @@ def post(self):
self.redirect('/showAdGroups?clientCustomerId=%s&campaignId=%s'
% (client_customer_id, campaign_id))
- except Exception, e:
+ except Exception as e:
template_values['error'] = str(e)
# Use template to write output to the page.
path = os.path.join(os.path.dirname(__file__),
diff --git a/examples/adwords/adwords_appengine_demo/views/add_campaign_view.py b/examples/adwords/adwords_appengine_demo/views/add_campaign_view.py
index 5b01c7f7..72e442ed 100755
--- a/examples/adwords/adwords_appengine_demo/views/add_campaign_view.py
+++ b/examples/adwords/adwords_appengine_demo/views/add_campaign_view.py
@@ -1,4 +1,4 @@
-#!/usr/bin/python
+#!/usr/bin/env python
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
@@ -16,7 +16,6 @@
"""Handles request to add a Campaign to a client account."""
-__author__ = 'Mark Saniscalchi'
import os
@@ -50,7 +49,7 @@ def post(self):
handler = APIHandler(app_user.client_id,
app_user.client_secret,
app_user.refresh_token,
- app_user.mcc_cid,
+ app_user.adwords_manager_cid,
app_user.developer_token)
# Create new campaign.
@@ -58,7 +57,7 @@ def post(self):
ad_channel_type, budget)
self.redirect('/showCampaigns?clientCustomerId=%s' % client_customer_id)
- except Exception, e:
+ except Exception as e:
template_values['error'] = str(e)
# Use template to write output to the page.
path = os.path.join(os.path.dirname(__file__),
diff --git a/examples/adwords/adwords_appengine_demo/views/init_view.py b/examples/adwords/adwords_appengine_demo/views/init_view.py
index d051fb4b..9f4038c1 100755
--- a/examples/adwords/adwords_appengine_demo/views/init_view.py
+++ b/examples/adwords/adwords_appengine_demo/views/init_view.py
@@ -1,4 +1,4 @@
-#!/usr/bin/python
+#!/usr/bin/env python
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
@@ -16,7 +16,6 @@
"""View at the root directory of the application."""
-__author__ = 'Mark Saniscalchi'
import logging
@@ -33,10 +32,10 @@ def get(self):
app_user = InitUser()
if (app_user.client_id and app_user.client_secret and
- app_user.mcc_cid and app_user.developer_token and
+ app_user.adwords_manager_cid and app_user.developer_token and
app_user.refresh_token):
self.redirect('/showAccounts')
else:
self.redirect('/showCredentials')
- except Exception, e:
+ except Exception as e:
logging.debug(str(e))
diff --git a/examples/adwords/adwords_appengine_demo/views/show_accounts_view.py b/examples/adwords/adwords_appengine_demo/views/show_accounts_view.py
index 43cce8dd..debc0a0d 100755
--- a/examples/adwords/adwords_appengine_demo/views/show_accounts_view.py
+++ b/examples/adwords/adwords_appengine_demo/views/show_accounts_view.py
@@ -1,4 +1,4 @@
-#!/usr/bin/python
+#!/usr/bin/env python
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
@@ -14,9 +14,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-"""Handles request to view accounts associated with MCC Cluent Customer Id."""
+"""Handles request to view accounts associated with manager account Id."""
-__author__ = 'Mark Saniscalchi'
import os
@@ -29,7 +28,7 @@
class ShowAccounts(webapp2.RequestHandler):
- """View showing the client accounts for a given MCC Client Customer Id."""
+ """View showing the client accounts for a given manager account Id."""
def get(self):
"""Handle get request."""
@@ -47,12 +46,12 @@ def get(self):
handler = APIHandler(app_user.client_id,
app_user.client_secret,
app_user.refresh_token,
- app_user.mcc_cid,
+ app_user.adwords_manager_cid,
app_user.developer_token)
# Fetch account info for each client account and place in template.
template_values['accounts'] = handler.GetAccounts()
- except Exception, e:
+ except Exception as e:
template_values['error'] = str(e)
finally:
# Use template to write output to the page.
diff --git a/examples/adwords/adwords_appengine_demo/views/show_adgroups_view.py b/examples/adwords/adwords_appengine_demo/views/show_adgroups_view.py
index cb7abf55..fa9397b8 100755
--- a/examples/adwords/adwords_appengine_demo/views/show_adgroups_view.py
+++ b/examples/adwords/adwords_appengine_demo/views/show_adgroups_view.py
@@ -1,4 +1,4 @@
-#!/usr/bin/python
+#!/usr/bin/env python
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
@@ -16,7 +16,6 @@
"""Handles request to view the AdGroups associated with a given Campaign."""
-__author__ = 'Mark Saniscalchi'
import os
@@ -51,13 +50,13 @@ def get(self):
handler = APIHandler(app_user.client_id,
app_user.client_secret,
app_user.refresh_token,
- app_user.mcc_cid,
+ app_user.adwords_manager_cid,
app_user.developer_token)
adgroups = handler.GetAdGroups(client_customer_id, campaign_id)
# Use template to write output to the page.
template_values['adgroups'] = adgroups
- except Exception, e:
+ except Exception as e:
template_values['error'] = str(e)
finally:
path = os.path.join(os.path.dirname(__file__),
diff --git a/examples/adwords/adwords_appengine_demo/views/show_budget_view.py b/examples/adwords/adwords_appengine_demo/views/show_budget_view.py
index c4cb2a8a..543fdbc9 100755
--- a/examples/adwords/adwords_appengine_demo/views/show_budget_view.py
+++ b/examples/adwords/adwords_appengine_demo/views/show_budget_view.py
@@ -1,4 +1,4 @@
-#!/usr/bin/python
+#!/usr/bin/env python
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
@@ -16,7 +16,6 @@
"""Handles request to view a Campaign's budget."""
-__author__ = 'Mark Saniscalchi'
import os
@@ -53,13 +52,13 @@ def get(self):
handler = APIHandler(app_user.client_id,
app_user.client_secret,
app_user.refresh_token,
- app_user.mcc_cid,
+ app_user.adwords_manager_cid,
app_user.developer_token)
budget = handler.GetBudget(client_customer_id, budget_id)
# Use template to write output to the page.
template_values['budget'] = budget
- except Exception, e:
+ except Exception as e:
template_values['error'] = str(e)
finally:
path = os.path.join(os.path.dirname(__file__),
diff --git a/examples/adwords/adwords_appengine_demo/views/show_campaigns_view.py b/examples/adwords/adwords_appengine_demo/views/show_campaigns_view.py
index da09fa47..1101c2f1 100755
--- a/examples/adwords/adwords_appengine_demo/views/show_campaigns_view.py
+++ b/examples/adwords/adwords_appengine_demo/views/show_campaigns_view.py
@@ -1,4 +1,4 @@
-#!/usr/bin/python
+#!/usr/bin/env python
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
@@ -16,7 +16,6 @@
"""Handles request to view Campaigns associated with a given client account."""
-__author__ = 'Mark Saniscalchi'
import os
@@ -51,11 +50,11 @@ def get(self):
handler = APIHandler(app_user.client_id,
app_user.client_secret,
app_user.refresh_token,
- app_user.mcc_cid,
+ app_user.adwords_manager_cid,
app_user.developer_token)
campaigns = handler.GetCampaigns(client_customer_id)
- except Exception, e:
+ except Exception as e:
template_values['error'] = str(e)
finally:
# Use template to write output to the page.
diff --git a/examples/adwords/adwords_appengine_demo/views/show_credentials_view.py b/examples/adwords/adwords_appengine_demo/views/show_credentials_view.py
index 38588dcd..e2fbf543 100755
--- a/examples/adwords/adwords_appengine_demo/views/show_credentials_view.py
+++ b/examples/adwords/adwords_appengine_demo/views/show_credentials_view.py
@@ -1,4 +1,4 @@
-#!/usr/bin/python
+#!/usr/bin/env python
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
@@ -15,7 +15,6 @@
# limitations under the License.
"""Handles requests to view the user's credentials."""
-__author__ = 'Mark Saniscalchi'
import os
@@ -48,11 +47,12 @@ def get(self):
app_user.client_secret else '')
template_values['refresh_token'] = (app_user.refresh_token if
app_user.refresh_token else '')
- template_values['mcc_cid'] = (app_user.mcc_cid if app_user.mcc_cid
- else '')
+ template_values['adwords_manager_cid'] = (
+ app_user.adwords_manager_cid if app_user.adwords_manager_cid else ''
+ )
template_values['dev_token'] = (app_user.developer_token if
app_user.developer_token else '')
- except Exception, e:
+ except Exception as e:
template_values['error'] = str(e)
finally:
# Use template to write output to the page.
diff --git a/examples/adwords/adwords_appengine_demo/views/update_budget_view.py b/examples/adwords/adwords_appengine_demo/views/update_budget_view.py
index 11e54864..51c8db7c 100755
--- a/examples/adwords/adwords_appengine_demo/views/update_budget_view.py
+++ b/examples/adwords/adwords_appengine_demo/views/update_budget_view.py
@@ -1,4 +1,4 @@
-#!/usr/bin/python
+#!/usr/bin/env python
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
@@ -16,7 +16,6 @@
"""Handles requests to update a given Budget."""
-__author__ = 'Mark Saniscalchi'
import os
@@ -51,7 +50,7 @@ def post(self):
handler = APIHandler(app_user.client_id,
app_user.client_secret,
app_user.refresh_token,
- app_user.mcc_cid,
+ app_user.adwords_manager_cid,
app_user.developer_token)
# Update the Budget.
@@ -60,7 +59,7 @@ def post(self):
self.redirect('/showBudget?clientCustomerId=%s&budgetId=%s'
% (client_customer_id, budget_id))
- except Exception, e:
+ except Exception as e:
# Use template to write output to the page.
template_values['error'] = str(e)
path = os.path.join(os.path.dirname(__file__),
diff --git a/examples/adwords/adwords_appengine_demo/views/update_credentials_view.py b/examples/adwords/adwords_appengine_demo/views/update_credentials_view.py
index 9c732019..4b2a4af5 100755
--- a/examples/adwords/adwords_appengine_demo/views/update_credentials_view.py
+++ b/examples/adwords/adwords_appengine_demo/views/update_credentials_view.py
@@ -1,4 +1,4 @@
-#!/usr/bin/python
+#!/usr/bin/env python
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
@@ -16,7 +16,6 @@
"""Handles requests to update the current user's credentials."""
-__author__ = 'Mark Saniscalchi'
import os
@@ -42,10 +41,10 @@ def post(self):
UpdateUserCredentials(self.request.get('client_id'),
self.request.get('client_secret'),
self.request.get('refresh_token'),
- self.request.get('mcc_cid'),
+ self.request.get('adwords_manager_cid'),
self.request.get('dev_token'))
self.redirect('/showCredentials')
- except Exception, e:
+ except Exception as e:
template_values['error'] = str(e)
# Use template to write output to the page.
path = os.path.join(os.path.dirname(__file__),
diff --git a/examples/adwords/authentication/create_adwords_client_with_access_token.py b/examples/adwords/authentication/create_adwords_client_with_access_token.py
new file mode 100755
index 00000000..53b61d66
--- /dev/null
+++ b/examples/adwords/authentication/create_adwords_client_with_access_token.py
@@ -0,0 +1,86 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Initializes an AdWordsClient using GoogleAccessTokenClient.
+
+Note that unlike clients initialized with GoogleRefreshTokenClient, those
+initialized with GoogleAccessTokenClient can't refresh.
+"""
+
+import argparse
+import datetime
+from googleads import adwords
+from googleads import oauth2
+import httplib2
+from oauth2client import client
+
+
+GOOGLE_OAUTH2_ENDPOINT = 'https://accounts.google.com/o/oauth2/token'
+
+# OAuth2 credential information.
+DEFAULT_CLIENT_ID = 'INSERT_CLIENT_ID_HERE'
+DEFAULT_CLIENT_SECRET = 'INSERT_CLIENT_SECRET_HERE'
+DEFAULT_REFRESH_TOKEN = 'INSERT_REFRESH_TOKEN_HERE'
+
+# AdWords API information.
+DEFAULT_CLIENT_CUSTOMER_ID = 'INSERT_CLIENT_CUSTOMER_ID_HERE'
+DEFAULT_DEVELOPER_TOKEN = 'INSERT_DEVELOPER_TOKEN_HERE'
+USER_AGENT = 'INSERT_USER_AGENT_HERE'
+
+
+parser = argparse.ArgumentParser(
+ description=('Creates an AdWordsClient using a GoogleAccessToken with an '
+ 'access token generated with the given credentials.'))
+parser.add_argument('--client_id', default=DEFAULT_CLIENT_ID,
+ help='Client Id retrieved from the Developer\'s Console.')
+parser.add_argument('--client_secret', default=DEFAULT_CLIENT_SECRET,
+ help='Client Secret retrieved from the Developer\'s '
+ 'Console.')
+parser.add_argument('--refresh_token', default=DEFAULT_REFRESH_TOKEN,
+ help='The refresh token used to generate an access token.')
+parser.add_argument('--client_customer_id', default=DEFAULT_CLIENT_CUSTOMER_ID,
+ help='The client customer ID for your AdWords account.')
+parser.add_argument('--developer_token', default=DEFAULT_DEVELOPER_TOKEN,
+ help='The refresh token used to generate an access token.')
+
+
+def main(access_token, token_expiry, client_customer_id, developer_token,
+ user_agent):
+ oauth2_client = oauth2.GoogleAccessTokenClient(access_token, token_expiry)
+
+ adwords_client = adwords.AdWordsClient(
+ developer_token, oauth2_client, user_agent,
+ client_customer_id=client_customer_id)
+
+ customer = adwords_client.GetService('CustomerService').getCustomers()[0]
+ print('You are logged in as customer: %s' % customer['customerId'])
+
+
+if __name__ == '__main__':
+ args = parser.parse_args()
+
+ # Retrieve a new access token for use in this example. In a production
+ # application, you may use a credential store to share access tokens for a
+ # given user across applications.
+ oauth2credentials = client.OAuth2Credentials(
+ None, args.client_id, args.client_secret, args.refresh_token,
+ datetime.datetime(1980, 1, 1, 12), GOOGLE_OAUTH2_ENDPOINT,
+ USER_AGENT)
+
+ oauth2credentials.refresh(httplib2.Http())
+
+ main(oauth2credentials.access_token, oauth2credentials.token_expiry,
+ args.client_customer_id, args.developer_token, USER_AGENT)
diff --git a/examples/adwords/authentication/create_adwords_client_with_refresh_token.py b/examples/adwords/authentication/create_adwords_client_with_refresh_token.py
new file mode 100755
index 00000000..17bdeead
--- /dev/null
+++ b/examples/adwords/authentication/create_adwords_client_with_refresh_token.py
@@ -0,0 +1,62 @@
+#!/usr/bin/env python
+#
+# Copyright 2014 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Initializes an AdWordsClient without using yaml-cached credentials.
+
+While our LoadFromStorage method provides a useful shortcut to instantiate a
+client if you regularly use just one set of credentials, production applications
+may need to swap out users. This example shows you how to create an OAuth2
+client and an AdWordsClient without relying on a yaml file.
+"""
+
+
+from googleads import adwords
+from googleads import oauth2
+
+# OAuth2 credential information. In a real application, you'd probably be
+# pulling these values from a credential storage.
+CLIENT_ID = 'INSERT_CLIENT_ID_HERE'
+CLIENT_SECRET = 'INSERT_CLIENT_SECRET_HERE'
+REFRESH_TOKEN = 'INSERT_REFRESH_TOKEN_HERE'
+
+# AdWords API information.
+DEVELOPER_TOKEN = 'INSERT_DEVELOPER_TOKEN_HERE'
+USER_AGENT = 'INSERT_USER_AGENT_HERE'
+CLIENT_CUSTOMER_ID = 'INSERT_CLIENT_CUSTOMER_ID_HERE'
+
+
+def main(client_id, client_secret, refresh_token, developer_token, user_agent,
+ client_customer_id):
+ oauth2_client = oauth2.GoogleRefreshTokenClient(
+ client_id, client_secret, refresh_token)
+
+ adwords_client = adwords.AdWordsClient(
+ developer_token, oauth2_client, user_agent,
+ client_customer_id=client_customer_id)
+
+ customer_service = adwords_client.GetService('CustomerService',
+ version='v201702')
+ customers = customer_service.getCustomers()
+
+ print('You are logged in as a user with access to the following customers:')
+
+ for customer in customers:
+ print('\t%s' % customer['customerId'])
+
+
+if __name__ == '__main__':
+ main(CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN, DEVELOPER_TOKEN, USER_AGENT,
+ CLIENT_CUSTOMER_ID)
diff --git a/examples/adwords/authentication/create_adwords_client_with_service_account.py b/examples/adwords/authentication/create_adwords_client_with_service_account.py
index 24e46578..ef481b1f 100755
--- a/examples/adwords/authentication/create_adwords_client_with_service_account.py
+++ b/examples/adwords/authentication/create_adwords_client_with_service_account.py
@@ -1,4 +1,4 @@
-#!/usr/bin/python
+#!/usr/bin/env python
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
@@ -16,14 +16,12 @@
"""Initializes an AdWordsClient via impersonation using a Service Account."""
-__author__ = 'Mark Saniscalchi'
from googleads import adwords
from googleads import oauth2
-# OAuth 2.0 credential information. In a real application, you'd probably be
+# OAuth2 credential information. In a real application, you'd probably be
# pulling these values from a credential storage.
-SERVICE_ACCOUNT_EMAIL = 'INSERT_SERVICE_ACCOUNT_EMAIL_HERE'
KEY_FILE = 'INSERT_PATH_TO_KEY_FILE'
SERVICE_ACCOUNT_USER = 'INSERT_IMPERSONATED_EMAIL_HERE'
@@ -33,19 +31,25 @@
CLIENT_CUSTOMER_ID = 'INSERT_CLIENT_CUSTOMER_ID_HERE'
-def main(service_account_email, key_file, service_account_user,
- developer_token, user_agent, client_customer_id):
+def main(key_file, service_account_user, developer_token, user_agent,
+ client_customer_id):
oauth2_client = oauth2.GoogleServiceAccountClient(
- oauth2.GetAPIScope('adwords'), service_account_email, key_file,
- sub=service_account_user)
+ key_file, oauth2.GetAPIScope('adwords'), sub=service_account_user)
adwords_client = adwords.AdWordsClient(
- developer_token, oauth2_client, user_agent, client_customer_id)
+ developer_token, oauth2_client, user_agent,
+ client_customer_id=client_customer_id)
- customer = adwords_client.GetService('CustomerService').get()
- print 'You are logged in as customer: %s' % customer['customerId']
+ customer_service = adwords_client.GetService('CustomerService',
+ version='v201702')
+ customers = customer_service.getCustomers()
+
+ print('You are logged in as a user with access to the following customers:')
+
+ for customer in customers:
+ print('\t%s' % customer['customerId'])
if __name__ == '__main__':
- main(SERVICE_ACCOUNT_EMAIL, KEY_FILE, SERVICE_ACCOUNT_USER,
- DEVELOPER_TOKEN, USER_AGENT, CLIENT_CUSTOMER_ID)
+ main(KEY_FILE, SERVICE_ACCOUNT_USER, DEVELOPER_TOKEN, USER_AGENT,
+ CLIENT_CUSTOMER_ID)
diff --git a/examples/adwords/authentication/create_adwords_client_without_yaml.py b/examples/adwords/authentication/create_adwords_client_without_yaml.py
deleted file mode 100755
index 4877407a..00000000
--- a/examples/adwords/authentication/create_adwords_client_without_yaml.py
+++ /dev/null
@@ -1,56 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Initializes an AdWordsClient without using yaml-cached credentials.
-
-While our LoadFromStorage method provides a useful shortcut to instantiate a
-client if you regularly use just one set of credentials, production applications
-may need to swap out users. This example shows you how to create an OAuth 2.0
-client and an AdWordsClient without relying on a yaml file.
-"""
-
-__author__ = 'Joseph DiLallo'
-
-from googleads import adwords
-from googleads import oauth2
-
-# OAuth 2.0 credential information. In a real application, you'd probably be
-# pulling these values from a credential storage.
-CLIENT_ID = 'INSERT_CLIENT_ID_HERE'
-CLIENT_SECRET = 'INSERT_CLIENT_SECRET_HERE'
-REFRESH_TOKEN = 'INSERT_REFRESH_TOKEN_HERE'
-
-# AdWords API information.
-DEVELOPER_TOKEN = 'INSERT_DEVELOPER_TOKEN_HERE'
-USER_AGENT = 'INSERT_USER_AGENT_HERE'
-CLIENT_CUSTOMER_ID = 'INSERT_CLIENT_CUSTOMER_ID_HERE'
-
-
-def main(client_id, client_secret, refresh_token, developer_token, user_agent,
- client_customer_id):
- oauth2_client = oauth2.GoogleRefreshTokenClient(
- client_id, client_secret, refresh_token)
-
- adwords_client = adwords.AdWordsClient(
- developer_token, oauth2_client, user_agent, client_customer_id)
-
- customer = adwords_client.GetService('CustomerService').get()
- print 'You are logged in as customer: %s' % customer['customerId']
-
-
-if __name__ == '__main__':
- main(CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN, DEVELOPER_TOKEN, USER_AGENT,
- CLIENT_CUSTOMER_ID)
diff --git a/examples/adwords/authentication/generate_refresh_token.py b/examples/adwords/authentication/generate_refresh_token.py
index 2ededff7..027dc59f 100755
--- a/examples/adwords/authentication/generate_refresh_token.py
+++ b/examples/adwords/authentication/generate_refresh_token.py
@@ -1,4 +1,4 @@
-#!/usr/bin/python
+#!/usr/bin/env python
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
@@ -16,47 +16,106 @@
"""Generates refresh token for AdWords using the Installed Application flow."""
-__author__ = 'Mark Saniscalchi'
+import argparse
import sys
-from oauth2client import client
+from google_auth_oauthlib.flow import InstalledAppFlow
+from oauthlib.oauth2.rfc6749.errors import InvalidGrantError
-# Your OAuth 2.0 Client ID and Secret. If you do not have an ID and Secret yet,
+# Your OAuth2 Client ID and Secret. If you do not have an ID and Secret yet,
# please go to https://console.developers.google.com and create a set.
-CLIENT_ID = 'INSERT_CLIENT_ID_HERE'
-CLIENT_SECRET = 'INSERT_CLIENT_SECRET_HERE'
+DEFAULT_CLIENT_ID = None
+DEFAULT_CLIENT_SECRET = None
-# The AdWords API OAuth 2.0 scope.
+# The AdWords API OAuth2 scope.
SCOPE = u'https://www.googleapis.com/auth/adwords'
+# The redirect URI set for the given Client ID. The redirect URI for Client ID
+# generated for an installed application will always have this value.
+_REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
+parser = argparse.ArgumentParser(description='Generates a refresh token with '
+ 'the provided credentials.')
+parser.add_argument('--client_id', default=DEFAULT_CLIENT_ID,
+ help='Client Id retrieved from the Developer\'s Console.')
+parser.add_argument('--client_secret', default=DEFAULT_CLIENT_SECRET,
+ help='Client Secret retrieved from the Developer\'s '
+ 'Console.')
+parser.add_argument('--additional_scopes', default=None,
+ help='Additional scopes to apply when generating the '
+ 'refresh token. Each scope should be separated by a comma.')
-def main():
+
+class ClientConfigBuilder(object):
+ """Helper class used to build a client config dict used in the OAuth 2.0 flow.
+ """
+ _DEFAULT_AUTH_URI = 'https://accounts.google.com/o/oauth2/auth'
+ _DEFAULT_TOKEN_URI = 'https://accounts.google.com/o/oauth2/token'
+ CLIENT_TYPE_WEB = 'web'
+ CLIENT_TYPE_INSTALLED_APP = 'installed'
+
+ def __init__(self, client_type=None, client_id=None, client_secret=None,
+ auth_uri=_DEFAULT_AUTH_URI, token_uri=_DEFAULT_TOKEN_URI):
+ self.client_type = client_type
+ self.client_id = client_id
+ self.client_secret = client_secret
+ self.auth_uri = auth_uri
+ self.token_uri = token_uri
+
+ 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_secret': self.client_secret,
+ 'auth_uri': self.auth_uri,
+ 'token_uri': self.token_uri
+ }
+ }
+ else:
+ raise ValueError('Required field is missing.')
+
+ return client_config
+
+
+def main(client_id, client_secret, scopes):
"""Retrieve and display the access and refresh token."""
- flow = client.OAuth2WebServerFlow(
- client_id=CLIENT_ID,
- client_secret=CLIENT_SECRET,
- scope=[SCOPE],
- user_agent='Ads Python Client Library',
- redirect_uri='urn:ietf:wg:oauth:2.0:oob')
+ client_config = ClientConfigBuilder(
+ client_type=ClientConfigBuilder.CLIENT_TYPE_WEB, client_id=client_id,
+ client_secret=client_secret)
- authorize_url = flow.step1_get_authorize_url()
+ flow = InstalledAppFlow.from_client_config(
+ client_config.Build(), scopes=scopes)
+ # Note that from_client_config will not produce a flow with the
+ # redirect_uris (if any) set in the client_config. This must be set
+ # separately.
+ flow.redirect_uri = _REDIRECT_URI
- print ('Log into the Google Account you use to access your AdWords account'
- 'and go to the following URL: \n%s\n' % (authorize_url))
- print 'After approving the token enter the verification code (if specified).'
- code = raw_input('Code: ').strip()
+ auth_url, _ = flow.authorization_url(prompt='consent')
+
+ print('Log into the Google Account you use to access your AdWords account '
+ 'and go to the following URL: \n%s\n' % auth_url)
+ print('After approving the token enter the verification code (if specified).')
+ code = input('Code: ').strip()
try:
- credential = flow.step2_exchange(code)
- except client.FlowExchangeError, e:
- print 'Authentication has failed: %s' % e
+ flow.fetch_token(code=code)
+ except InvalidGrantError as ex:
+ print('Authentication has failed: %s' % ex)
sys.exit(1)
- else:
- print ('OAuth 2.0 authorization successful!\n\n'
- 'Your access token is:\n %s\n\nYour refresh token is:\n %s'
- % (credential.access_token, credential.refresh_token))
+
+ print('Access token: %s' % flow.credentials.token)
+ print('Refresh token: %s' % flow.credentials.refresh_token)
if __name__ == '__main__':
- main()
+ args = parser.parse_args()
+ configured_scopes = [SCOPE]
+ if not (any([args.client_id, DEFAULT_CLIENT_ID]) and
+ any([args.client_secret, DEFAULT_CLIENT_SECRET])):
+ raise AttributeError('No client_id or client_secret specified.')
+ if args.additional_scopes:
+ configured_scopes.extend(args.additional_scopes.replace(' ', '').split(','))
+ main(args.client_id, args.client_secret, configured_scopes)
diff --git a/examples/adwords/v201406/account_management/__init__.py b/examples/adwords/v201406/account_management/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/examples/adwords/v201406/account_management/create_account.py b/examples/adwords/v201406/account_management/create_account.py
deleted file mode 100755
index ce1e5d6b..00000000
--- a/examples/adwords/v201406/account_management/create_account.py
+++ /dev/null
@@ -1,67 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example illustrates how to create an account.
-
-Note by default this account will only be accessible via parent MCC.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreateAccountService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from datetime import datetime
-
-from googleads import adwords
-
-
-def main(client):
- # Initialize appropriate service.
- managed_customer_service = client.GetService(
- 'ManagedCustomerService', version='v201406')
-
- today = datetime.today().strftime('%Y%m%d %H:%M:%S')
- # Construct operations and add campaign.
- operations = [{
- 'operator': 'ADD',
- 'operand': {
- 'name': 'Account created with ManagedCustomerService on %s' % today,
- 'currencyCode': 'EUR',
- 'dateTimeZone': 'Europe/London',
- }
- }]
-
- # Create the account. It is possible to create multiple accounts with one
- # request by sending an array of operations.
- accounts = managed_customer_service.mutate(operations)
-
- # Display results.
- for account in accounts['value']:
- print ('Account with customer ID \'%s\' was successfully created.'
- % account['customerId'])
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
- main(adwords_client)
diff --git a/examples/adwords/v201406/account_management/get_account_alerts.py b/examples/adwords/v201406/account_management/get_account_alerts.py
deleted file mode 100755
index 0fef7d71..00000000
--- a/examples/adwords/v201406/account_management/get_account_alerts.py
+++ /dev/null
@@ -1,86 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all alerts for all clients of an MCC account.
-
-This example assumes the email and password belong to an MCC.
-
-Note: this code example won't work with test accounts. See
-https://developers.google.com/adwords/api/docs/test-accounts
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AlertService.get
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-from googleads import adwords
-
-
-PAGE_SIZE = 500
-
-
-def main(client):
- # Initialize appropriate service.
- alert_service = client.GetService('AlertService', version='v201406')
-
- # Construct selector and get all alerts.
- offset = 0
- selector = {
- 'query': {
- 'clientSpec': 'ALL',
- 'filterSpec': 'ALL',
- 'types': ['ACCOUNT_BUDGET_BURN_RATE', 'ACCOUNT_BUDGET_ENDING',
- 'ACCOUNT_ON_TARGET', 'CAMPAIGN_ENDED', 'CAMPAIGN_ENDING',
- 'CREDIT_CARD_EXPIRING', 'DECLINED_PAYMENT',
- 'KEYWORD_BELOW_MIN_CPC', 'MANAGER_LINK_PENDING',
- 'MISSING_BANK_REFERENCE_NUMBER', 'PAYMENT_NOT_ENTERED',
- 'TV_ACCOUNT_BUDGET_ENDING', 'TV_ACCOUNT_ON_TARGET',
- 'TV_ZERO_DAILY_SPENDING_LIMIT', 'USER_INVITE_ACCEPTED',
- 'USER_INVITE_PENDING', 'ZERO_DAILY_SPENDING_LIMIT'],
- 'severities': ['GREEN', 'YELLOW', 'RED'],
- 'triggerTimeSpec': 'ALL_TIME'
- },
- 'paging': {
- 'startIndex': str(offset),
- 'numberResults': str(PAGE_SIZE)
- }
- }
- more_pages = True
- while more_pages:
- page = alert_service.get(selector)
- # Display results.
- if 'entries' in page:
- for alert in page['entries']:
- print ('Alert of type \'%s\' and severity \'%s\' for account \'%s\' was'
- ' found.' % (alert['alertType'], alert['alertSeverity'],
- alert['clientCustomerId']))
- else:
- print 'No alerts were found.'
- offset += PAGE_SIZE
- selector['paging']['startIndex'] = str(offset)
- more_pages = offset < int(page['totalNumEntries'])
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
- main(adwords_client)
diff --git a/examples/adwords/v201406/account_management/get_account_changes.py b/examples/adwords/v201406/account_management/get_account_changes.py
deleted file mode 100755
index 66f5de64..00000000
--- a/examples/adwords/v201406/account_management/get_account_changes.py
+++ /dev/null
@@ -1,102 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets the changes in the account during the last 24 hours.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomerSyncService.get
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-import datetime
-
-from googleads import adwords
-
-
-def main(client):
- # Initialize appropriate service.
- customer_sync_service = client.GetService(
- 'CustomerSyncService', version='v201406')
- campaign_service = client.GetService('CampaignService', version='v201406')
-
- # Construct selector and get all campaigns.
- selector = {
- 'fields': ['Id', 'Name', 'Status']
- }
- campaigns = campaign_service.get(selector)
- campaign_ids = []
- if 'entries' in campaigns:
- for campaign in campaigns['entries']:
- campaign_ids.append(campaign['id'])
- else:
- print 'No campaigns were found.'
- return
-
- # Construct selector and get all changes.
- today = datetime.datetime.today()
- yesterday = today - datetime.timedelta(1)
- selector = {
- 'dateTimeRange': {
- 'min': yesterday.strftime('%Y%m%d %H%M%S'),
- 'max': today.strftime('%Y%m%d %H%M%S')
- },
- 'campaignIds': campaign_ids
- }
- account_changes = customer_sync_service.get(selector)
-
- # Display results.
- if account_changes:
- if 'lastChangeTimestamp' in account_changes:
- print 'Most recent changes: %s' % account_changes['lastChangeTimestamp']
- if account_changes['changedCampaigns']:
- for data in account_changes['changedCampaigns']:
- print ('Campaign with id \'%s\' has change status \'%s\'.'
- % (data['campaignId'], data['campaignChangeStatus']))
- if (data['campaignChangeStatus'] != 'NEW' and
- data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'):
- print ' Added ad extensions: %s' % data.get('addedAdExtensions')
- print ' Removed ad extensions: %s' % data.get('deletedAdExtensions')
- print (' Added campaign criteria: %s'
- % data.get('addedCampaignCriteria'))
- print (' Removed campaign criteria: %s'
- % data.get('deletedCampaignCriteria'))
- print (' Campaign targeting changed: %s'
- % data.get('campaignTargetingChanged'))
- if data.get('changedAdGroups'):
- for ad_group_data in data['changedAdGroups']:
- print (' Ad group with id \'%s\' has change status \'%s\'.'
- % (ad_group_data['adGroupId'],
- ad_group_data['adGroupChangeStatus']))
- if ad_group_data['adGroupChangeStatus'] != 'NEW':
- print ' Changed ads: %s' % ad_group_data['changedAds']
- print (' Changed criteria: %s'
- % ad_group_data['changedCriteria'])
- print (' Removed criteria: %s'
- % ad_group_data['deletedCriteria'])
- else:
- print 'No changes were found.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
- main(adwords_client)
diff --git a/examples/adwords/v201406/account_management/get_account_hierarchy.py b/examples/adwords/v201406/account_management/get_account_hierarchy.py
deleted file mode 100755
index a077c122..00000000
--- a/examples/adwords/v201406/account_management/get_account_hierarchy.py
+++ /dev/null
@@ -1,98 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets the account hierarchy under the current account.
-
-Note: this code example won't work with test accounts. See
-https://developers.google.com/adwords/api/docs/test-accounts
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ServicedAccountService.get
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-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 = '-' * depth * 2
- print '%s%s, %s, %s' % (prefix, account['login'], account['customerId'],
- account['name'])
- if account['customerId'] in links:
- for child_link in links[account['customerId']]:
- child_account = accounts[child_link['clientCustomerId']]
- DisplayAccountTree(child_account, accounts, links, depth + 1)
-
-
-def main(client):
- # Initialize appropriate service.
- managed_customer_service = client.GetService(
- 'ManagedCustomerService', version='v201406')
-
- # Construct selector to get all accounts.
- selector = {
- 'fields': ['Login', 'CustomerId', 'Name']
- }
- # Get serviced account graph.
- graph = managed_customer_service.get(selector)
- if 'entries' in graph and graph['entries']:
- # Create map from customerId to parent and child links.
- child_links = {}
- parent_links = {}
- if 'links' in graph:
- for link in graph['links']:
- if link['managerCustomerId'] not in child_links:
- child_links[link['managerCustomerId']] = []
- child_links[link['managerCustomerId']].append(link)
- if link['clientCustomerId'] not in parent_links:
- parent_links[link['clientCustomerId']] = []
- parent_links[link['clientCustomerId']].append(link)
- # Create map from customerID to account and find root account.
- accounts = {}
- root_account = None
- for account in graph['entries']:
- accounts[account['customerId']] = account
- if account['customerId'] not in parent_links:
- root_account = account
- # Display account tree.
- if root_account:
- print 'Login, CustomerId, Name'
- DisplayAccountTree(root_account, accounts, child_links, 0)
- else:
- print 'Unable to determine a root account'
- else:
- print 'No serviced accounts were found'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
- main(adwords_client)
diff --git a/examples/adwords/v201406/advanced_operations/__init__.py b/examples/adwords/v201406/advanced_operations/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/examples/adwords/v201406/advanced_operations/add_ad_customizer.py b/examples/adwords/v201406/advanced_operations/add_ad_customizer.py
deleted file mode 100755
index 53aa536c..00000000
--- a/examples/adwords/v201406/advanced_operations/add_ad_customizer.py
+++ /dev/null
@@ -1,251 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Adds an ad customizer feed.
-
-Associates the feed with customer and adds an ad that
-uses the feed to populate dynamic data.
-
-Tags: CustomerFeedService.mutate, FeedItemService.mutate
-Tags: FeedMappingService.mutate, FeedService.mutate
-Tags: AdGroupAdService.mutate
-"""
-
-__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)',
- 'yufeng.dev@gmail.com (Yufeng Guo)')
-
-# Import appropriate classes from the client library.
-from googleads import adwords
-
-# See the Placeholder reference page for a list of all the placeholder types
-# and fields:
-# https://developers.google.com/adwords/api/docs/appendix/placeholders
-PLACEHOLDER_AD_CUSTOMIZER = '10'
-PLACEHOLDER_FIELD_INTEGER = '1'
-PLACEHOLDER_FIELD_FLOAT = '2'
-PLACEHOLDER_FIELD_PRICE = '3'
-PLACEHOLDER_FIELD_DATE = '4'
-PLACEHOLDER_FIELD_STRING = '5'
-
-ADGROUPS = [
- 'INSERT_ADGROUP_ID_HERE',
- 'INSERT_ADGROUP_ID_HERE'
-]
-
-FEEDNAME = 'INSERT_FEED_NAME_HERE'
-
-
-def main(client, adgroups):
- # Initialize appropriate services.
- ad_group_ad_service = client.GetService('AdGroupAdService', version='v201406')
- customer_feed_service = client.GetService(
- 'CustomerFeedService', version='v201406')
- feed_item_service = client.GetService('FeedItemService', version='v201406')
- feed_mapping_service = client.GetService(
- 'FeedMappingService', version='v201406')
- feed_service = client.GetService('FeedService', version='v201406')
-
- # First, create a customizer feed. One feed per account can be used for all
- # ads.
- customizer_feed = {
- 'name': FEEDNAME,
- 'attributes': [
- {'type': 'STRING', 'name': 'Name'},
- {'type': 'STRING', 'name': 'Price'},
- {'type': 'DATE_TIME', 'name': 'Date'}
- ]
- }
-
- feed_service_operation = {
- 'operator': 'ADD',
- 'operand': customizer_feed
- }
-
- response = feed_service.mutate([feed_service_operation])
-
- if response and 'value' in response:
- feed = response['value'][0]
- feed_data = {
- 'feedId': feed['id'],
- 'nameId': feed['attributes'][0]['id'],
- 'priceId': feed['attributes'][1]['id'],
- 'dateId': feed['attributes'][2]['id']
- }
- print ('Feed with name \'%s\' and ID %s was added with:'
- '\tName attribute ID %s and price attribute ID %s and date attribute'
- 'ID %s') % (feed['name'], feed['id'], feed_data['nameId'],
- feed_data['priceId'], feed_data['dateId'])
- else:
- raise Exception('No feeds were added')
-
- # Creating feed mapping to map the fields with customizer IDs.
- feed_mapping = {
- 'placeholderType': PLACEHOLDER_AD_CUSTOMIZER,
- 'feedId': feed_data['feedId'],
- 'attributeFieldMappings': [
- {
- 'feedAttributeId': feed_data['nameId'],
- 'fieldId': PLACEHOLDER_FIELD_STRING
- },
- {
- 'feedAttributeId': feed_data['priceId'],
- 'fieldId': PLACEHOLDER_FIELD_PRICE
- },
- {
- 'feedAttributeId': feed_data['dateId'],
- 'fieldId': PLACEHOLDER_FIELD_DATE
- }
- ]
- }
-
- feed_mapping_operation = {
- 'operator': 'ADD',
- 'operand': feed_mapping
- }
-
- response = feed_mapping_service.mutate([feed_mapping_operation])
-
- if response and 'value' in response:
- feed_mapping = response['value'][0]
- print ('Feed mapping with ID %s and placeholder type %s was saved for feed'
- ' with ID %s.') % (feed_mapping['feedMappingId'],
- feed_mapping['placeholderType'],
- feed_mapping['feedId'])
- else:
- raise Exception('No feed mappings were added.')
-
- # Now adding feed items -- the values we'd like to place.
- items_data = [
- {
- 'name': 'Mars',
- 'price': '$1234.56',
- 'date': '20140601 000000',
- 'adGroupId': adgroups[0]
- },
- {
- 'name': 'Venus',
- 'price': '$1450.00',
- 'date': '20140615 120000',
- 'adGroupId': adgroups[1]
- }
- ]
-
- feed_items = [{'feedId': feed_data['feedId'],
- 'adGroupTargeting': {
- 'TargetingAdGroupId': item['adGroupId']
- },
- 'attributeValues': [
- {
- 'feedAttributeId': feed_data['nameId'],
- 'stringValue': item['name']
- },
- {
- 'feedAttributeId': feed_data['priceId'],
- 'stringValue': item['price']
- },
- {
- 'feedAttributeId': feed_data['dateId'],
- 'stringValue': item['date']
- }
- ]} for item in items_data]
-
- feed_item_operations = [{
- 'operator': 'ADD',
- 'operand': feed_item
- } for feed_item in feed_items]
-
- response = feed_item_service.mutate(feed_item_operations)
-
- if response and 'value' in response:
- for feed_item in response['value']:
- print 'Feed item with ID %s was added.' % feed_item['feedItemId']
- else:
- raise Exception('No feed items were added.')
-
- # Finally, creating a customer (account-level) feed with a matching function
- # that determines when to use this feed. For this case we use the "IDENTITY"
- # matching function that is always 'true' just to associate this feed with
- # the customer. The targeting is done within the feed items using the
- # :campaign_targeting, :ad_group_targeting, or :keyword_targeting attributes.
- matching_function = {
- 'operator': 'IDENTITY',
- 'lhsOperand': [
- {
- 'xsi_type': 'ConstantOperand',
- 'type': 'BOOLEAN',
- 'booleanValue': 'true'
- }
- ]
- }
-
- customer_feed = {
- 'feedId': feed_data['feedId'],
- 'matchingFunction': matching_function,
- 'placeholderTypes': [PLACEHOLDER_AD_CUSTOMIZER]
- }
-
- customer_feed_operation = {
- 'operator': 'ADD',
- 'operand': customer_feed
- }
-
- response = customer_feed_service.mutate([customer_feed_operation])
-
- if response and 'value' in response:
- feed = response['value'][0]
- print 'Customer feed with ID %s was added.' % feed['feedId']
- else:
- raise Exception('No customer feeds were added.')
-
- # All set! We can now create ads with customizations.
- text_ad = {
- 'xsi_type': 'TextAd',
- 'headline': 'Luxury Cruise to {=%s.Name}' % FEEDNAME,
- 'description1': 'Only {=%s.Price}' % FEEDNAME,
- 'description2': 'Offer ends in {=countdown(%s.Date)}!' % FEEDNAME,
- 'url': 'http://www.example.com',
- 'displayUrl': 'www.example.com'
- }
-
- # We add the same ad to both ad groups. When they serve, they will show
- # different values, since they match different feed items.
- operations = [{
- 'operator': 'ADD',
- 'operand': {
- 'adGroupId': adgroup,
- 'ad': text_ad
- }
- } for adgroup in adgroups]
-
- print operations
-
- response = ad_group_ad_service.mutate(operations)
-
- print '===ad group ad service==='
- print response
-
- if response and 'value' in response:
- for ad in response['value']:
- print ('\tCreated an ad with ID \'%s\', type \'%s\', and status \'%s\'.'
- % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status']))
- else:
- raise Exception('No ads were added.')
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
- main(adwords_client, ADGROUPS)
diff --git a/examples/adwords/v201406/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201406/advanced_operations/add_ad_group_bid_modifier.py
deleted file mode 100755
index 2b7f40f6..00000000
--- a/examples/adwords/v201406/advanced_operations/add_ad_group_bid_modifier.py
+++ /dev/null
@@ -1,78 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Adds an ad group level mobile bid modifier override for a campaign.
-
-To get your ad groups, run get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupBidModifierService.mutate
-"""
-
-__author__ = 'Joseph DiLallo'
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-BID_MODIFIER = 'INSERT_BID_MODIFIER_HERE'
-
-
-def main(client, ad_group_id, bid_modifier):
- # Initialize appropriate service.
- ad_group_bid_modifier_service = client.GetService(
- 'AdGroupBidModifierService', version='v201406')
-
- # Mobile criterion ID.
- criterion_id = '30001'
-
- # Prepare to add an ad group level override.
- operation = {
- # Use 'ADD' to add a new modifier and 'SET' to update an existing one. A
- # modifier can be removed with the 'REMOVE' operator.
- 'operator': 'ADD',
- 'operand': {
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Platform',
- 'id': criterion_id
- },
- 'bidModifier': bid_modifier
- }
- }
-
- # Add ad group level mobile bid modifier.
- response = ad_group_bid_modifier_service.mutate([operation])
- if response and response['value']:
- modifier = response['value'][0]
- value = modifier['bidModifier'] if 'bidModifier' in modifier else 'unset'
- print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s was updated with '
- 'ad group level modifier: %s' %
- (modifier['campaignId'], modifier['adGroupId'],
- modifier['criterion']['id'], value))
- else:
- print 'No modifiers were added.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID, BID_MODIFIER)
diff --git a/examples/adwords/v201406/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201406/advanced_operations/add_click_to_download_ad.py
deleted file mode 100755
index 1eb5d81f..00000000
--- a/examples/adwords/v201406/advanced_operations/add_click_to_download_ad.py
+++ /dev/null
@@ -1,113 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates a click-to-download ad in a given ad group.
-
-This type of ad is also known as an app promotion ad. To list ad groups, run
-get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupAdService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = 'Joseph DiLallo'
-
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Initialize appropriate service.
- ad_group_ad_service = client.GetService('AdGroupAdService', version='v201406')
-
- # Create the template elements for the ad. You can refer to
- # https://developers.google.com/adwords/api/docs/appendix/templateads
- # for the list of available template fields.
- ad_data = {
- 'uniqueName': 'adData',
- 'fields': [
- {
- 'name': 'headline',
- 'fieldText': 'Enjoy your drive in Mars',
- 'type': 'TEXT'
- },
- {
- 'name': 'description1',
- 'fieldText': 'Realistic physics simulation',
- 'type': 'TEXT'
- },
- {
- 'name': 'description2',
- 'fieldText': 'Race against players online',
- 'type': 'TEXT'
- },
- {
- 'name': 'appId',
- 'fieldText': 'com.example.demogame',
- 'type': 'TEXT'
- },
- {
- 'name': 'appStore',
- 'fieldText': '2',
- 'type': 'ENUM'
- }
- ]
- }
-
- # Create click to download ad.
- click_to_download_app_ad = {
- 'xsi_type': 'TemplateAd',
- 'name': 'Ad for demo game',
- 'templateId': '353',
- 'url': ('http://play.google.com/store/apps/details?'
- 'id=com.example.demogame'),
- 'displayUrl': 'play.google.com',
- 'templateElements': [ad_data]
- }
-
- # Create ad group ad.
- ad_group_ad = {
- 'adGroupId': ad_group_id,
- 'ad': click_to_download_app_ad,
- # Optional.
- 'status': 'PAUSED'
- }
-
- # Add ad.
- ads = ad_group_ad_service.mutate([
- {'operator': 'ADD', 'operand': ad_group_ad}
- ])
- # Display results.
- if 'value' in ads:
- for ad in ads['value']:
- print ('Added new click-to-download ad to ad group ID \'%s\' '
- 'with URL \'%s\'.' % (ad['ad']['id'], ad['ad']['url']))
- else:
- print 'No ads were added.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201406/advanced_operations/add_google_my_business_location_extensions.py b/examples/adwords/v201406/advanced_operations/add_google_my_business_location_extensions.py
deleted file mode 100755
index 07e1e11c..00000000
--- a/examples/adwords/v201406/advanced_operations/add_google_my_business_location_extensions.py
+++ /dev/null
@@ -1,140 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-
-"""Adds a feed that syncs feed items from a Google My Business (GMB) account.
-
-This example associates the feed with a customer.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomerFeedService.mutate, FeedService.mutate
-"""
-
-__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)',
- 'Joseph DiLallo')
-
-import time
-import uuid
-
-# Import appropriate modules from the client library.
-import suds
-
-from googleads import adwords
-from googleads import errors
-
-GMB_EMAIL_ADDRESS = 'INSERT_GMB_EMAIL_ADDRESS_HERE'
-# To obtain an access token for your Places account, you can run the
-# generate_refresh_token.py example and manually replace the scope with
-# "https://www.google.com/local/add".
-GMB_ACCESS_TOKEN = 'INSERT_GMB_OAUTH_ACCESS_TOKEN_HERE'
-
-# The placeholder type for location extensions.
-# See the Placeholder reference page for a list of all the placeholder types
-# and fields:
-# https://developers.google.com/adwords/api/docs/appendix/placeholders
-PLACEHOLDER_LOCATION = 7
-
-# The maximum number of CustomerFeed ADD operation attempts to make before
-# throwing an exception.
-MAX_CUSTOMER_FEED_ADD_ATTEMPTS = 10
-
-
-def main(client, gmb_email_address, gmb_access_token):
- # Create a feed that will sync to the Google Places account specified by
- # gmb_email_address. Do not add FeedAttributes to this object,
- # as AdWords will add them automatically because this will be a
- # system generated feed.
- feed = {
- 'name': 'Places feed #%s' % uuid.uuid4(),
- 'systemFeedGenerationData': {
- 'xsi_type': 'PlacesLocationFeedData',
- 'oAuthInfo': {
- 'httpMethod': 'GET',
- 'httpRequestUrl': 'https://www.google.com/local/add',
- 'httpAuthorizationHeader': 'Bearer %s' % gmb_access_token
- },
- 'emailAddress': gmb_email_address,
- },
- # Since this feed's feed items will be managed by AdWords, you must set
- # its origin to ADWORDS.
- 'origin': 'ADWORDS'
- }
-
- # Create an operation to add the feed.
- gmb_operations = [{
- 'operator': 'ADD',
- 'operand': feed
- }]
-
- gmb_response = client.GetService('FeedService', version='v201406').mutate(
- gmb_operations)
- added_feed = gmb_response['value'][0]
- print 'Added GMB feed with ID: %d\n' % added_feed['id']
-
- # Add a CustomerFeed that associates the feed with this customer for the
- # LOCATION placeholder type.
- customer_feed = {
- 'feedId': added_feed['id'],
- 'placeholderTypes': [PLACEHOLDER_LOCATION],
- 'matchingFunction': {
- 'operator': 'IDENTITY',
- 'lhsOperand': {
- 'xsi_type': 'FunctionArgumentOperand',
- 'type': 'BOOLEAN',
- 'booleanValue': True
- }
- }
- }
-
- customer_feed_operation = {
- 'xsi_type': 'CustomerFeedOperation',
- 'operator': 'ADD',
- 'operand': customer_feed
- }
-
- customer_feed_service = client.GetService(
- 'CustomerFeedService', version='v201406')
- added_customer_feed = None
-
- i = 0
- while i < MAX_CUSTOMER_FEED_ADD_ATTEMPTS and added_customer_feed is None:
- try:
- added_customer_feed = customer_feed_service.mutate([
- customer_feed_operation])['value'][0]
- except suds.WebFault:
- # Wait using exponential backoff policy
- sleep_seconds = 2 ** i
- print ('Attempt %d to add the CustomerFeed was not successful.'
- 'Waiting %d seconds before trying again.\n' % (i, sleep_seconds))
- time.sleep(sleep_seconds)
- i += 1
-
- if added_customer_feed is None:
- raise errors.GoogleAdsError(
- 'Could not create the CustomerFeed after %s attempts. Please retry the '
- 'CustomerFeed ADD operation later.' % MAX_CUSTOMER_FEED_ADD_ATTEMPTS)
-
- print ('Added CustomerFeed for feed ID %d and placeholder type %d\n'
- % (added_customer_feed['id'], added_customer_feed['placeholderTypes']))
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
- main(adwords_client, GMB_EMAIL_ADDRESS, GMB_ACCESS_TOKEN)
diff --git a/examples/adwords/v201406/advanced_operations/add_site_links.py b/examples/adwords/v201406/advanced_operations/add_site_links.py
deleted file mode 100755
index fe3e52ea..00000000
--- a/examples/adwords/v201406/advanced_operations/add_site_links.py
+++ /dev/null
@@ -1,261 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds a sitelinks feed and associates it with a campaign.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignFeedService.mutate, FeedItemService.mutate
-Tags: FeedMappingService.mutate, FeedService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = 'Joseph DiLallo'
-
-import uuid
-
-from googleads import adwords
-from googleads import errors
-
-# See the Placeholder reference page for a list of all the placeholder types and
-# fields.
-# https://developers.google.com/adwords/api/docs/appendix/placeholders.html
-PLACEHOLDER_SITELINKS = '1'
-PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = '1'
-PLACEHOLDER_FIELD_SITELINK_LINK_URL = '2'
-PLACEHOLDER_FIELD_LINE_1_TEXT = '3'
-PLACEHOLDER_FIELD_LINE_2_TEXT = '4'
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-
-
-def main(client, campaign_id):
- # Initialize appropriate service.
- feed_service = client.GetService('FeedService', version='v201406')
- feed_item_service = client.GetService('FeedItemService', version='v201406')
- feed_mapping_service = client.GetService(
- 'FeedMappingService', version='v201406')
- campaign_feed_service = client.GetService(
- 'CampaignFeedService', version='v201406')
-
- sitelinks_data = {}
-
- # Create site links feed first.
- site_links_feed = {
- 'name': 'Feed For Site Links #%s' % uuid.uuid4(),
- 'attributes': [
- {'type': 'STRING', 'name': 'Link Text'},
- {'type': 'URL', 'name': 'Link URL'},
- {'type': 'STRING', 'name': 'Line 1 Description'},
- {'type': 'STRING', 'name': 'Line 2 Description'}
- ]
- }
-
- response = feed_service.mutate([
- {'operator': 'ADD', 'operand': site_links_feed}
- ])
- if 'value' in response:
- feed = response['value'][0]
- link_text_feed_attribute_id = feed['attributes'][0]['id']
- link_url_feed_attribute_id = feed['attributes'][1]['id']
- line_1_feed_attribute_id = feed['attributes'][2]['id']
- line_2_feed_attribute_id = feed['attributes'][3]['id']
- print ('Feed with name \'%s\' and ID \'%s\' was added with' %
- (feed['name'], feed['id']))
- print ('\tText attribute ID \'%s\' and URL attribute ID \'%s\'.' %
- (link_text_feed_attribute_id, link_url_feed_attribute_id))
- print ('\tLine 1 attribute ID \'%s\' and Line 2 attribute ID \'%s\'.' %
- (line_1_feed_attribute_id, line_2_feed_attribute_id))
- sitelinks_data['feedId'] = feed['id']
- sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id
- sitelinks_data['linkUrlFeedId'] = link_url_feed_attribute_id
- sitelinks_data['line1FeedId'] = line_1_feed_attribute_id
- sitelinks_data['line2FeedId'] = line_2_feed_attribute_id
- else:
- raise errors.GoogleAdsError('No feeds were added.')
-
- # Create site links feed items.
- items_data = [
- {'text': 'Home', 'url': 'http://www.example.com',
- 'line1': 'Home line 1', 'line2': 'Home line 2'},
- {'text': 'Stores', 'url': 'http://www.example.com/stores',
- 'line1': 'Stores line 1', 'line2': 'Stores line 2'},
- {'text': 'On Sale', 'url': 'http://www.example.com/sale',
- 'line1': 'On Sale line 1', 'line2': 'On Sale line 2'},
- {'text': 'Support', 'url': 'http://www.example.com/support',
- 'line1': 'Support line 1', 'line2': 'Support line 2'},
- {'text': 'Products', 'url': 'http://www.example.com/products',
- 'line1': 'Products line 1', 'line2': 'Products line 2'},
- {'text': 'About', 'url': 'http://www.example.com/about',
- 'line1': 'About line 1', 'line2': 'About line 2'}
- ]
-
- feed_items = []
- for item in items_data:
- feed_items.append({
- 'feedId': sitelinks_data['feedId'],
- 'attributeValues': [
- {
- 'feedAttributeId': sitelinks_data['linkTextFeedId'],
- 'stringValue': item['text']
- },
- {
- 'feedAttributeId': sitelinks_data['linkUrlFeedId'],
- 'stringValue': item['url']
- },
- {
- 'feedAttributeId': sitelinks_data['line1FeedId'],
- 'stringValue': item['line1']
- },
- {
- 'feedAttributeId': sitelinks_data['line2FeedId'],
- 'stringValue': item['line2']
- }
- ],
- # Optional: use the 'startTime' and 'endTime' keys to specify the time
- # period for the feed to deliver. The example below will make the feed
- # start now and stop in one month.
- # Make sure you specify the datetime in the customer's time zone. You
- # can retrieve this from customer['dateTimeZone'].
- #
- # ['startTime']: datetime.datetime.now().strftime('%Y%m%d %H%M%S')
- # ['endTime']: (datetime.datetime.now() +
- # relativedelta(months=1)).strftime('%Y%m%d %H%M%S')
-
- # Optional: use the 'scheduling' key to specify time and days of the
- # week for feed to deliver. This is a Beta feature.
- })
-
- feed_items_operations = [{'operator': 'ADD', 'operand': item} for item
- in feed_items]
-
- response = feed_item_service.mutate(feed_items_operations)
- if 'value' in response:
- sitelinks_data['feedItemIds'] = []
- for feed_item in response['value']:
- print 'Feed item with ID %s was added.' % feed_item['feedItemId']
- sitelinks_data['feedItemIds'].append(feed_item['feedItemId'])
- else:
- raise errors.GoogleAdsError('No feed items were added.')
-
- # Create site links feed mapping.
-
- feed_mapping = {
- 'placeholderType': PLACEHOLDER_SITELINKS,
- 'feedId': sitelinks_data['feedId'],
- 'attributeFieldMappings': [
- {
- 'feedAttributeId': sitelinks_data['linkTextFeedId'],
- 'fieldId': PLACEHOLDER_FIELD_SITELINK_LINK_TEXT
- },
- {
- 'feedAttributeId': sitelinks_data['linkUrlFeedId'],
- 'fieldId': PLACEHOLDER_FIELD_SITELINK_LINK_URL
- },
- {
- 'feedAttributeId': sitelinks_data['line1FeedId'],
- 'fieldId': PLACEHOLDER_FIELD_LINE_1_TEXT
- },
- {
- 'feedAttributeId': sitelinks_data['line2FeedId'],
- 'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT
- }
- ]
- }
-
- response = feed_mapping_service.mutate([
- {'operator': 'ADD', 'operand': feed_mapping}
- ])
- if 'value' in response:
- feed_mapping = response['value'][0]
- print ('Feed mapping with ID %s and placeholder type %s was saved for feed'
- ' with ID %s.' %
- (feed_mapping['feedMappingId'], feed_mapping['placeholderType'],
- feed_mapping['feedId']))
- else:
- raise errors.GoogleAdsError('No feed mappings were added.')
-
- # Create site links campaign feed.
- operands = []
- for feed_item_id in sitelinks_data['feedItemIds']:
- operands.append({
- 'xsi_type': 'ConstantOperand',
- 'type': 'LONG',
- 'longValue': feed_item_id
- })
-
- feed_item_function = {
- 'operator': 'IN',
- 'lhsOperand': [
- {'xsi_type': 'RequestContextOperand', 'contextType': 'FEED_ITEM_ID'}
- ],
- 'rhsOperand': operands
- }
-
- # Optional: to target to a platform, define a function and 'AND' it with the
- # feed item ID link:
- platform_function = {
- 'operator': 'EQUALS',
- 'lhsOperand': [
- {
- 'xsi_type': 'RequestContextOperand',
- 'contextType': 'DEVICE_PLATFORM'
- }
- ],
- 'rhsOperand': [
- {
- 'xsi_type': 'ConstantOperand',
- 'type': 'STRING',
- 'stringValue': 'Mobile'
- }
- ]
- }
- combined_function = {
- 'operator': 'AND',
- 'lhsOperand': [
- {'xsi_type': 'FunctionOperand', 'value': feed_item_function},
- {'xsi_type': 'FunctionOperand', 'value': platform_function}
- ]
- }
-
- campaign_feed = {
- 'feedId': sitelinks_data['feedId'],
- 'campaignId': campaign_id,
- 'matchingFunction': combined_function,
- # Specifying placeholder types on the CampaignFeed allows the same feed
- # to be used for different placeholders in different Campaigns.
- 'placeholderTypes': [PLACEHOLDER_SITELINKS]
- }
-
- response = campaign_feed_service.mutate([
- {'operator': 'ADD', 'operand': campaign_feed}
- ])
- if 'value' in response:
- campaign_feed = response['value'][0]
- print ('Campaign with ID %s was associated with feed with ID %s.' %
- (campaign_feed['campaignId'], campaign_feed['feedId']))
- else:
- raise errors.GoogleAdsError('No campaign feeds were added.')
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201406/advanced_operations/add_text_ad_with_upgraded_urls.py b/examples/adwords/v201406/advanced_operations/add_text_ad_with_upgraded_urls.py
deleted file mode 100755
index c5e7dd94..00000000
--- a/examples/adwords/v201406/advanced_operations/add_text_ad_with_upgraded_urls.py
+++ /dev/null
@@ -1,114 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This examples adds a text add that uses upgraded URLs.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupAdService.mutate
-"""
-
-__author__ = 'Mark Saniscalchi'
-
-from googleads import adwords
-from googleads import errors
-
-
-ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE'
-
-
-def main(client, adgroup_id):
- # Initialize appropriate service.
- adgroup_ad_service = client.GetService('AdGroupAdService', version='v201406')
-
- # Create the text ad
- text_ad = {
- 'xsi_type': 'TextAd',
- 'headline': 'Luxury Cruise to Mars',
- 'description1': 'Visit the Red Planet in style.',
- 'description2': 'Low-gravity fun for everyone!',
- 'displayUrl': 'www.example.com',
- # Specify a tracking URL for 3rd party tracking provider. You may specify
- # one at customer, campaign, ad group, ad, criterion or feed item levels.
- 'trackingUrlTemplate': ('http://tracker.example.com/?season={_season}'
- '&promocode={_promocode}&u={lpurl}'),
- 'urlCustomParameters': {
- 'parameters': [
- # Since your tracking URL has two custom parameters, provide
- # their values too. This can be provided at campaign, ad group,
- # ad, criterion, or feed item levels.
- {
- 'key': 'season',
- 'value': 'christmas'
- },
- {
- 'key': 'promocode',
- 'value': 'NYC123'
- }
- ]
- },
- # Specify a list of final URLs. This field cannot be set if URL
- # field is set, or finalUrls is unset. This may be specified at ad,
- # criterion, and feed item levels.
- 'finalUrls': [
- 'http://www.example.com/cruise/space/',
- 'http://www.example.com/locations/mars/'
- ],
- # Specify a list of final mobile URLs. This field cannot be set if URL
- # field is set, or finalUrls is unset. This may be specified at ad,
- # criterion, and feed item levels.
- 'finalMobileUrls': [
- 'http://mobile.example.com/cruise/space/',
- 'http://mobile.example.com/locations/mars/'
- ]
- }
-
- text_adgroup_ad = {
- 'adGroupId': adgroup_id,
- 'ad': text_ad,
- # Optional: Set the status.
- 'status': 'PAUSED'
- }
-
- operations = [{
- 'operator': 'ADD',
- 'operand': text_adgroup_ad
- }]
-
- response = adgroup_ad_service.mutate(operations)
-
- if 'value' in response:
- for adgroup_ad in response['value']:
- print ('AdGroupAd with ID %s and display URL \'%s\'was added.'
- % (adgroup_ad['ad']['id'], adgroup_ad['ad']['displayUrl']))
- print 'Upgraded URL properties:'
- print 'Final Urls: %s' % adgroup_ad['ad']['finalUrls']
- print 'Final Mobile URLs: %s' % adgroup_ad['ad']['finalMobileUrls']
- print ('Tracking URL template: %s'
- % adgroup_ad['ad']['trackingUrlTemplate'])
- print 'Custom parameters: %s' % adgroup_ad['ad']['urlCustomParameters']
- else:
- raise errors.GoogleAdsError('Failed to create AdGroupAd.')
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, ADGROUP_ID)
diff --git a/examples/adwords/v201406/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201406/advanced_operations/get_ad_group_bid_modifier.py
deleted file mode 100755
index 705108e3..00000000
--- a/examples/adwords/v201406/advanced_operations/get_ad_group_bid_modifier.py
+++ /dev/null
@@ -1,76 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Retrieves the ad group level bid modifiers for a campaign.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupBidModifierService.get
-"""
-
-__author__ = 'Joseph DiLallo'
-
-from googleads import adwords
-
-
-PAGE_SIZE = 500
-
-
-def main(client):
- # Initialize appropriate service.
- ad_group_bid_modifier_service = client.GetService(
- 'AdGroupBidModifierService', version='v201406')
-
- # Get all ad group bid modifiers for the campaign.
- selector = {
- 'fields': ['CampaignId', 'AdGroupId', 'BidModifier', 'Id'],
- 'paging': {
- 'startIndex': '0',
- 'numberResults': str(PAGE_SIZE)
- }
- }
-
- # Set initial values.
- offset, page = 0, {}
- more_results = True
-
- while more_results:
- page = ad_group_bid_modifier_service.get(selector)
- if page['entries']:
- for modifier in page['entries']:
- value = (modifier['bidModifier'] if 'bidModifier' in modifier
- else 'unset')
- print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s has ad group '
- 'level modifier: %s' %
- (modifier['campaignId'], modifier['adGroupId'],
- modifier['criterion']['id'], value))
-
- # Increment values to request the next page.
- offset += PAGE_SIZE
- selector['paging']['startIndex'] = str(offset)
- else:
- print 'No ad group bid modifiers returned.'
- more_results = int(page['totalNumEntries']) > offset
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201406/advanced_operations/update_site_links.py b/examples/adwords/v201406/advanced_operations/update_site_links.py
deleted file mode 100755
index f4439e1e..00000000
--- a/examples/adwords/v201406/advanced_operations/update_site_links.py
+++ /dev/null
@@ -1,168 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates an existing sitelinks feed.
-
-Specifically, it does the following:
- * Adds FeedItemAttributes for line 1 and line 2 descriptions to the Feed
- * Populates the new FeedItemAttributes on FeedItems in the Feed
- * Replaces the Feed's existing FeedMapping with one that contains the new
- set of FeedItemAttributes
-
-The end result of this is that any campaign or ad group whose CampaignFeed
-or AdGroupFeed points to the Feed's ID will now serve line 1 and line 2
-descriptions in its sitelinks.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: FeedItemService.mutate
-Tags: FeedMappingService.mutate, FeedService.mutate
-"""
-
-__author__ = 'Joseph DiLallo'
-
-from googleads import adwords
-
-FEED_ID = 'FEED_ID'
-FEED_ITEM_DESCRIPTIONS = {
- 'INSERT_FEED_ITEM_A_ID_HERE': [
- 'INSERT_FEED_ITEM_A_LINE1_DESC_HERE',
- 'INSERT_FEED_ITEM_A_LINE2_DESC_HERE'
- ],
- 'INSERT_FEED_ITEM_B_ID_HERE': [
- 'INSERT_FEED_ITEM_B_LINE1_DESC_HERE',
- 'INSERT_FEED_ITEM_B_LINE2_DESC_HERE'
- ]
-}
-
-# See the Placeholder reference page for a list of all the placeholder types
-# and fields:
-# https://developers.google.com/adwords/api/docs/appendix/placeholders
-PLACEHOLDER_FIELD_LINE_1_TEXT = 3
-PLACEHOLDER_FIELD_LINE_2_TEXT = 4
-
-
-def main(client, feed_id, feed_item_descriptions):
- feed_service = client.GetService('FeedService', 'v201406')
- feed_item_service = client.GetService('FeedItemService', 'v201406')
- feed_mapping_service = client.GetService('FeedMappingService', 'v201406')
-
- feed_selector = {
- 'fields': ['Id', 'Attributes'],
- 'predicates': [
- {'field': 'Id', 'operator': 'EQUALS', 'values': [feed_id]}
- ]
- }
-
- feed = feed_service.get(feed_selector)['entries'][0]
-
- # Add new line1 and line2 feed attributes.
- next_attribute_index = len(feed['attributes'])
-
- feed['attributes'] = [
- {'type': 'STRING', 'name': 'Line 1 Description'},
- {'type': 'STRING', 'name': 'Line 2 Description'}
- ]
-
- mutated_feed_result = feed_service.mutate([
- {'operator': 'SET', 'operand': feed}
- ])
-
- mutated_feed = mutated_feed_result['value'][0]
- line_1_attribute = mutated_feed['attributes'][next_attribute_index]
- line_2_attribute = mutated_feed['attributes'][next_attribute_index + 1]
-
- # Update feed items.
- feed_item_ids = feed_item_descriptions.keys()
- item_selector = {
- 'fields': ['FeedId', 'FeedItemId', 'AttributeValues'],
- 'predicates': [
- {'field': 'FeedId', 'operator': 'EQUALS', 'values': [feed_id]},
- {'field': 'FeedItemId', 'operator': 'IN', 'values': feed_item_ids}
- ]
- }
-
- feed_items = feed_item_service.get(item_selector)['entries']
-
- item_operations = []
- for feed_item in feed_items:
- feed_item['attributeValues'] = [
- {
- 'feedAttributeId': line_1_attribute['id'],
- 'stringValue': feed_item_descriptions[feed_item['feedItemId']][0]
- },
- {
- 'feedAttributeId': line_2_attribute['id'],
- 'stringValue': feed_item_descriptions[feed_item['feedItemId']][1]
- }
- ]
-
- item_operations.append({'operator': 'SET', 'operand': feed_item})
-
- items_update_result = feed_item_service.mutate(item_operations)
- print 'Updated %d items' % len(items_update_result['value'])
-
- # Update feed mapping.
- mapping_selector = {
- 'fields': [
- 'FeedId',
- 'FeedMappingId',
- 'PlaceholderType',
- 'AttributeFieldMappings'
- ],
- 'predicates': [
- {'field': 'FeedId', 'operator': 'EQUALS', 'values': [feed_id]}
- ]
- }
- feed_mapping_results = feed_mapping_service.get(mapping_selector)
- feed_mapping = feed_mapping_results['entries'][0]
-
- # Feed mappings are immutable, so we have to delete it and re-add
- # it with modifications.
- feed_mapping = feed_mapping_service.mutate([
- {'operator': 'REMOVE', 'operand': feed_mapping}
- ])['value'][0]
-
- feed_mapping['attributeFieldMappings'].push(
- {
- 'feedAttributeId': line_1_attribute['id'],
- 'fieldId': PLACEHOLDER_FIELD_LINE_1_TEXT
- },
- {
- 'feedAttributeId': line_2_attribute['id'],
- 'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT
- }
- )
- mapping_update_result = feed_mapping_service.mutate([
- {'operator': 'ADD', 'operand': feed_mapping}
- ])
-
- mutated_mapping = mapping_update_result['value'][0]
- print ('Updated field mappings for feedId %d and feedMappingId %d to:' %
- (mutated_mapping['feedId'], mutated_mapping['feedMappingId']))
- for field_mapping in mutated_mapping['attributeFieldMappings']:
- print ('\tfeedAttributeId %d --> fieldId %d' %
- (field_mapping['feedAttributeId'], field_mapping['fieldId']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, FEED_ID, FEED_ITEM_DESCRIPTIONS)
diff --git a/examples/adwords/v201406/advanced_operations/upload_offline_conversions.py b/examples/adwords/v201406/advanced_operations/upload_offline_conversions.py
deleted file mode 100755
index 0a21d330..00000000
--- a/examples/adwords/v201406/advanced_operations/upload_offline_conversions.py
+++ /dev/null
@@ -1,101 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Imports offline conversion values for specific clicks into your account.
-
-To get the Google Click ID for a click, run a CLICK_PERFORMANCE_REPORT.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ConversionTrackerService.mutate, OfflineConversionFeedService.mutate
-"""
-
-__author__ = 'Joseph DiLallo'
-
-from googleads import adwords
-
-
-CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE'
-# Your click ID must be less than 30 days old.
-CLICK_ID = 'INSERT_GOOGLE_CLICK_ID_HERE'
-# The conversion time must be more recent than the time of the click.
-CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE'
-CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE'
-
-
-def main(client, conversion_name, click_id, conversion_time, conversion_value):
- # Initialize appropriate services.
- conversion_tracker_service = client.GetService('ConversionTrackerService',
- version='v201406')
-
- offline_conversion_feed_service = client.GetService(
- 'OfflineConversionFeedService', version='v201406')
-
- # Once created, this entry will be visible under
- # Tools and Analysis->Conversion and will have "Source = Import".
- upload_conversion = {
- 'xsi_type': 'UploadConversion',
- 'category': 'PAGE_VIEW',
- 'name': conversion_name,
- 'viewthroughLookbackWindow': '30',
- 'ctcLookbackWindow': '90'
- }
-
- upload_conversion_operation = {
- 'operator': 'ADD',
- 'operand': upload_conversion
- }
-
- response = conversion_tracker_service.mutate(
- [upload_conversion_operation])
- new_upload_conversion = response['value']
-
- print ('New upload conversion type with name \'%s\' and ID \'%s\' was '
- 'created.' % (new_upload_conversion['name'],
- new_upload_conversion['id']))
-
- # Associate offline conversions with the upload conversion we created.
- feed = {
- 'conversionName': conversion_name,
- 'conversionTime': conversion_time,
- 'conversionValue': conversion_value,
- 'googleClickId': click_id
- }
-
- offline_conversion_operation = {
- 'operator': 'ADD',
- 'operand': feed
- }
-
- offline_conversion_response = offline_conversion_feed_service.mutate(
- [offline_conversion_operation])
- new_feed = offline_conversion_response['value']
-
- print ('Uploaded offline conversion value of \'%s\' for Google Click ID '
- '\'%s\' to \'%s\'.' % (new_feed['conversionValue'],
- new_feed['googleClickId'],
- new_feed['conversionName']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CONVERSION_NAME, CLICK_ID, CONVERSION_TIME,
- CONVERSION_VALUE)
diff --git a/examples/adwords/v201406/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201406/advanced_operations/use_shared_bidding_strategy.py
deleted file mode 100755
index 377c7fee..00000000
--- a/examples/adwords/v201406/advanced_operations/use_shared_bidding_strategy.py
+++ /dev/null
@@ -1,180 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Adds a Shared Bidding Strategy and uses it to construct a campaign.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: BiddingStrategyService.mutate
-Tags: BudgetService.mutate, CampaignService.mutate
-"""
-
-__author__ = 'Joseph DiLallo'
-
-import uuid
-
-from googleads import adwords
-
-
-# Enter a shared budget ID to re-use an existing budget or leave as None to
-# create a new one.
-BUDGET_ID = None
-
-
-def main(client, budget_id):
- bidding_strategy = CreateBiddingStrategy(client)
-
- if budget_id is None:
- budget = CreateSharedBudget(client)
- budget_id = budget['budgetId']
-
- CreateCampaignWithBiddingStrategy(client, bidding_strategy['id'], budget_id)
-
-
-def CreateBiddingStrategy(client):
- """Creates a bidding strategy object.
-
- Args:
- client: AdWordsClient the client to run the example with.
-
- Returns:
- dict An object representing a bidding strategy.
- """
- # Initialize appropriate service.
- bidding_strategy_service = client.GetService(
- 'BiddingStrategyService', version='v201406')
-
- # Create a shared bidding strategy.
- shared_bidding_strategy = {
- 'name': 'Maximize Clicks %s' % uuid.uuid4(),
- 'biddingScheme': {
- 'xsi_type': 'TargetSpendBiddingScheme',
- # Optionally set additional bidding scheme parameters.
- 'bidCeiling': {
- 'microAmount': '2000000'
- }
- }
- }
-
- # Create operation.
- operation = {
- 'operator': 'ADD',
- 'operand': shared_bidding_strategy
- }
-
- response = bidding_strategy_service.mutate([operation])
- new_bidding_strategy = response['value'][0]
-
- print ('Shared bidding strategy with name \'%s\' and ID \'%s\' of type \'%s\''
- 'was created.' %
- (new_bidding_strategy['name'], new_bidding_strategy['id'],
- new_bidding_strategy['biddingScheme']['BiddingScheme.Type']))
-
- return new_bidding_strategy
-
-
-def CreateSharedBudget(client):
- """Creates an explicit budget to be used only to create the Campaign.
-
- Args:
- client: AdWordsClient the client to run the example with.
-
- Returns:
- dict An object representing a shared budget.
- """
- # Initialize appropriate service.
- budget_service = client.GetService('BudgetService', version='v201406')
-
- # Create a shared budget
- budget = {
- 'name': 'Shared Interplanetary Budget #%s' % uuid.uuid4(),
- 'period': 'DAILY',
- 'amount': {
- 'microAmount': '2000000'
- },
- 'deliveryMethod': 'STANDARD',
- 'isExplicitlyShared': 'true'
- }
-
- # Create operation.
- operation = {
- 'operator': 'ADD',
- 'operand': budget
- }
-
- response = budget_service.mutate([operation])
- return response['value'][0]
-
-
-def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id):
- """Create a Campaign with a Shared Bidding Strategy.
-
- Args:
- client: AdWordsClient the client to run the example with.
- bidding_strategy_id: string the bidding strategy ID to use.
- budget_id: string the shared budget ID to use.
-
- Returns:
- dict An object representing a campaign.
- """
- # Initialize appropriate service.
- campaign_service = client.GetService('CampaignService', version='v201406')
-
- # Create campaign.
- campaign = {
- 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(),
- 'budget': {
- 'budgetId': budget_id
- },
- 'biddingStrategyConfiguration': {
- 'biddingStrategyId': bidding_strategy_id
- },
- 'advertisingChannelType': 'SEARCH',
- 'settings': [{
- 'xsi_type': 'KeywordMatchSetting',
- 'optIn': 'true'
- }],
- 'networkSetting': {
- 'targetGoogleSearch': 'true',
- 'targetSearchNetwork': 'true',
- 'targetContentNetwork': 'true'
- }
- }
-
- # Create operation.
- operation = {
- 'operator': 'ADD',
- 'operand': campaign
- }
-
- response = campaign_service.mutate([operation])
- new_campaign = response['value'][0]
-
- print ('Campaign with name \'%s\', ID \'%s\' and bidding scheme ID \'%s\' '
- 'was created.' %
- (new_campaign['name'], new_campaign['id'],
- new_campaign['biddingStrategyConfiguration']['biddingStrategyId']))
-
- return new_campaign
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
- main(adwords_client, BUDGET_ID)
diff --git a/examples/adwords/v201406/basic_operations/__init__.py b/examples/adwords/v201406/basic_operations/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/examples/adwords/v201406/basic_operations/add_ad_groups.py b/examples/adwords/v201406/basic_operations/add_ad_groups.py
deleted file mode 100755
index 4c7e95b4..00000000
--- a/examples/adwords/v201406/basic_operations/add_ad_groups.py
+++ /dev/null
@@ -1,116 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds ad groups to a given campaign.
-
-To get ad groups, run get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README..
-
-Tags: AdGroupService.mutate
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-import uuid
-
-from googleads import adwords
-
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-
-
-def main(client, campaign_id):
- # Initialize appropriate service.
- ad_group_service = client.GetService('AdGroupService', version='v201406')
-
- # Construct operations and add ad groups.
- operations = [{
- 'operator': 'ADD',
- 'operand': {
- 'campaignId': campaign_id,
- 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(),
- 'status': 'ENABLED',
- 'biddingStrategyConfiguration': {
- 'bids': [
- {
- 'xsi_type': 'CpcBid',
- 'bid': {
- 'microAmount': '1000000'
- },
- }
- ]
- },
- 'settings': [
- {
- # Targeting restriction settings - these settings only affect
- # serving for the Display Network.
- 'xsi_type': 'TargetingSetting',
- 'details': [
- # Restricting to serve ads that match your ad group
- # placements. This is equivalent to choosing
- # "Target and bid" in the UI.
- {
- 'xsi_type': 'TargetingSettingDetail',
- 'criterionTypeGroup': 'PLACEMENT',
- 'targetAll': 'false',
- },
- # Using your ad group verticals only for bidding. This is
- # equivalent to choosing "Bid only" in the UI.
- {
- 'xsi_type': 'TargetingSettingDetail',
- 'criterionTypeGroup': 'VERTICAL',
- 'targetAll': 'true',
- },
- ]
- }
- ]
- }
- }, {
- 'operator': 'ADD',
- 'operand': {
- 'campaignId': campaign_id,
- 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(),
- 'status': 'ENABLED',
- 'biddingStrategyConfiguration': {
- 'bids': [
- {
- 'xsi_type': 'CpcBid',
- 'bid': {
- 'microAmount': '1000000'
- }
- }
- ]
- }
- }
- }]
- ad_groups = ad_group_service.mutate(operations)
-
- # Display results.
- for ad_group in ad_groups['value']:
- print ('Ad group with name \'%s\' and id \'%s\' was added.'
- % (ad_group['name'], ad_group['id']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201406/basic_operations/add_campaigns.py b/examples/adwords/v201406/basic_operations/add_campaigns.py
deleted file mode 100755
index 6c5547fd..00000000
--- a/examples/adwords/v201406/basic_operations/add_campaigns.py
+++ /dev/null
@@ -1,141 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds campaigns.
-
-To get campaigns, run get_campaigns.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignService.mutate
-Tags: BudgetService.mutate
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-import datetime
-import uuid
-
-from googleads import adwords
-
-
-def main(client):
- # Initialize appropriate services.
- campaign_service = client.GetService('CampaignService', version='v201406')
- budget_service = client.GetService('BudgetService', version='v201406')
-
- # Create a budget, which can be shared by multiple campaigns.
- budget = {
- 'name': 'Interplanetary budget #%s' % uuid.uuid4(),
- 'amount': {
- 'microAmount': '50000000'
- },
- 'deliveryMethod': 'STANDARD',
- 'period': 'DAILY'
- }
-
- budget_operations = [{
- 'operator': 'ADD',
- 'operand': budget
- }]
-
- # Add the budget.
- budget_id = budget_service.mutate(budget_operations)['value'][0][
- 'budgetId']
-
- # Construct operations and add campaigns.
- operations = [{
- 'operator': 'ADD',
- 'operand': {
- 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(),
- 'status': 'PAUSED',
- 'advertisingChannelType': 'SEARCH',
- 'biddingStrategyConfiguration': {
- 'biddingStrategyType': 'MANUAL_CPC',
- },
- 'endDate': (datetime.datetime.now() +
- datetime.timedelta(365)).strftime('%Y%m%d'),
- # Note that only the budgetId is required
- 'budget': {
- 'budgetId': budget_id
- },
- 'networkSetting': {
- 'targetGoogleSearch': 'true',
- 'targetSearchNetwork': 'true',
- 'targetContentNetwork': 'false',
- 'targetPartnerSearchNetwork': 'false'
- },
- # Optional fields
- 'startDate': (datetime.datetime.now() +
- datetime.timedelta(1)).strftime('%Y%m%d'),
- 'adServingOptimizationStatus': 'ROTATE',
- 'frequencyCap': {
- 'impressions': '5',
- 'timeUnit': 'DAY',
- 'level': 'ADGROUP'
- },
- 'settings': [
- {
- 'xsi_type': 'GeoTargetTypeSetting',
- 'positiveGeoTargetType': 'DONT_CARE',
- 'negativeGeoTargetType': 'DONT_CARE'
- },
- {
- 'xsi_type': 'KeywordMatchSetting',
- 'optIn': 'false'
- }
- ]
- }
- }, {
- 'operator': 'ADD',
- 'operand': {
- 'name': 'Interplanetary Cruise banner #%s' % uuid.uuid4(),
- 'status': 'PAUSED',
- 'biddingStrategyConfiguration': {
- 'biddingStrategyType': 'MANUAL_CPC'
- },
- 'endDate': (datetime.datetime.now() +
- datetime.timedelta(365)).strftime('%Y%m%d'),
- # Note that only the budgetId is required
- 'budget': {
- 'budgetId': budget_id
- },
- 'advertisingChannelType': 'DISPLAY',
- 'settings': [
- {
- 'xsi_type': 'KeywordMatchSetting',
- 'optIn': 'false'
- }
- ]
- }
- }]
- campaigns = campaign_service.mutate(operations)
-
- # Display results.
- for campaign in campaigns['value']:
- print ('Campaign with name \'%s\' and id \'%s\' was added.'
- % (campaign['name'], campaign['id']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201406/basic_operations/add_keywords.py b/examples/adwords/v201406/basic_operations/add_keywords.py
deleted file mode 100755
index f510e8cf..00000000
--- a/examples/adwords/v201406/basic_operations/add_keywords.py
+++ /dev/null
@@ -1,95 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds ad group criteria to an ad group.
-
-To get ad groups, run get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupCriterionService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Initialize appropriate service.
- ad_group_criterion_service = client.GetService(
- 'AdGroupCriterionService', version='v201406')
-
- # Construct keyword ad group criterion object.
- keyword1 = {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Keyword',
- 'matchType': 'BROAD',
- 'text': 'mars'
- },
- # These fields are optional.
- 'userStatus': 'PAUSED',
- 'destinationUrl': 'http://example.com/mars'
- }
-
- keyword2 = {
- 'xsi_type': 'NegativeAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Keyword',
- 'matchType': 'EXACT',
- 'text': 'pluto'
- }
- }
-
- # Construct operations and add ad group criteria.
- operations = [
- {
- 'operator': 'ADD',
- 'operand': keyword1
- },
- {
- 'operator': 'ADD',
- 'operand': keyword2
- }
- ]
- ad_group_criteria = ad_group_criterion_service.mutate(
- operations)['value']
-
- # Display results.
- for criterion in ad_group_criteria:
- print ('Keyword ad group criterion with ad group id \'%s\', criterion id '
- '\'%s\', text \'%s\', and match type \'%s\' was added.'
- % (criterion['adGroupId'], criterion['criterion']['id'],
- criterion['criterion']['text'],
- criterion['criterion']['matchType']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201406/basic_operations/add_text_ads.py b/examples/adwords/v201406/basic_operations/add_text_ads.py
deleted file mode 100755
index 036e0149..00000000
--- a/examples/adwords/v201406/basic_operations/add_text_ads.py
+++ /dev/null
@@ -1,98 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds several text ads to a given ad group.
-
-To get ad_group_id, run get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupAdService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Initialize appropriate service.
- ad_group_ad_service = client.GetService('AdGroupAdService', version='v201406')
-
- # Construct operations and add ads.
- # If needed, you could specify an exemption request here, e.g.:
- # 'exemptionRequests': [{
- # # This comes back in a PolicyViolationError.
- # 'key' {
- # 'policyName': '...',
- # 'violatingText': '...'
- # }
- # }]
- operations = [
- {
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'AdGroupAd',
- 'adGroupId': ad_group_id,
- 'ad': {
- 'xsi_type': 'TextAd',
- 'url': 'http://www.example.com',
- 'displayUrl': 'example.com',
- 'description1': 'Visit the Red Planet in style.',
- 'description2': 'Low-gravity fun for everyone!',
- 'headline': 'Luxury Cruise to Mars'
- },
- # Optional fields.
- 'status': 'PAUSED'
- }
- },
- {
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'AdGroupAd',
- 'adGroupId': ad_group_id,
- 'ad': {
- 'xsi_type': 'TextAd',
- 'url': 'http://www.example.com',
- 'displayUrl': 'example.com',
- 'description1': 'Enjoy your stay at Red Planet.',
- 'description2': 'Buy your tickets now!',
- 'headline': 'Luxury Cruise to Mars'
- }
- }
- }
- ]
- ads = ad_group_ad_service.mutate(operations)
-
- # Display results.
- for ad in ads['value']:
- print ('Ad with id \'%s\' and of type \'%s\' was added.'
- % (ad['ad']['id'], ad['ad']['Ad.Type']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201406/basic_operations/get_ad_groups.py b/examples/adwords/v201406/basic_operations/get_ad_groups.py
deleted file mode 100755
index a2a1f822..00000000
--- a/examples/adwords/v201406/basic_operations/get_ad_groups.py
+++ /dev/null
@@ -1,80 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all ad groups for a given campaign.
-
-To add an ad group, run add_ad_group.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupService.get
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-PAGE_SIZE = 500
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-
-
-def main(client, campaign_id):
- # Initialize appropriate service.
- ad_group_service = client.GetService('AdGroupService', version='v201406')
-
- # Construct selector and get all ad groups.
- offset = 0
- selector = {
- 'fields': ['Id', 'Name', 'Status'],
- 'predicates': [
- {
- 'field': 'CampaignId',
- 'operator': 'EQUALS',
- 'values': [campaign_id]
- }
- ],
- 'paging': {
- 'startIndex': str(offset),
- 'numberResults': str(PAGE_SIZE)
- }
- }
- more_pages = True
- while more_pages:
- page = ad_group_service.get(selector)
-
- # Display results.
- if 'entries' in page:
- for ad_group in page['entries']:
- print ('Ad group with name \'%s\', id \'%s\' and status \'%s\' was '
- 'found.' % (ad_group['name'], ad_group['id'],
- ad_group['status']))
- else:
- print 'No ad groups were found.'
- offset += PAGE_SIZE
- selector['paging']['startIndex'] = str(offset)
- more_pages = offset < int(page['totalNumEntries'])
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201406/basic_operations/get_campaigns.py b/examples/adwords/v201406/basic_operations/get_campaigns.py
deleted file mode 100755
index 9bbf338e..00000000
--- a/examples/adwords/v201406/basic_operations/get_campaigns.py
+++ /dev/null
@@ -1,77 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all campaigns.
-
-To add a campaign, run add_campaign.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignService.get
-"""
-
-__author__ = 'Joseph DiLallo'
-
-import logging
-import time
-
-from googleads import adwords
-
-logging.basicConfig(level=logging.INFO)
-logging.getLogger('suds.transport').setLevel(logging.DEBUG)
-
-
-PAGE_SIZE = 100
-
-
-def main(client):
- # Initialize appropriate service.
- campaign_service = client.GetService('CampaignService', version='v201406')
-
- # Construct selector and get all campaigns.
- offset = 0
- selector = {
- 'fields': ['Id', 'Name', 'Status'],
- 'paging': {
- 'startIndex': str(offset),
- 'numberResults': str(PAGE_SIZE)
- }
- }
-
- more_pages = True
- while more_pages:
- page = campaign_service.get(selector)
-
- # Display results.
- if 'entries' in page:
- for campaign in page['entries']:
- print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was '
- 'found.' % (campaign['id'], campaign['name'],
- campaign['status']))
- else:
- print 'No campaigns were found.'
- offset += PAGE_SIZE
- selector['paging']['startIndex'] = str(offset)
- more_pages = offset < int(page['totalNumEntries'])
- time.sleep(1)
-
-
-if __name__ == '__main__':
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
- main(adwords_client)
diff --git a/examples/adwords/v201406/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201406/basic_operations/get_campaigns_with_awql.py
deleted file mode 100755
index 4bb219f9..00000000
--- a/examples/adwords/v201406/basic_operations/get_campaigns_with_awql.py
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all campaigns with AWQL.
-
-To add a campaign, run add_campaign.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignService.query
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-import time
-
-from googleads import adwords
-
-
-PAGE_SIZE = 100
-
-
-def main(client):
- # Initialize appropriate service.
- campaign_service = client.GetService('CampaignService', version='v201406')
-
- # Construct query and get all campaigns.
- offset = 0
- query = 'SELECT Id, Name, Status ORDER BY Name'
-
- more_pages = True
- while more_pages:
- page = campaign_service.query(query + ' LIMIT %s, %s' % (offset, PAGE_SIZE))
-
- # Display results.
- if 'entries' in page:
- for campaign in page['entries']:
- print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was '
- 'found.' % (campaign['id'], campaign['name'],
- campaign['status']))
- else:
- print 'No campaigns were found.'
- offset += PAGE_SIZE
- more_pages = offset < int(page['totalNumEntries'])
- time.sleep(1)
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
- main(adwords_client)
diff --git a/examples/adwords/v201406/basic_operations/get_keywords.py b/examples/adwords/v201406/basic_operations/get_keywords.py
deleted file mode 100755
index 492af1dd..00000000
--- a/examples/adwords/v201406/basic_operations/get_keywords.py
+++ /dev/null
@@ -1,81 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all ad group criteria in an account.
-
-To add keywords, run add_keywords.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupCriterionService.get
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-PAGE_SIZE = 500
-
-
-def main(client):
- # Initialize appropriate service.
- ad_group_criterion_service = client.GetService(
- 'AdGroupCriterionService', version='v201406')
-
- # Construct selector and get all ad group criteria.
- offset = 0
- selector = {
- 'fields': ['AdGroupId', 'Id', 'Text', 'KeywordMatchType', 'PlacementUrl'],
- 'predicates': [{
- 'field': 'CriteriaType',
- 'operator': 'EQUALS',
- 'values': ['KEYWORD']
- }],
- 'paging': {
- 'startIndex': str(offset),
- 'numberResults': str(PAGE_SIZE)
- }
- }
- more_pages = True
- while more_pages:
- page = ad_group_criterion_service.get(selector)
-
- # Display results.
- if 'entries' in page:
- for criterion in page['entries']:
- print ('Keyword ad group criterion with ad group id \'%s\', criterion '
- 'id \'%s\', text \'%s\', and match type \'%s\' was found.'
- % (criterion['adGroupId'], criterion['criterion']['id'],
- criterion['criterion']['text'],
- criterion['criterion']['matchType']))
- else:
- print 'No keywords were found.'
- offset += PAGE_SIZE
- selector['paging']['startIndex'] = str(offset)
- more_pages = offset < int(page['totalNumEntries'])
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201406/basic_operations/get_text_ads.py b/examples/adwords/v201406/basic_operations/get_text_ads.py
deleted file mode 100755
index 11986346..00000000
--- a/examples/adwords/v201406/basic_operations/get_text_ads.py
+++ /dev/null
@@ -1,85 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all text ads for a given ad group.
-
-To add an ad, run add_text_ads.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupAdService.get
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-PAGE_SIZE = 500
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Initialize appropriate service.
- ad_group_ad_service = client.GetService('AdGroupAdService', version='v201406')
-
- # Construct selector and get all ads for a given ad group.
- offset = 0
- selector = {
- 'fields': ['Id', 'AdGroupId', 'Status'],
- 'predicates': [
- {
- 'field': 'AdGroupId',
- 'operator': 'EQUALS',
- 'values': [ad_group_id]
- },
- {
- 'field': 'AdType',
- 'operator': 'EQUALS',
- 'values': ['TEXT_AD']
- }
- ],
- 'paging': {
- 'startIndex': str(offset),
- 'numberResults': str(PAGE_SIZE)
- }
- }
- more_pages = True
- while more_pages:
- page = ad_group_ad_service.get(selector)
-
- # Display results.
- if 'entries' in page:
- for ad in page['entries']:
- print ('Ad with id \'%s\', status \'%s\', and of type \'%s\' was found.'
- % (ad['ad']['id'], ad['status'], ad['ad']['Ad.Type']))
- else:
- print 'No ads were found.'
- offset += PAGE_SIZE
- selector['paging']['startIndex'] = str(offset)
- more_pages = offset < int(page['totalNumEntries'])
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201406/basic_operations/pause_ad.py b/examples/adwords/v201406/basic_operations/pause_ad.py
deleted file mode 100755
index 3b9b9c5a..00000000
--- a/examples/adwords/v201406/basic_operations/pause_ad.py
+++ /dev/null
@@ -1,65 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates status for a given ad.
-
-To get ads, run get_text_ads.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupAdService.mutate
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-AD_ID = 'INSERT_AD_ID_HERE'
-
-
-def main(client, ad_group_id, ad_id):
- # Initialize appropriate service.
- ad_group_ad_service = client.GetService('AdGroupAdService', version='v201406')
-
- # Construct operations and update an ad.
- operations = [{
- 'operator': 'SET',
- 'operand': {
- 'adGroupId': ad_group_id,
- 'ad': {
- 'id': ad_id,
- },
- 'status': 'PAUSED'
- }
- }]
- ads = ad_group_ad_service.mutate(operations)
-
- # Display results.
- for ad in ads['value']:
- print 'Ad with id \'%s\' was updated.'% ad['ad']['id']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID, AD_ID)
diff --git a/examples/adwords/v201406/basic_operations/remove_ad.py b/examples/adwords/v201406/basic_operations/remove_ad.py
deleted file mode 100755
index 722ccc6b..00000000
--- a/examples/adwords/v201406/basic_operations/remove_ad.py
+++ /dev/null
@@ -1,66 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example deletes an ad using the 'REMOVE' operator.
-
-To get ads, run get_text_ads.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupAdService.mutate
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-AD_ID = 'INSERT_AD_ID_HERE'
-
-
-def main(client, ad_group_id, ad_id):
- # Initialize appropriate service.
- ad_group_ad_service = client.GetService('AdGroupAdService', version='v201406')
-
- # Construct operations and delete ad.
- operations = [{
- 'operator': 'REMOVE',
- 'operand': {
- 'xsi_type': 'AdGroupAd',
- 'adGroupId': ad_group_id,
- 'ad': {
- 'id': ad_id
- }
- }
- }]
- result = ad_group_ad_service.mutate(operations)
-
- # Display results.
- for ad in result['value']:
- print ('Ad with id \'%s\' and type \'%s\' was deleted.'
- % (ad['ad']['id'], ad['ad']['Ad.Type']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID, AD_ID)
diff --git a/examples/adwords/v201406/basic_operations/remove_ad_group.py b/examples/adwords/v201406/basic_operations/remove_ad_group.py
deleted file mode 100755
index cd126cb3..00000000
--- a/examples/adwords/v201406/basic_operations/remove_ad_group.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example deletes an ad group by setting the status to 'REMOVED'.
-
-To get ad groups, run get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupService.mutate
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Initialize appropriate service.
- ad_group_service = client.GetService('AdGroupService', version='v201406')
-
- # Construct operations and delete ad group.
- operations = [{
- 'operator': 'SET',
- 'operand': {
- 'id': ad_group_id,
- 'status': 'REMOVED'
- }
- }]
- result = ad_group_service.mutate(operations)
-
- # Display results.
- for ad_group in result['value']:
- print ('Ad group with name \'%s\' and id \'%s\' was deleted.'
- % (ad_group['name'], ad_group['id']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201406/basic_operations/remove_campaign.py b/examples/adwords/v201406/basic_operations/remove_campaign.py
deleted file mode 100755
index 3243e86a..00000000
--- a/examples/adwords/v201406/basic_operations/remove_campaign.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example deletes a campaign by setting the status to 'REMOVED'.
-
-To get campaigns, run get_campaigns.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignService.mutate
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-
-
-def main(client, campaign_id):
- # Initialize appropriate service.
- campaign_service = client.GetService('CampaignService', version='v201406')
-
- # Construct operations and delete campaign.
- operations = [{
- 'operator': 'SET',
- 'operand': {
- 'id': campaign_id,
- 'status': 'REMOVED'
- }
- }]
- result = campaign_service.mutate(operations)
-
- # Display results.
- for campaign in result['value']:
- print ('Campaign with name \'%s\' and id \'%s\' was deleted.'
- % (campaign['name'], campaign['id']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201406/basic_operations/remove_keyword.py b/examples/adwords/v201406/basic_operations/remove_keyword.py
deleted file mode 100755
index 23f94eb5..00000000
--- a/examples/adwords/v201406/basic_operations/remove_keyword.py
+++ /dev/null
@@ -1,72 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example deletes an ad group criterion using the 'REMOVE' operator.
-
-To get ad group criteria, run get_keywords.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupCriterionService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-CRITERION_ID = 'INSERT_CRITERION_ID_HERE'
-
-
-def main(client, ad_group_id, criterion_id):
- # Initialize appropriate service.
- ad_group_criterion_service = client.GetService(
- 'AdGroupCriterionService', version='v201406')
-
- # Construct operations and delete ad group criteria.
- operations = [
- {
- 'operator': 'REMOVE',
- 'operand': {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'id': criterion_id
- }
- }
- }
- ]
- result = ad_group_criterion_service.mutate(operations)
-
- # Display results.
- for criterion in result['value']:
- print ('Ad group criterion with ad group id \'%s\', criterion id \'%s\', '
- 'and type \'%s\' was deleted.'
- % (criterion['adGroupId'], criterion['criterion']['id'],
- criterion['criterion']['Criterion.Type']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID, CRITERION_ID)
diff --git a/examples/adwords/v201406/basic_operations/update_ad_group.py b/examples/adwords/v201406/basic_operations/update_ad_group.py
deleted file mode 100755
index 4893d505..00000000
--- a/examples/adwords/v201406/basic_operations/update_ad_group.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates status for a given ad group.
-
-To get ad groups, run get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupService.mutate
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Initialize appropriate service.
- ad_group_service = client.GetService('AdGroupService', version='v201406')
-
- # Construct operations and update an ad group.
- operations = [{
- 'operator': 'SET',
- 'operand': {
- 'id': ad_group_id,
- 'status': 'PAUSED'
- }
- }]
- ad_groups = ad_group_service.mutate(operations)
-
- # Display results.
- for ad_group in ad_groups['value']:
- print ('Ad group with name \'%s\' and id \'%s\' was updated.'
- % (ad_group['name'], ad_group['id']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201406/basic_operations/update_campaign.py b/examples/adwords/v201406/basic_operations/update_campaign.py
deleted file mode 100755
index f93143e3..00000000
--- a/examples/adwords/v201406/basic_operations/update_campaign.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates a campaign by setting its status to PAUSED.
-
-To get campaigns, run get_campaigns.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignService.mutate
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-
-
-def main(client, campaign_id):
- # Initialize appropriate service.
- campaign_service = client.GetService('CampaignService', version='v201406')
-
- # Construct operations and update campaign.
- operations = [{
- 'operator': 'SET',
- 'operand': {
- 'id': campaign_id,
- 'status': 'PAUSED'
- }
- }]
- campaigns = campaign_service.mutate(operations)
-
- # Display results.
- for campaign in campaigns['value']:
- print ('Campaign with name \'%s\' and id \'%s\' was updated.'
- % (campaign['name'], campaign['id']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201406/basic_operations/update_keyword.py b/examples/adwords/v201406/basic_operations/update_keyword.py
deleted file mode 100755
index c6b2e5ab..00000000
--- a/examples/adwords/v201406/basic_operations/update_keyword.py
+++ /dev/null
@@ -1,87 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates the bid of a keyword.
-
-To add a keyword, run add_keywords.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupCriterionService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE'
-
-
-def main(client, ad_group_id, criterion_id):
- # Initialize appropriate service.
- ad_group_criterion_service = client.GetService(
- 'AdGroupCriterionService', version='v201406')
-
- # Construct operations and update bids.
-
- operations = [{
- 'operator': 'SET',
- 'operand': {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'id': criterion_id,
- },
- 'biddingStrategyConfiguration': {
- 'bids': [
- {
- 'xsi_type': 'CpcBid',
- 'bid': {
- 'microAmount': '1000000'
- }
- }
- ]
- }
- }
- }]
- ad_group_criteria = ad_group_criterion_service.mutate(operations)
-
- # Display results.
- if 'value' in ad_group_criteria:
- for criterion in ad_group_criteria['value']:
- if criterion['criterion']['Criterion.Type'] == 'Keyword':
- print ('Ad group criterion with ad group id \'%s\' and criterion id '
- '\'%s\' currently has bids:'
- % (criterion['adGroupId'], criterion['criterion']['id']))
- for bid in criterion['biddingStrategyConfiguration']['bids']:
- print '\tType: \'%s\', value: %s' % (bid['Bids.Type'],
- bid['bid']['microAmount'])
- else:
- print 'No ad group criteria were updated.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID, CRITERION_ID)
diff --git a/examples/adwords/v201406/campaign_management/__init__.py b/examples/adwords/v201406/campaign_management/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/examples/adwords/v201406/campaign_management/add_campaign_labels.py b/examples/adwords/v201406/campaign_management/add_campaign_labels.py
deleted file mode 100755
index cfc87dd2..00000000
--- a/examples/adwords/v201406/campaign_management/add_campaign_labels.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds a label to multiple campaigns.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignService.mutateLabel
-"""
-
-__author__ = 'Mark Saniscalchi'
-
-from googleads import adwords
-
-
-CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE'
-CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE'
-LABEL_ID = 'INSERT_LABEL_ID_HERE'
-
-
-def main(client, campaign_id1, campaign_id2, label_id):
- # Initialize appropriate service.
- campaign_service = client.GetService('CampaignService', version='v201406')
-
- operations = [
- {
- 'operator': 'ADD',
- 'operand': {
- 'campaignId': campaign_id1,
- 'labelId': label_id,
- }
- },
- {
- 'operator': 'ADD',
- 'operand': {
- 'campaignId': campaign_id2,
- 'labelId': label_id,
- }
- }
- ]
-
- result = campaign_service.mutateLabel(operations)
-
- # Display results.
- for label in result['value']:
- print ('CampaignLabel with campaignId \'%s\' and labelId \'%s\' was added.'
- % (label['campaignId'], label['labelId']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2, LABEL_ID)
diff --git a/examples/adwords/v201406/campaign_management/add_experiment.py b/examples/adwords/v201406/campaign_management/add_experiment.py
deleted file mode 100755
index 51975763..00000000
--- a/examples/adwords/v201406/campaign_management/add_experiment.py
+++ /dev/null
@@ -1,132 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates an experiment.
-
-The created experiment is using a query percentage of 10, which defines what
-fraction of auctions should go to the control split (90%) vs. the experiment
-split (10%), then adds experimental bid changes for an ad group, and adds an
-experiment-only keyword. To get campaigns, run get_campaigns.py. To get ad
-groups, run get_ad_groups.py. To get keywords, run get_keywords.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ExperimentService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-import datetime
-import uuid
-
-from googleads import adwords
-
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, campaign_id, ad_group_id):
- # Initialize appropriate service.
- experiment_service = client.GetService('ExperimentService', version='v201406')
- ad_group_service = client.GetService('AdGroupService', version='v201406')
- ad_group_criterion_service = client.GetService(
- 'AdGroupCriterionService', version='v201406')
-
- # Construct operations and add experiment.
- tomorrow = datetime.datetime.now() + datetime.timedelta(1)
- thirty_days = datetime.datetime.now() + datetime.timedelta(30)
- operations = [{
- 'operator': 'ADD',
- 'operand': {
- 'campaignId': campaign_id,
- 'name': 'Interplanetary Experiment #%s' % uuid.uuid4(),
- 'queryPercentage': '10',
- 'startDateTime': tomorrow.strftime('%Y%m%d %H%M%S'),
- # Optional fields.
- 'status': 'ENABLED',
- 'endDateTime': thirty_days.strftime('%Y%m%d %H%M%S')
- }
- }]
- result = experiment_service.mutate(operations)
-
- # Display results.
- for experiment in result['value']:
- print ('Experiment with name \'%s\' and id \'%s\' was added.'
- % (experiment['name'], experiment['id']))
-
- # Construct operations and update ad group.
- operations = [{
- 'operator': 'SET',
- 'operand': {
- 'id': ad_group_id,
- 'experimentData': {
- 'xsi_type': 'AdGroupExperimentData',
- 'experimentId': experiment['id'],
- 'experimentDeltaStatus': 'MODIFIED',
- 'experimentBidMultipliers': {
- 'xsi_type': 'ManualCPCAdGroupExperimentBidMultipliers',
- 'maxCpcMultiplier': {
- 'multiplier': '0.5'
- }
- }
- }
- }
- }]
- result = ad_group_service.mutate(operations)
-
- # Display results.
- for ad_group in result['value']:
- print ('Ad group with name \'%s\' and id \'%s\' was updated in the '
- 'experiment.' % (ad_group['name'], ad_group['id']))
-
- # Construct operations and add ad group crierion.
- operations = [{
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group['id'],
- 'criterion': {
- 'xsi_type': 'Keyword',
- 'matchType': 'BROAD',
- 'text': 'mars cruise'
- },
- 'experimentData': {
- 'xsi_type': 'BiddableAdGroupCriterionExperimentData',
- 'experimentId': experiment['id'],
- 'experimentDeltaStatus': 'EXPERIMENT_ONLY'
- }
- }
- }]
- result = ad_group_criterion_service.mutate(operations)
-
- # Display results.
- for criterion in result['value']:
- print ('Ad group criterion with ad group id \'%s\' and criterion '
- 'id \'%s\' was added to the experiment.'
- % (criterion['adGroupId'], criterion['criterion']['id']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID, AD_GROUP_ID)
diff --git a/examples/adwords/v201406/campaign_management/add_keywords_in_bulk.py b/examples/adwords/v201406/campaign_management/add_keywords_in_bulk.py
deleted file mode 100755
index e4ddc91b..00000000
--- a/examples/adwords/v201406/campaign_management/add_keywords_in_bulk.py
+++ /dev/null
@@ -1,141 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code sample illustrates how to perform asynchronous requests.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: MutateJobService.mutate
-Tags: MutateJobService.get
-Tags: MutateJobService.getResult
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-import random
-import re
-import time
-
-from googleads import adwords
-from googleads import errors
-
-
-RETRY_INTERVAL = 10
-RETRIES_COUNT = 30
-KEYWORD_NUMBER = 100
-INDEX_REGEX = r'operations\[(\d+)\].operand'
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Initialize appropriate service.
- mutate_job_service = client.GetService('MutateJobService', version='v201406')
-
- # Create list of all operations for the job.
- operations = []
-
- # Create AdGroupCriterionOperations to add keywords.
- for i in range(KEYWORD_NUMBER):
- keyword = 'mars%d' % i
- if random.randint(1, 10) == 1:
- keyword += '!!!'
- operations.append({
- 'xsi_type': 'AdGroupCriterionOperation',
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Keyword',
- 'matchType': 'BROAD',
- 'text': keyword
- }
- }
- })
-
- # You can specify up to 3 job IDs that must successfully complete before
- # this job can be processed.
- policy = {
- 'prerequisiteJobIds': []
- }
-
- # Call mutate to create a new job.
- response = mutate_job_service.mutate(operations, policy)
-
- if not response:
- raise errors.GoogleAdsError('Failed to submit a job; aborting.')
-
- job_id = response['id']
- print 'Job with ID %s was successfully created.' % job_id
-
- # Create selector to retrieve job status and wait for it to complete.
- selector = {
- 'xsi_type': 'BulkMutateJobSelector',
- 'jobIds': [job_id]
- }
-
- time.sleep(RETRY_INTERVAL)
- # Poll for job status until it's finished.
- print 'Retrieving job status...'
- for i in range(RETRIES_COUNT):
- job_status_response = mutate_job_service.get(selector)
- status = job_status_response[0]['status']
- if status in ('COMPLETED', 'FAILED'):
- break
- print ('[%d] Current status is \'%s\', waiting %d seconds to retry...' %
- (i, status, RETRY_INTERVAL))
- time.sleep(RETRY_INTERVAL)
-
- if status == 'FAILED':
- raise errors.GoogleAdsError('Job failed with reason: \'%s\'' %
- job_status_response[0]['failure_reason'])
- if status in ('PROCESSING', 'PENDING'):
- raise errors.GoogleAdsError('Job did not complete within %d seconds' %
- (RETRY_INTERVAL * (RETRIES_COUNT - 1)))
-
- # Status must be COMPLETED.
- # Get the job result. Here we re-use the same selector.
- result_response = mutate_job_service.getResult(selector)
-
- # Output results.
- index = 0
- for result in result_response['SimpleMutateResult']['results']:
- if 'PlaceHolder' in result:
- print 'Operation [%d] - FAILED' % index
- else:
- print 'Operation [%d] - SUCCEEDED' % index
- index += 1
-
- # Output errors
- for error in result_response['SimpleMutateResult']['errors']:
- index = int(re.search(INDEX_REGEX, error['fieldPath']).group(1))
- reason = error['reason']
- keyword = operations[index]['operand']['criterion']['text']
- print ('ERROR - keyword \'%s\' failed due to \'%s\'' %
- (keyword, reason))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201406/campaign_management/add_location_extension.py b/examples/adwords/v201406/campaign_management/add_location_extension.py
deleted file mode 100755
index 96b2a4df..00000000
--- a/examples/adwords/v201406/campaign_management/add_location_extension.py
+++ /dev/null
@@ -1,114 +0,0 @@
-#!/usr/bin/python
-# -*- coding: UTF-8 -*-
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds a campaign ad extension to a given campaign.
-
-To get campaigns, run get_campaigns.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: GeoLocationService.get, CampaignAdExtensionService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-
-
-def main(client, campaign_id):
- # Initialize appropriate service.
- geo_location_service = client.GetService(
- 'GeoLocationService', version='v201406')
- campaign_ad_extension_service = client.GetService(
- 'CampaignAdExtensionService', version='v201406')
-
- # Construct selector and get geo location info for given addresses.
- selector = {
- 'addresses': [
- {
- 'streetAddress': '1600 Amphitheatre Parkway',
- 'cityName': 'Mountain View',
- 'provinceCode': 'US-CA',
- 'provinceName': 'California',
- 'postalCode': '94043',
- 'countryCode': 'US'
- },
- {
- 'streetAddress': u'38 avenue de l\'Opéra',
- 'cityName': 'Paris',
- 'postalCode': '75002',
- 'countryCode': 'FR'
- }
- ]
- }
- geo_locations = geo_location_service.get(selector)
-
- # Construct operations and add campaign ad extension.
- operations = [
- {
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'CampaignAdExtension',
- 'campaignId': campaign_id,
- 'adExtension': {
- 'xsi_type': 'LocationExtension',
- 'address': geo_locations[0]['address'],
- 'geoPoint': geo_locations[0]['geoPoint'],
- 'encodedLocation': geo_locations[0]['encodedLocation'],
- 'source': 'ADWORDS_FRONTEND',
- # Optional fields.
- 'companyName': 'ACME Inc.',
- 'phoneNumber': '(650) 253-0000'
- }
- }
- },
- {
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'CampaignAdExtension',
- 'campaignId': campaign_id,
- 'adExtension': {
- 'xsi_type': 'LocationExtension',
- 'address': geo_locations[1]['address'],
- 'geoPoint': geo_locations[1]['geoPoint'],
- 'encodedLocation': geo_locations[1]['encodedLocation'],
- 'source': 'ADWORDS_FRONTEND'
- }
- }
- }
- ]
- ad_extensions = campaign_ad_extension_service.mutate(operations)
-
- # Display results.
- for ad_extension in ad_extensions['value']:
- print ('Campaign ad extension with id \'%s\' and status \'%s\' was added.'
- % (ad_extension['adExtension']['id'], ad_extension['status']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201406/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201406/campaign_management/get_all_disapproved_ads.py
deleted file mode 100755
index bad1d446..00000000
--- a/examples/adwords/v201406/campaign_management/get_all_disapproved_ads.py
+++ /dev/null
@@ -1,78 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all disapproved ads for a given campaign.
-
-To add an ad, run add_ads.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupAdService.get
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-
-
-def main(client, campaign_id):
- # Initialize appropriate service.
- ad_group_ad_service = client.GetService('AdGroupAdService', version='v201406')
-
- # Construct selector and get all ads for a given ad group.
- selector = {
- 'fields': ['Id', 'AdGroupAdDisapprovalReasons'],
- 'predicates': [
- {
- 'field': 'CampaignId',
- 'operator': 'EQUALS',
- 'values': [campaign_id]
- },
- {
- 'field': 'AdGroupCreativeApprovalStatus',
- 'operator': 'IN',
- 'values': ['DISAPPROVED']
- }
- ]
- }
- ads = ad_group_ad_service.get(selector)
-
- # Display results.
- if 'entries' in ads:
- for ad in ads['entries']:
- print ('Ad with id \'%s\' was disapproved for the following reasons: '
- % (ad['ad']['id']))
- if ad['ad'].get('disapprovalReasons'):
- for reason in ad['ad']['disapprovalReasons']:
- print '\t%s' % reason
- else:
- print '\tReason not provided.'
- else:
- print 'No disapproved ads were found.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201406/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201406/campaign_management/get_all_disapproved_ads_with_awql.py
deleted file mode 100755
index 925864be..00000000
--- a/examples/adwords/v201406/campaign_management/get_all_disapproved_ads_with_awql.py
+++ /dev/null
@@ -1,67 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all disapproved ads for a given campaign with AWQL.
-
-To add an ad, run add_ads.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupAdService.get
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-
-
-def main(client, campaign_id):
- # Initialize appropriate service.
- ad_group_ad_service = client.GetService('AdGroupAdService', version='v201406')
-
- # Construct query and get all ads for a given campaign.
- query = ('SELECT Id, AdGroupAdDisapprovalReasons '
- 'WHERE CampaignId = %s AND '
- 'AdGroupCreativeApprovalStatus = DISAPPROVED '
- 'ORDER BY Id' % campaign_id)
- ads = ad_group_ad_service.query(query)
-
- # Display results.
- if 'entries' in ads:
- for ad in ads['entries']:
- print ('Ad with id \'%s\' was disapproved for the following reasons: '
- % (ad['ad']['id']))
- if ad['ad'].get('disapprovalReasons'):
- for reason in ad['ad']['disapprovalReasons']:
- print '\t%s' % reason
- else:
- print '\tReason not provided.'
- else:
- print 'No disapproved ads were found.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201406/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201406/campaign_management/get_campaigns_by_label.py
deleted file mode 100755
index 53938687..00000000
--- a/examples/adwords/v201406/campaign_management/get_campaigns_by_label.py
+++ /dev/null
@@ -1,88 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all campaigns with a specific label.
-
-To add a label to campaigns, run add_campaign_labels.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignService.get
-"""
-
-__author__ = 'Mark Saniscalchi'
-
-import time
-
-from googleads import adwords
-
-
-LABEL_ID = 'INSERT_LABEL_ID_HERE'
-PAGE_SIZE = 100
-
-
-def main(client, label_id):
- # Initialize appropriate service.
- campaign_service = client.GetService('CampaignService', version='v201406')
-
- offset = 0
- selector = {
- 'fields': ['Id', 'Name', 'Labels'],
- # Labels filtering is performed by ID. You can use CONTAINS_ANY to select
- # campaigns with any of the label IDs, CONTAINS_ALL to select campaigns
- # with all of the label IDs, or CONTAINS_NONE to select campaigns with
- # none of the label IDs.
- 'ordering': {
- 'field': 'Name',
- 'sortOrder': 'ASCENDING'
- },
- 'paging': {
- 'startIndex': str(offset),
- 'numberResults': str(PAGE_SIZE)
- },
- 'predicates': {
- 'field': 'Labels',
- 'operator': 'CONTAINS_ANY',
- 'values': [label_id]
- }
- }
-
- more_pages = True
- while more_pages:
- page = campaign_service.get(selector)
-
- # Display results.
- if 'entries' in page:
- for campaign in page['entries']:
- print ('Campaign found with Id \'%s\', name \'%s\', and labels: %s'
- % (campaign['id'], campaign['name'], campaign['labels']))
- else:
- print 'No campaigns were found.'
-
- offset += PAGE_SIZE
- selector['paging']['startIndex'] = str(offset)
- more_pages = offset < int(page['totalNumEntries'])
- time.sleep(1)
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, LABEL_ID)
diff --git a/examples/adwords/v201406/campaign_management/promote_experiment.py b/examples/adwords/v201406/campaign_management/promote_experiment.py
deleted file mode 100755
index d74e24c0..00000000
--- a/examples/adwords/v201406/campaign_management/promote_experiment.py
+++ /dev/null
@@ -1,65 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example promotes an experiment.
-
-Promoting an experiment permanently applies all the experimental changes made to
-its related ad groups, criteria and ads. To add an experiment, run
-add_experiment.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ExperimentService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-EXPERIMENT_ID = 'INSERT_EXPERIMENT_ID_HERE'
-
-
-def main(client, experiment_id):
- # Initialize appropriate service.
- experiment_service = client.GetService('ExperimentService', version='v201406')
-
- # Construct operations and promote experiment.
- operations = [{
- 'operator': 'SET',
- 'operand': {
- 'id': experiment_id,
- 'status': 'PROMOTED'
- }
- }]
- result = experiment_service.mutate(operations)
-
- # Display results.
- for experiment in result['value']:
- print ('Experiment with name \'%s\' and id \'%s\' was promoted.'
- % (experiment['name'], experiment['id']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, EXPERIMENT_ID)
diff --git a/examples/adwords/v201406/campaign_management/set_ad_parameters.py b/examples/adwords/v201406/campaign_management/set_ad_parameters.py
deleted file mode 100755
index 01ca3178..00000000
--- a/examples/adwords/v201406/campaign_management/set_ad_parameters.py
+++ /dev/null
@@ -1,105 +0,0 @@
-#!/usr/bin/python
-# -*- coding: utf-8 -*-
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds a text ad with ad parameters.
-
-To get ad groups, run get_ad_groups.py. To get keywords, run add_keywords.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupAdService.mutate, AdParamService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE'
-
-
-def main(client, ad_group_id, criterion_id):
- # Initialize appropriate service.
- ad_group_ad_service = client.GetService('AdGroupAdService', version='v201406')
- ad_param_service = client.GetService('AdParamService', version='v201406')
-
- # Construct operations for adding text ad object and add to an ad group.
- operations = [{
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'AdGroupAd',
- 'adGroupId': ad_group_id,
- 'ad': {
- 'xsi_type': 'TextAd',
- 'url': 'http://www.example.com',
- 'displayUrl': 'example.com',
- 'description1': 'Low-gravity fun for {param1:cheap}.',
- 'description2': 'Only {param2:a few} seats left!',
- 'headline': 'Luxury Mars Cruises'
- },
- 'status': 'ENABLED'
- }
- }]
- ads = ad_group_ad_service.mutate(operations)['value']
-
- # Display results.
- for ad in ads:
- print ('Text ad with id \'%s\' was successfully added to an ad group with '
- 'id \'%s\'.' % (ad['adGroupId'], ad['ad']['id']))
-
- # Construct operations for setting ad parameters.
- operations = [
- {
- 'operator': 'SET',
- 'operand': {
- 'adGroupId': ad_group_id,
- 'criterionId': criterion_id,
- 'insertionText': u'£100',
- 'paramIndex': '1'
- }
- },
- {
- 'operator': 'SET',
- 'operand': {
- 'adGroupId': ad_group_id,
- 'criterionId': criterion_id,
- 'insertionText': '50',
- 'paramIndex': '2'
- }
- }
- ]
- ad_params = ad_param_service.mutate(operations)
-
- # Display results.
- for ad_param in ad_params:
- print ('Ad parameter with text \'%s\' was successfully set for criterion '
- 'with id \'%s\' and ad group id \'%s\'.'
- % (ad_param['insertionText'], ad_param['criterionId'],
- ad_param['adGroupId']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID, CRITERION_ID)
diff --git a/examples/adwords/v201406/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201406/campaign_management/set_criterion_bid_modifier.py
deleted file mode 100755
index 29c790d6..00000000
--- a/examples/adwords/v201406/campaign_management/set_criterion_bid_modifier.py
+++ /dev/null
@@ -1,82 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example sets a bid modifier for the mobile platform on given campaign.
-
-To get campaigns, run get_campaigns.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignCriterionService.mutate
-"""
-
-__author__ = ('api.dklimkin@gmail.com (Danial Klimkin)',
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-BID_MODIFIER = '1.5'
-
-
-def main(client, campaign_id, bid_modifier):
- # Initialize appropriate service.
- campaign_criterion_service = client.GetService(
- 'CampaignCriterionService', version='v201406')
-
- # Create mobile platform.The ID can be found in the documentation.
- # https://developers.google.com/adwords/api/docs/appendix/platforms
- mobile = {
- 'xsi_type': 'Platform',
- 'id': '30001'
- }
-
- # Create campaign criterion with modified bid.
- campaign_criterion = {
- 'campaignId': campaign_id,
- 'criterion': mobile,
- 'bidModifier': bid_modifier
- }
-
- # Create operations.
- operations = [
- {
- 'operator': 'SET',
- 'operand': campaign_criterion
- }
- ]
-
- # Make the mutate request.
- result = campaign_criterion_service.mutate(operations)
-
- # Display the resulting campaign criteria.
- for campaign_criterion in result['value']:
- print ('Campaign criterion with campaign id \'%s\' and criterion id \'%s\' '
- 'was updated with bid modifier \'%s\'.'
- % (campaign_criterion['campaignId'],
- campaign_criterion['criterion']['id'],
- campaign_criterion['bidModifier']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID, BID_MODIFIER)
diff --git a/examples/adwords/v201406/campaign_management/validate_text_ad.py b/examples/adwords/v201406/campaign_management/validate_text_ad.py
deleted file mode 100755
index cadcd25c..00000000
--- a/examples/adwords/v201406/campaign_management/validate_text_ad.py
+++ /dev/null
@@ -1,89 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example shows how to use validateOnly SOAP header.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-import suds
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Initialize appropriate service with validate only flag enabled.
- client.validate_only = True
- ad_group_ad_service = client.GetService('AdGroupAdService', version='v201406')
-
- # Construct operations to add a text ad.
- operations = [{
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'AdGroupAd',
- 'adGroupId': ad_group_id,
- 'ad': {
- 'xsi_type': 'TextAd',
- 'url': 'http://www.example.com',
- 'displayUrl': 'example.com',
- 'description1': 'Visit the Red Planet in style.',
- 'description2': 'Low-gravity fun for everyone!',
- 'headline': 'Luxury Cruise to Mars'
- }
- }
- }]
- ad_group_ad_service.mutate(operations)
- # No error means the request is valid.
-
- # Now let's check an invalid ad using a very long line to trigger an error.
- operations = [{
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'AdGroupAd',
- 'adGroupId': ad_group_id,
- 'ad': {
- 'xsi_type': 'TextAd',
- 'url': 'http://www.example.com',
- 'displayUrl': 'example.com',
- 'description1': 'Visit the Red Planet in style.',
- 'description2': 'Low-gravity fun for all astronauts in orbit',
- 'headline': 'Luxury Cruise to Mars'
- }
- }
- }]
- try:
- ad_group_ad_service.mutate(operations)
- except suds.WebFault, e:
- print 'Validation correctly failed with \'%s\'.' % str(e)
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201406/error_handling/__init__.py b/examples/adwords/v201406/error_handling/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/examples/adwords/v201406/error_handling/handle_partial_failures.py b/examples/adwords/v201406/error_handling/handle_partial_failures.py
deleted file mode 100755
index c801d34e..00000000
--- a/examples/adwords/v201406/error_handling/handle_partial_failures.py
+++ /dev/null
@@ -1,124 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example demonstrates how to handle partial failures.
-
-To get ad groups, run get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupCriterionService.mutate
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-import re
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Enable partial failure.
- client.partial_failure = True
-
- # Initialize appropriate service.
- ad_group_criterion_service = client.GetService(
- 'AdGroupCriterionService', version='v201406')
-
- # Construct keyword ad group criteria objects.
- keywords = [
- {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Keyword',
- 'matchType': 'BROAD',
- 'text': 'mars cruise'
- }
- },
- {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Keyword',
- 'matchType': 'BROAD',
- 'text': r'inv\@lid cruise'
- }
- },
- {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Keyword',
- 'matchType': 'BROAD',
- 'text': 'venus cruise'
- }
- },
- {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Keyword',
- 'matchType': 'BROAD',
- 'text': r'b\(a\)d keyword cruise'
- }
- }
- ]
-
- # Construct operations and add ad group criteria.
- operations = []
- for keyword in keywords:
- operations.append(
- {
- 'operator': 'ADD',
- 'operand': keyword
- })
- result = ad_group_criterion_service.mutate(operations)
-
- # Display results.
- for criterion in result['value']:
- if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion':
- print ('Added keyword ad group criterion with ad group id \'%s\', '
- 'criterion id \'%s\', text \'%s\', and match type \'%s\' was '
- 'added.'
- % (criterion['adGroupId'], criterion['criterion']['id'],
- criterion['criterion']['text'],
- criterion['criterion']['matchType']))
-
- for error in result['partialFailureErrors']:
- index = re.findall(r'operations\[(.*)\]\.', error['fieldPath'])
- if index:
- print ('Keyword ad group criterion with ad group id \'%s\' and text '
- '\'%s\' triggered a failure for the following reason: \'%s\'.'
- % (keywords[int(index[0])]['adGroupId'],
- keywords[int(index[0])]['criterion']['text'],
- error['errorString']))
- else:
- print 'The following failure has occurred: \'%s\'.' % error['errorString']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201406/error_handling/handle_policy_violation_error.py b/examples/adwords/v201406/error_handling/handle_policy_violation_error.py
deleted file mode 100755
index 8fe69907..00000000
--- a/examples/adwords/v201406/error_handling/handle_policy_violation_error.py
+++ /dev/null
@@ -1,117 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example demonstrates how to handle policy violation errors.
-
-To get ad groups, run get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupAdService.mutate
-"""
-
-__author__ = 'Joseph DiLallo'
-
-import re
-
-import suds
-
-from googleads import adwords
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- ad_group_ad_service = client.GetService('AdGroupAdService', 'v201406')
-
- # Create text ad.
- text_ad_operation = {
- 'operator': 'ADD',
- 'operand': {
- 'adGroupId': ad_group_id,
- 'ad': {
- # The 'xsi_type' field allows you to specify the xsi:type of the
- # object being created. It's only necessary when you must provide
- # an explicit type that the client library can't infer.
- 'xsi_type': 'TextAd',
- 'headline': 'Mars Cruise!!!',
- 'description1': 'Visit the Red Planet in style.',
- 'description2': 'Low-gravity fun for everyone!',
- 'url': 'http://www.example.com',
- 'displayUrl': 'www.example.com',
- }
- }
- }
-
- operations = [text_ad_operation]
-
- # Validate the ad.
- try:
- # Enable "validate only" to check for errors.
- client.validate_only = True
- ad_group_ad_service.mutate(operations)
- print 'Validation successful, no errors returned.'
- except suds.WebFault, e:
- for error in e.fault.detail.ApiExceptionFault.errors:
- if error['ApiError.Type'] == 'PolicyViolationError':
- operation_index = re.findall(r'operations\[(.*)\]\.',
- error['fieldPath'])
- if operation_index:
- operation = operations[int(operation_index[0])]
- print ('Ad with headline \'%s\' violated %s policy \'%s\'.' %
- (operation['operand']['ad']['headline'],
- 'exemptable' if error['isExemptable'] else 'non-exemptable',
- error['externalPolicyName']))
- if error['isExemptable'].lower() == 'true':
- # Add exemption request to the operation.
- print ('Adding exemption request for policy name \'%s\' on text '
- '\'%s\'.' %
- (error['key']['policyName'], error['key']['violatingText']))
- if 'exemptionRequests' not in operation:
- operation['exemptionRequests'] = []
- operation['exemptionRequests'].append({
- 'key': error['key']
- })
- else:
- # Remove non-exemptable operation
- print 'Removing the operation from the request.'
- operations.delete(operation)
- else:
- # Non-policy error returned, re-throw exception.
- raise e
-
- # Add these ads. Disable "validate only" so the ads will get created.
- client.validate_only = False
- if operations:
- response = ad_group_ad_service.mutate(operations)
- if response and response['value']:
- ads = response['value']
- print 'Added %s ad(s) to ad group %s.' % (len(ads), ad_group_id)
- for ad in ads:
- print (' Ad id is %s, type is %s and status is \'%s\'.' %
- (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status']))
- else:
- print 'No ads were added.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201406/misc/__init__.py b/examples/adwords/v201406/misc/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/examples/adwords/v201406/misc/get_all_images_and_videos.py b/examples/adwords/v201406/misc/get_all_images_and_videos.py
deleted file mode 100755
index 831e76b6..00000000
--- a/examples/adwords/v201406/misc/get_all_images_and_videos.py
+++ /dev/null
@@ -1,80 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all images and videos.
-
-To upload an image, run upload_image.py. To upload video, see:
-http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=39454.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: MediaService.get
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-PAGE_SIZE = 500
-
-
-def main(client):
- # Initialize appropriate service.
- media_service = client.GetService('MediaService', version='v201406')
-
- # Construct selector and get all images.
- offset = 0
- selector = {
- 'fields': ['MediaId', 'Type', 'Width', 'Height', 'MimeType'],
- 'predicates': [{
- 'field': 'Type',
- 'operator': 'IN',
- 'values': ['IMAGE', 'VIDEO']
- }],
- 'paging': {
- 'startIndex': str(offset),
- 'numberResults': str(PAGE_SIZE)
- }
- }
- more_pages = True
- while more_pages:
- page = media_service.get(selector)
-
- # Display results.
- if 'entries' in page:
- for image in page['entries']:
- dimensions = dict([(entry['key'], entry['value'])
- for entry in image['dimensions']])
- print ('Media with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\''
- ' was found.' % (image['mediaId'], dimensions['FULL']['height'],
- dimensions['FULL']['width'], image['mimeType']))
- else:
- print 'No images/videos were found.'
- offset += PAGE_SIZE
- selector['paging']['startIndex'] = str(offset)
- more_pages = offset < int(page['totalNumEntries'])
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201406/misc/upload_image.py b/examples/adwords/v201406/misc/upload_image.py
deleted file mode 100755
index 53d9810b..00000000
--- a/examples/adwords/v201406/misc/upload_image.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example uploads an image.
-
-To get images, run get_all_images.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: MediaService.upload
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-import base64
-
-from googleads import adwords
-
-
-IMAGE_FILENAME = 'INSERT_IMAGE_PATH_HERE'
-
-
-def main(client, image_filename):
- # Initialize appropriate service.
- media_service = client.GetService('MediaService', version='v201406')
-
- with open(image_filename, 'r') as image_handle:
- image_data = base64.encodestring(image_handle.read())
-
- # Construct media and upload image.
- media = [{
- 'xsi_type': 'Image',
- 'data': image_data,
- 'type': 'IMAGE'
- }]
- media = media_service.upload(media)[0]
-
- # Display results.
- if media:
- dimensions = dict([(entry['key'], entry['value'])
- for entry in media['dimensions']])
- print ('Image with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\' was'
- ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'],
- dimensions['FULL']['width'], media['mimeType']))
- else:
- print 'No images were uploaded.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, IMAGE_FILENAME)
diff --git a/examples/adwords/v201406/optimization/__init__.py b/examples/adwords/v201406/optimization/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/examples/adwords/v201406/optimization/estimate_keyword_traffic.py b/examples/adwords/v201406/optimization/estimate_keyword_traffic.py
deleted file mode 100755
index 49540b23..00000000
--- a/examples/adwords/v201406/optimization/estimate_keyword_traffic.py
+++ /dev/null
@@ -1,122 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example retrieves keyword traffic estimates.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: TrafficEstimatorService.get
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-def main(client):
- # Initialize appropriate service.
- traffic_estimator_service = client.GetService(
- 'TrafficEstimatorService', version='v201406')
-
- # Construct selector object and retrieve traffic estimates.
- keywords = [
- {'text': 'mars cruise', 'matchType': 'BROAD'},
- {'text': 'cheap cruise', 'matchType': 'PHRASE'},
- {'text': 'cruise', 'matchType': 'EXACT'}
- ]
- negative_keywords = [
- {'text': 'moon walk', 'matchType': 'BROAD'}
- ]
- keyword_estimate_requests = []
- for keyword in keywords:
- keyword_estimate_requests.append({
- 'keyword': {
- 'xsi_type': 'Keyword',
- 'matchType': keyword['matchType'],
- 'text': keyword['text']
- }
- })
-
- for keyword in negative_keywords:
- keyword_estimate_requests.append({
- 'keyword': {
- 'xsi_type': 'Keyword',
- 'matchType': keyword['matchType'],
- 'text': keyword['text']
- },
- 'isNegative': 'true'
- })
-
- selector = {
- 'campaignEstimateRequests': [{
- 'adGroupEstimateRequests': [{
- 'keywordEstimateRequests': keyword_estimate_requests,
- 'maxCpc': {
- 'xsi_type': 'Money',
- 'microAmount': '1000000'
- }
- }],
- 'criteria': [
- {
- 'xsi_type': 'Location',
- 'id': '2840' # United States.
- },
- {
- 'xsi_type': 'Language',
- 'id': '1000' # English.
- }
- ]
- }]
- }
- estimates = traffic_estimator_service.get(selector)
-
- # Display results.
- ad_group_estimate = estimates['campaignEstimates'][0]['adGroupEstimates'][0]
- keyword_estimates = ad_group_estimate['keywordEstimates']
- for index in xrange(len(keyword_estimates)):
- keyword = keyword_estimate_requests[index]['keyword']
- estimate = keyword_estimates[index]
- if keyword_estimate_requests[index].get('isNegative', False):
- continue
-
- # Find the mean of the min and max values.
- mean_avg_cpc = (long(estimate['min']['averageCpc']['microAmount']) +
- long(estimate['max']['averageCpc']['microAmount'])) / 2
- mean_avg_pos = (float(estimate['min']['averagePosition']) +
- float(estimate['max']['averagePosition'])) / 2
- mean_clicks = (float(estimate['min']['clicksPerDay']) +
- float(estimate['max']['clicksPerDay'])) / 2
- mean_total_cost = (long(estimate['min']['totalCost']['microAmount']) +
- long(estimate['max']['totalCost']['microAmount'])) / 2
-
- print ('Results for the keyword with text \'%s\' and match type \'%s\':'
- % (keyword['text'], keyword['matchType']))
- print ' Estimated average CPC: %s' % mean_avg_cpc
- print ' Estimated ad position: %s' % mean_avg_pos
- print ' Estimated daily clicks: %s' % mean_clicks
- print ' Estimated daily cost: %s' % mean_total_cost
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201406/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201406/optimization/get_keyword_bid_simulations.py
deleted file mode 100755
index 9842789e..00000000
--- a/examples/adwords/v201406/optimization/get_keyword_bid_simulations.py
+++ /dev/null
@@ -1,88 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets a bid landscape for an ad group and a criterion.
-
-To get ad groups, run get_ad_groups.py. To get criteria, run get_keywords.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: BidLandscapeService.getBidLandscape
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-CRITERION_ID = 'INSERT_CRITERION_ID_HERE'
-
-
-def main(client, ad_group_id, criterion_id):
- # Initialize appropriate service.
- data_service = client.GetService('DataService', version='v201406')
-
- # Construct bid landscape selector object and retrieve bid landscape.
- selector = {
- 'fields': ['AdGroupId', 'CriterionId', 'StartDate', 'EndDate', 'Bid',
- 'LocalClicks', 'LocalCost', 'MarginalCpc', 'LocalImpressions'],
- 'predicates': [
- {
- 'field': 'AdGroupId',
- 'operator': 'EQUALS',
- 'values': [ad_group_id]
- },
- {
- 'field': 'CriterionId',
- 'operator': 'EQUALS',
- 'values': [criterion_id]
- }
- ]
- }
- bid_landscapes = data_service.getCriterionBidLandscape(selector)
-
- # Display results.
- if 'entries' in bid_landscapes:
- for bid_landscape in bid_landscapes['entries']:
- if bid_landscape['BidLandscape.Type'] == 'CriterionBidLandscape':
- print ('Criterion bid landscape with ad group id \'%s\', criterion id '
- '\'%s\', start date \'%s\', end date \'%s\', with landscape '
- 'points was found:'
- % (bid_landscape['adGroupId'], bid_landscape['criterionId'],
- bid_landscape['startDate'], bid_landscape['endDate']))
- for bid_landscape_point in bid_landscape['landscapePoints']:
- print (' bid: %s => clicks: %s, cost: %s, marginalCpc: %s, '
- 'impressions: %s'
- % (bid_landscape_point['bid']['microAmount'],
- bid_landscape_point['clicks'],
- bid_landscape_point['cost']['microAmount'],
- bid_landscape_point['marginalCpc']['microAmount'],
- bid_landscape_point['impressions']))
- else:
- print 'No bid landscapes found.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID, CRITERION_ID)
diff --git a/examples/adwords/v201406/optimization/get_keyword_ideas.py b/examples/adwords/v201406/optimization/get_keyword_ideas.py
deleted file mode 100755
index a21567b2..00000000
--- a/examples/adwords/v201406/optimization/get_keyword_ideas.py
+++ /dev/null
@@ -1,94 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example retrieves keywords that are related to a given keyword.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: TargetingIdeaService.get
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-PAGE_SIZE = 100
-
-
-def main(client):
- # Initialize appropriate service.
- targeting_idea_service = client.GetService(
- 'TargetingIdeaService', version='v201406')
-
- # Construct selector object and retrieve related keywords.
- offset = 0
- selector = {
- 'searchParameters': [
- {
- 'xsi_type': 'RelatedToQuerySearchParameter',
- 'queries': ['space cruise']
- },
- {
- # Language setting (optional).
- # The ID can be found in the documentation:
- # https://developers.google.com/adwords/api/docs/appendix/languagecodes
- 'xsi_type': 'LanguageSearchParameter',
- 'languages': [{'id': '1000'}]
- }
- ],
- 'ideaType': 'KEYWORD',
- 'requestType': 'IDEAS',
- 'requestedAttributeTypes': ['KEYWORD_TEXT', 'SEARCH_VOLUME',
- 'CATEGORY_PRODUCTS_AND_SERVICES'],
- 'paging': {
- 'startIndex': str(offset),
- 'numberResults': str(PAGE_SIZE)
- }
- }
- more_pages = True
- while more_pages:
- page = targeting_idea_service.get(selector)
-
- # Display results.
- if 'entries' in page:
- for result in page['entries']:
- attributes = {}
- for attribute in result['data']:
- attributes[attribute['key']] = attribute['value']
- print ('Keyword with \'%s\' text and average monthly search volume '
- '\'%s\' was found with Products and Services categories: %s.'
- % (attributes['KEYWORD_TEXT'],
- attributes['SEARCH_VOLUME'],
- attributes['CATEGORY_PRODUCTS_AND_SERVICES']))
- print
- else:
- print 'No related keywords were found.'
- offset += PAGE_SIZE
- selector['paging']['startIndex'] = str(offset)
- more_pages = offset < int(page['totalNumEntries'])
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201406/optimization/get_placement_ideas.py b/examples/adwords/v201406/optimization/get_placement_ideas.py
deleted file mode 100755
index 9ee071ac..00000000
--- a/examples/adwords/v201406/optimization/get_placement_ideas.py
+++ /dev/null
@@ -1,81 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Retrieves urls that have content keywords related to a given website.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: TargetingIdeaService.get
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-PAGE_SIZE = 100
-
-
-def main(client):
- # Initialize appropriate service.
- targeting_idea_service = client.GetService(
- 'TargetingIdeaService', version='v201406')
-
- # Construct selector object and retrieve related placements.
- offset = 0
- url = 'http://mars.google.com'
- selector = {
- 'searchParameters': [{
- 'xsi_type': 'RelatedToUrlSearchParameter',
- 'urls': [url],
- 'includeSubUrls': 'false'
- }],
- 'ideaType': 'PLACEMENT',
- 'requestType': 'IDEAS',
- 'requestedAttributeTypes': ['SAMPLE_URL'],
- 'paging': {
- 'startIndex': str(offset),
- 'numberResults': str(PAGE_SIZE)
- }
- }
- more_pages = True
- while more_pages:
- page = targeting_idea_service.get(selector)
-
- # Display results.
- if 'entries' in page:
- for result in page['entries']:
- result = result['data'][0]['value']
- print 'Related content keywords were found at \'%s\' url.' % result
- print
- print ('Total urls found with content keywords related to keywords at '
- '\'%s\': %s' % (url, page['totalNumEntries']))
- else:
- print 'No content keywords were found at \'%s\'.' % url
- offset += PAGE_SIZE
- selector['paging']['startIndex'] = str(offset)
- more_pages = offset < int(page['totalNumEntries'])
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201406/remarketing/__init__.py b/examples/adwords/v201406/remarketing/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/examples/adwords/v201406/remarketing/add_audience.py b/examples/adwords/v201406/remarketing/add_audience.py
deleted file mode 100755
index cb947c1b..00000000
--- a/examples/adwords/v201406/remarketing/add_audience.py
+++ /dev/null
@@ -1,107 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds a remarketing user list (a.k.a. audience).
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: UserListService.mutate
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-import uuid
-
-from googleads import adwords
-
-
-def main(client):
- # Initialize appropriate service.
- user_list_service = client.GetService(
- 'AdwordsUserListService', version='v201406')
- conversion_tracker_service = client.GetService(
- 'ConversionTrackerService', version='v201406')
-
- # Construct operations and add a user list.
- operations = [
- {
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'BasicUserList',
- 'name': 'Mars cruise customers #%s' % uuid.uuid4(),
- 'description': 'A list of mars cruise customers in the last year',
- 'membershipLifeSpan': '365',
- 'conversionTypes': [
- {
- 'name': ('Mars cruise customers #%s'
- % uuid.uuid4())
- }
- ],
- # Optional field.
- 'status': 'OPEN',
- }
- }
- ]
- result = user_list_service.mutate(operations)
-
- # Display results.
- if 'value' in result:
- conversion_ids = []
- for user_list in result['value']:
- if user_list['conversionTypes']:
- for conversion_type in user_list['conversionTypes']:
- conversion_ids.append(conversion_type['id'])
-
- selector = {
- 'fields': ['Name', 'Status', 'Category'],
- 'predicates': [{
- 'field': 'Id',
- 'operator': 'IN',
- 'values': conversion_ids
- }],
- 'ordering': [{
- 'field': 'Name',
- 'sortOrder': 'ASCENDING'
- }]
- }
-
- pages = conversion_tracker_service.get(selector)
- conversions_map = {}
- if pages['entries']:
- for conversion_tracker in pages['entries']:
- conversions_map[conversion_tracker['id']] = conversion_tracker
-
- for user_list in result['value']:
- print ('User list with name \'%s\' and ID \'%s\' was added.'
- % (user_list['name'], user_list['id']))
- if user_list['conversionTypes']:
- for conversion_type in user_list['conversionTypes']:
- conversion_tracker = conversions_map[conversion_type['id']]
- print ('Conversion type code snippet associated to the list:\n%s\n'
- % conversion_tracker['snippet'])
- else:
- print 'No user lists were added.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201406/remarketing/add_conversion_tracker.py b/examples/adwords/v201406/remarketing/add_conversion_tracker.py
deleted file mode 100755
index 1c1f5269..00000000
--- a/examples/adwords/v201406/remarketing/add_conversion_tracker.py
+++ /dev/null
@@ -1,77 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the 'License');
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an 'AS IS' BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds an AdWords conversion.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ConversionTrackerService.mutate
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-import uuid
-
-from googleads import adwords
-
-
-def main(client):
- # Initialize appropriate service.
- conversion_tracker_service = client.GetService(
- 'ConversionTrackerService', version='v201406')
-
- # Construct operations and add conversion_tracker.
- operations = [
- {
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'AdWordsConversionTracker',
- 'name': 'Mars cruise customers #%s' % uuid.uuid4(),
- 'category': 'DEFAULT',
- 'markupLanguage': 'HTML',
- 'textFormat': 'HIDDEN',
- # Optional fields.
- 'status': 'ENABLED',
- 'viewthroughLookbackWindow': '15',
- 'isProductAdsChargeable': 'true',
- 'productAdsChargeableConversionWindow': '15',
- 'conversionPageLanguage': 'en',
- 'backgroundColor': '#0000FF',
- 'defaultRevenueValue': '23.41',
- 'alwaysUseDefaultRevenueValue': 'true'
- }
- }
- ]
- conversion_trackers = conversion_tracker_service.mutate(operations)
-
- # Display results.
- for conversion_tracker in conversion_trackers['value']:
- print ('Conversion tracker with id \'%s\', name \'%s\', status \'%s\' '
- 'and category \'%s\' and snippet \n\'%s\'\n was added.\n' %
- (conversion_tracker['id'], conversion_tracker['name'],
- conversion_tracker['status'], conversion_tracker['category'],
- conversion_tracker['snippet']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201406/reporting/__init__.py b/examples/adwords/v201406/reporting/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/examples/adwords/v201406/reporting/download_criteria_report.py b/examples/adwords/v201406/reporting/download_criteria_report.py
deleted file mode 100755
index 6bb30cc6..00000000
--- a/examples/adwords/v201406/reporting/download_criteria_report.py
+++ /dev/null
@@ -1,65 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example downloads a criteria performance report.
-
-To get report fields, run get_report_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ReportDefinitionService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = 'Joseph DiLallo'
-
-import logging
-import sys
-
-from googleads import adwords
-
-logging.basicConfig(level=logging.INFO)
-logging.getLogger('suds.transport').setLevel(logging.DEBUG)
-
-
-def main(client):
- report_downloader = client.GetReportDownloader(version='v201406')
-
- # Create report definition.
- report = {
- 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT',
- 'dateRangeType': 'LAST_7_DAYS',
- 'reportType': 'CRITERIA_PERFORMANCE_REPORT',
- 'downloadFormat': 'CSV',
- 'selector': {
- 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType',
- 'Criteria', 'Impressions', 'Clicks', 'Cost']
- },
- # Enable to get rows with zero impressions.
- 'includeZeroImpressions': 'false'
- }
-
- # You can provide a file object to write the output to. For this demonstration
- # we use sys.stdout to write the report to the screen.
- report_downloader.DownloadReport(report, sys.stdout)
-
-
-if __name__ == '__main__':
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
- main(adwords_client)
diff --git a/examples/adwords/v201406/reporting/download_criteria_report_as_stream.py b/examples/adwords/v201406/reporting/download_criteria_report_as_stream.py
deleted file mode 100755
index 8105415d..00000000
--- a/examples/adwords/v201406/reporting/download_criteria_report_as_stream.py
+++ /dev/null
@@ -1,77 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example retrieves the report download stream.
-
-To get report fields, run get_report_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ReportDefinitionService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = 'Mark Saniscalchi'
-
-import logging
-import sys
-
-from googleads import adwords
-import StringIO
-
-logging.basicConfig(level=logging.INFO)
-logging.getLogger('suds.transport').setLevel(logging.DEBUG)
-
-
-def main(client):
- report_downloader = client.GetReportDownloader(version='v201406')
-
- # Create report definition.
- report = {
- 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT',
- 'dateRangeType': 'LAST_7_DAYS',
- 'reportType': 'CRITERIA_PERFORMANCE_REPORT',
- 'downloadFormat': 'CSV',
- 'selector': {
- 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType',
- 'Criteria', 'Impressions', 'Clicks', 'Cost']
- },
- # Enable to get rows with zero impressions.
- 'includeZeroImpressions': 'false'
- }
-
- # Retrieve the report stream and print it out
- report_data = StringIO.StringIO()
- stream_data = report_downloader.DownloadReportAsStream(report)
-
- try:
- while True:
- chunk = stream_data.read(adwords.CHUNK_SIZE)
- if not chunk: break
- report_data.write(chunk.decode() if sys.version_info[0] == 3
- and getattr(report_data, 'mode', 'w') == 'w' else chunk)
- print report_data.getvalue()
- finally:
- report_data.close()
- stream_data.close()
-
-
-if __name__ == '__main__':
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
- main(adwords_client)
diff --git a/examples/adwords/v201406/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201406/reporting/download_criteria_report_as_stream_with_awql.py
deleted file mode 100755
index ee9a33fe..00000000
--- a/examples/adwords/v201406/reporting/download_criteria_report_as_stream_with_awql.py
+++ /dev/null
@@ -1,80 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example downloads a criteria performance report as a string with AWQL.
-
-To get report fields, run get_report_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ReportDefinitionService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-import logging
-import sys
-
-from googleads import adwords
-import StringIO
-
-logging.basicConfig(level=logging.INFO)
-logging.getLogger('suds.transport').setLevel(logging.DEBUG)
-
-# Specify where to download the file here.
-PATH = '/tmp/report_download.csv'
-
-
-def main(client):
- # Initialize appropriate service.
- report_downloader = client.GetReportDownloader(version='v201406')
-
- # Create report query.
- report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, '
- 'Impressions, Clicks, Cost '
- 'FROM CRITERIA_PERFORMANCE_REPORT '
- 'WHERE Status IN [ENABLED, PAUSED] '
- 'DURING LAST_7_DAYS')
-
- print report_downloader.DownloadReportAsStringWithAwql(report_query, 'CSV')
-
- # Retrieve the report stream and print it out
- report_data = StringIO.StringIO()
- stream_data = report_downloader.DownloadReportAsStreamWithAwql(report_query,
- 'CSV')
-
- try:
- while True:
- chunk = stream_data.read(adwords.CHUNK_SIZE)
- if not chunk: break
- report_data.write(chunk.decode() if sys.version_info[0] == 3
- and getattr(report_data, 'mode', 'w') == 'w' else chunk)
- print report_data.getvalue()
- finally:
- report_data.close()
- stream_data.close()
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201406/reporting/download_criteria_report_as_string.py b/examples/adwords/v201406/reporting/download_criteria_report_as_string.py
deleted file mode 100755
index 0b494d15..00000000
--- a/examples/adwords/v201406/reporting/download_criteria_report_as_string.py
+++ /dev/null
@@ -1,64 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example downloads a criteria performance report as a string.
-
-To get report fields, run get_report_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ReportDefinitionService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = 'Mark Saniscalchi'
-
-import logging
-import sys
-
-from googleads import adwords
-
-logging.basicConfig(level=logging.INFO)
-logging.getLogger('suds.transport').setLevel(logging.DEBUG)
-
-
-def main(client):
- report_downloader = client.GetReportDownloader(version='v201406')
-
- # Create report definition.
- report = {
- 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT',
- 'dateRangeType': 'LAST_7_DAYS',
- 'reportType': 'CRITERIA_PERFORMANCE_REPORT',
- 'downloadFormat': 'CSV',
- 'selector': {
- 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType',
- 'Criteria', 'Impressions', 'Clicks', 'Cost']
- },
- # Enable to get rows with zero impressions.
- 'includeZeroImpressions': 'false'
- }
-
- # Print out the report as a string
- print report_downloader.DownloadReportAsString(report)
-
-
-if __name__ == '__main__':
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
- main(adwords_client)
diff --git a/examples/adwords/v201406/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201406/reporting/download_criteria_report_as_string_with_awql.py
deleted file mode 100755
index e02e8115..00000000
--- a/examples/adwords/v201406/reporting/download_criteria_report_as_string_with_awql.py
+++ /dev/null
@@ -1,58 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example downloads a criteria performance report as a string with AWQL.
-
-To get report fields, run get_report_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ReportDefinitionService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-# Specify where to download the file here.
-PATH = '/tmp/report_download.csv'
-
-
-def main(client):
- # Initialize appropriate service.
- report_downloader = client.GetReportDownloader(version='v201406')
-
- # Create report query.
- report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, '
- 'Impressions, Clicks, Cost '
- 'FROM CRITERIA_PERFORMANCE_REPORT '
- 'WHERE Status IN [ENABLED, PAUSED] '
- 'DURING LAST_7_DAYS')
-
- print report_downloader.DownloadReportAsStringWithAwql(report_query, 'CSV')
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201406/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201406/reporting/download_criteria_report_with_awql.py
deleted file mode 100755
index 7a8937df..00000000
--- a/examples/adwords/v201406/reporting/download_criteria_report_with_awql.py
+++ /dev/null
@@ -1,61 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example downloads a criteria performance report with AWQL.
-
-To get report fields, run get_report_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ReportDefinitionService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-# Specify where to download the file here.
-PATH = '/tmp/report_download.csv'
-
-
-def main(client, path):
- # Initialize appropriate service.
- report_downloader = client.GetReportDownloader(version='v201406')
-
- # Create report query.
- report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, '
- 'Impressions, Clicks, Cost '
- 'FROM CRITERIA_PERFORMANCE_REPORT '
- 'WHERE Status IN [ENABLED, PAUSED] '
- 'DURING LAST_7_DAYS')
-
- with open(path, 'w') as output_file:
- report_downloader.DownloadReportWithAwql(report_query, 'CSV', output_file)
-
- print 'Report was downloaded to \'%s\'.' % path
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, PATH)
diff --git a/examples/adwords/v201406/reporting/get_report_fields.py b/examples/adwords/v201406/reporting/get_report_fields.py
deleted file mode 100755
index 0595cafe..00000000
--- a/examples/adwords/v201406/reporting/get_report_fields.py
+++ /dev/null
@@ -1,56 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets report fields.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ReportDefinitionService.getReportFields
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-REPORT_TYPE = 'INSERT_REPORT_TYPE_HERE'
-
-
-def main(client, report_type):
- # Initialize appropriate service.
- report_definition_service = client.GetService(
- 'ReportDefinitionService', version='v201406')
-
- # Get report fields.
- fields = report_definition_service.getReportFields(report_type)
-
- # Display results.
- print 'Report type \'%s\' contains the following fields:' % report_type
- for field in fields:
- print ' - %s (%s)' % (field['fieldName'], field['fieldType'])
- if 'enumValues' in field:
- print ' := [%s]' % ', '.join(field['enumValues'])
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, REPORT_TYPE)
diff --git a/examples/adwords/v201406/shopping/add_product_partition_tree.py b/examples/adwords/v201406/shopping/add_product_partition_tree.py
deleted file mode 100755
index d885ae36..00000000
--- a/examples/adwords/v201406/shopping/add_product_partition_tree.py
+++ /dev/null
@@ -1,285 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates a ProductPartition tree.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupCriterionService.mutate
-"""
-
-__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import adwords
-
-ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-class ProductPartitionHelper(object):
- """A helper for creating ProductPartition trees."""
-
- # The next temporary criterion ID to be used.
- # When creating our tree we need to specify the parent-child relationships
- # between nodes. However, until a criterion has been created on the server we
- # do not have a criterion ID with which to refer to it.
- # Instead we can specify temporary IDs that are specific to a single mutate
- # request. Once the criteria have been created they are assigned an ID as
- # normal and the temporary ID will no longer refer to it.
- # A valid temporary ID is any negative integer.
- next_id = -1
-
- # The set of mutate operations needed to create the current tree.
- operations = []
-
- def __init__(self, adgroup_id):
- """Initializer.
-
- Args:
- adgroup_id: The ID of the AdGroup that we wish to attach the partition
- tree to.
- """
- self.adgroup_id = adgroup_id
-
- 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',
- 'partitionType': 'SUBDIVISION',
- 'id': str(self.next_id)
- }
-
- # The root has neither a parent nor a value.
- if parent is not None:
- division['parentCriterionId'] = parent['id']
- division['caseValue'] = value
-
- adgroup_criterion = {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': self.adgroup_id,
- 'criterion': division
- }
-
- self.CreateAddOperation(adgroup_criterion)
- self.next_id -= 1
-
- return division
-
- 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.
- """
- unit = {
- 'xsi_type': 'ProductPartition',
- 'partitionType': 'UNIT'
- }
-
- # The root node has neither a parent nor a value.
- if parent is not None:
- unit['parentCriterionId'] = parent['id']
- unit['caseValue'] = value
-
- if bid_amount is not None and bid_amount > 0:
- bidding_strategy_configuration = {
- 'bids': [{
- 'xsi_type': 'CpcBid',
- 'bid': {
- 'xsi_type': 'Money',
- 'microAmount': str(bid_amount)
- }
- }]
- }
-
- adgroup_criterion = {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'biddingStrategyConfiguration': bidding_strategy_configuration
- }
- else:
- adgroup_criterion = {
- 'xsi_type': 'NegativeAdGroupCriterion'
- }
-
- adgroup_criterion['adGroupId'] = self.adgroup_id
- adgroup_criterion['criterion'] = unit
-
- self.CreateAddOperation(adgroup_criterion)
-
- return unit
-
- def GetOperations(self):
- """Returns the set of mutate operations needed to create the current tree.
-
- Returns:
- The set of operations
- """
- return self.operations
-
- def CreateAddOperation(self, criterion):
- """Creates an AdGroupCriterionOperation for the given criterion.
-
- Args:
- criterion: The criterion we want to add.
- """
- operation = {
- 'operator': 'ADD',
- 'operand': criterion
- }
-
- self.operations.append(operation)
-
-
-def main(client, adgroup_id):
- """Runs the example."""
- adgroup_criterion_service = client.GetService(
- 'AdGroupCriterionService', version='v201406')
-
- helper = ProductPartitionHelper(adgroup_id)
-
- # The most trivial partition tree has only a unit node as the root, e.g.:
- # helper.CreateUnit(bid_amount=100000)
-
- root = helper.CreateSubdivision()
-
- new_product_canonical_condition = {
- 'xsi_type': 'ProductCanonicalCondition',
- 'condition': 'NEW'
- }
-
- used_product_canonical_condition = {
- 'xsi_type': 'ProductCanonicalCondition',
- 'condition': 'USED'
- }
-
- other_product_canonical_condition = {
- 'xsi_type': 'ProductCanonicalCondition',
- }
-
- helper.CreateUnit(root, new_product_canonical_condition, 200000)
- helper.CreateUnit(root, used_product_canonical_condition, 100000)
- other_condition = helper.CreateSubdivision(
- root, other_product_canonical_condition)
-
- cool_product_brand = {
- 'xsi_type': 'ProductBrand',
- 'value': 'CoolBrand'
- }
-
- cheap_product_brand = {
- 'xsi_type': 'ProductBrand',
- 'value': 'CheapBrand'
- }
-
- other_product_brand = {
- 'xsi_type': 'ProductBrand',
- }
-
- helper.CreateUnit(other_condition, cool_product_brand, 900000)
- helper.CreateUnit(other_condition, cheap_product_brand, 10000)
- other_brand = helper.CreateSubdivision(other_condition, other_product_brand)
-
- # The value for the bidding category is a fixed ID for the 'Luggage & Bags'
- # category. You can retrieve IDs for categories from the ConstantDataService.
- # See the 'GetProductTaxonomy' example for more details.
- luggage_category = {
- 'xsi_type': 'ProductBiddingCategory',
- 'type': 'BIDDING_CATEGORY_L1',
- 'value': '-5914235892932915235'
- }
-
- generic_category = {
- 'xsi_type': 'ProductBiddingCategory',
- 'type': 'BIDDING_CATEGORY_L1',
- }
-
- helper.CreateUnit(other_brand, luggage_category, 750000)
- helper.CreateUnit(other_brand, generic_category, 110000)
-
- # Make the mutate request
- result = adgroup_criterion_service.mutate(helper.GetOperations())
-
- children = {}
-
- root_node = None
-
- # For each criterion, make an array containing each of its children.
- # We always create the parent before the child, so we can rely on that here.
- for adgroup_criterion in result['value']:
- children[adgroup_criterion['criterion']['id']] = []
-
- if 'parentCriterionId' in adgroup_criterion['criterion']:
- children[adgroup_criterion['criterion']['parentCriterionId']].append(
- adgroup_criterion['criterion'])
- else:
- root_node = adgroup_criterion['criterion']
-
- # Show the tree
- DisplayTree(root_node, 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_value = node['caseValue']
- node_type = case_value['ProductDimension.Type']
-
- if node_type == 'ProductCanonicalCondition':
- value = (case_value['condition'] if 'condition' in case_value
- else 'OTHER')
- elif node_type == 'ProductBiddingCategory':
- value = '%s(%s)' % (case_value['type'], case_value['value']
- if 'value' in case_value else 'OTHER')
- else:
- value = (case_value['value'] if 'value' in case_value else 'OTHER')
-
- print ('%sid: %s, node_type: %s, value: %s\n'
- % (' ' * level, node['id'], node_type, value))
-
- for child_node in children[node['id']]:
- DisplayTree(child_node, children, level + 1)
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, ADGROUP_ID)
-
diff --git a/examples/adwords/v201406/shopping/add_product_scope.py b/examples/adwords/v201406/shopping/add_product_scope.py
deleted file mode 100755
index e9b3bb14..00000000
--- a/examples/adwords/v201406/shopping/add_product_scope.py
+++ /dev/null
@@ -1,107 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Restricts products that will be included in a campaign with a ProductScope.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignCriterionService.mutate
-"""
-
-__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import adwords
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-
-
-def main(client, campaign_id):
- campaign_criterion_service = client.GetService(
- 'CampaignCriterionService', version='v201406')
-
- product_scope = {
- 'xsi_type': 'ProductScope',
- # This set of dimensions is for demonstration purposes only. It would be
- # extremely unlikely that you want to include so many dimensions in your
- # product scope.
- 'dimensions': [
- {
- 'xsi_type': 'ProductBrand',
- 'value': 'Nexus'
- },
- {
- 'xsi_type': 'ProductCanonicalCondition',
- 'condition': 'NEW'
- },
- {
- 'xsi_type': 'ProductCustomAttribute',
- 'type': 'CUSTOM_ATTRIBUTE_0',
- 'value': 'my attribute value'
- },
- {
- 'xsi_type': 'ProductOfferId',
- 'value': 'book1'
- },
- {
- 'xsi_type': 'ProductType',
- 'type': 'PRODUCT_TYPE_L1',
- 'value': 'Media'
- },
- {
- 'xsi_type': 'ProductType',
- 'type': 'PRODUCT_TYPE_L2',
- 'value': 'Books'
- },
- # The value for the bidding category is a fixed ID for the "Luggage
- # & Bags" category. You can retrieve IDs for categories from the
- # ConstantDataService. See the "GetProductCategoryTaxonomy" example
- # for more details.
- {
- 'xsi_type': 'ProductBiddingCategory',
- 'type': 'BIDDING_CATEGORY_L1',
- 'value': '-5914235892932915235'
- }
- ]
- }
-
- campaign_criterion = {
- 'campaignId': campaign_id,
- 'criterion': product_scope
- }
-
- operations = [{
- 'operator': 'ADD',
- 'operand': campaign_criterion
- }]
-
- # Make the request
- result = campaign_criterion_service.mutate(operations)
-
- for criterion in result['value']:
- print ('Created a ProductScope criterion with Id: %s'
- % criterion['criterion']['id'])
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201406/shopping/add_shopping_campaign.py b/examples/adwords/v201406/shopping/add_shopping_campaign.py
deleted file mode 100755
index 44c6cc44..00000000
--- a/examples/adwords/v201406/shopping/add_shopping_campaign.py
+++ /dev/null
@@ -1,127 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds a Shopping campaign.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignService.mutate, AdGroupService.mutate, AdGroupAdService.mutate
-"""
-
-__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import adwords
-
-BUDGET_ID = 'INSERT_BUDGET_ID_HERE'
-MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE'
-
-
-def main(client, budget_id, merchant_id):
- campaign_service = client.GetService('CampaignService', version='v201406')
- ad_group_service = client.GetService('AdGroupService', version='v201406')
- ad_group_ad_service = client.GetService('AdGroupAdService', version='v201406')
-
- # Create campaign
- campaign = {
- 'name': 'Shopping campaign #%s' % uuid.uuid4(),
- # The advertisingChannelType is what makes this a shopping campaign
- 'advertisingChannelType': 'SHOPPING',
- # Set shared budget (required)
- 'budget': {
- 'budgetId': budget_id
- },
- 'biddingStrategyConfiguration': {
- 'biddingStrategyType': 'MANUAL_CPC'
- },
- 'settings': [
- # Set keyword matching setting (required)
- {
- 'xsi_type': 'KeywordMatchSetting',
- 'optIn': 'false'
- },
- # All shopping campaigns need a ShoppingSetting
- {
- 'xsi_type': 'ShoppingSetting',
- 'salesCountry': 'US',
- 'campaignPriority': '0',
- 'merchantId': merchant_id
- }
- ]
- }
-
- campaign_operations = [{
- 'operator': 'ADD',
- 'operand': campaign
- }]
-
- result = campaign_service.mutate(campaign_operations)
-
- for campaign in result['value']:
- print ('Campaign with name \'%s\' and ID \'%s\' was added.'
- % (campaign['name'], campaign['id']))
-
- # Create the AdGroup
- adgroup = {
- 'campaignId': campaign['id'],
- 'name': 'AdGroup #%s' % uuid.uuid4()
- }
-
- adgroup_operations = {
- 'operator': 'ADD',
- 'operand': adgroup
- }
-
- # Make the mutate request to add the AdGroup to the Shopping Campaign
- ad_group_result = ad_group_service.mutate(adgroup_operations)
-
- for adgroup in ad_group_result['value']:
- print ('AdGroup with name \'%s\' and ID \'%s\' was added.'
- % (adgroup['name'], adgroup['id']))
-
- # Create an AdGroup Ad
- adgroup_ad = {
- 'adGroupId': adgroup['id'],
- # Create ProductAd
- 'ad': {
- 'xsi_type': 'ProductAd',
- 'Ad.Type': 'ProductAd'
- }
- }
-
- ad_operation = {
- 'operator': 'ADD',
- 'operand': adgroup_ad
- }
-
- # Make the mutate request to add the ProductAd to the AdGroup
- ad_result = ad_group_ad_service.mutate([ad_operation])
-
- for adgroup_ad in ad_result['value']:
- print 'ProductAd with ID \'%s\' was added.' % adgroup_ad['ad']['id']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, BUDGET_ID, MERCHANT_ID)
diff --git a/examples/adwords/v201406/shopping/get_product_category_taxonomy.py b/examples/adwords/v201406/shopping/get_product_category_taxonomy.py
deleted file mode 100755
index 47e27963..00000000
--- a/examples/adwords/v201406/shopping/get_product_category_taxonomy.py
+++ /dev/null
@@ -1,99 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example fetches the set of valid ProductBiddingCategories.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ConstantDataService.getProductBiddingCategoryData
-"""
-
-__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import adwords
-
-
-def main(client):
- service = client.GetService('ConstantDataService', version='v201406')
-
- selector = {
- 'predicates': [
- {
- 'field': 'Country',
- 'operator': 'IN',
- 'values': ['US']
- }
- ]
- }
-
- result = service.getProductBiddingCategoryData(selector)
-
- bidding_categories = {}
- root_categories = []
-
- for product_bidding_category in result:
- category_id = product_bidding_category['dimensionValue']['value']
- parent_id = None
- name = product_bidding_category['displayValue'][0]['value']
-
- # Note: There may be cases where there isn't a value.
- if ('parentDimensionValue' in product_bidding_category and
- 'value' in product_bidding_category['parentDimensionValue']):
- parent_id = product_bidding_category['parentDimensionValue']['value']
-
- if category_id not in bidding_categories:
- bidding_categories[category_id] = {}
-
- category = bidding_categories[category_id]
-
- if parent_id is not None:
- if parent_id not in bidding_categories:
- bidding_categories[parent_id] = {}
-
- parent = bidding_categories[parent_id]
-
- if 'children' not in parent:
- parent['children'] = []
-
- parent['children'].append(category)
- else:
- root_categories.append(category)
-
- category['id'] = category_id
- category['name'] = name
-
- DisplayCategories(root_categories)
-
-
-def DisplayCategories(categories, prefix=''):
- for category in categories:
- print '%s%s [%s]' % (prefix, category['name'], category['id'])
-
- if 'children' in category:
- DisplayCategories(category['children'], '%s%s > ' % (prefix,
- category['name']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201406/shopping/set_product_sales_channel.py b/examples/adwords/v201406/shopping/set_product_sales_channel.py
deleted file mode 100755
index 245fa722..00000000
--- a/examples/adwords/v201406/shopping/set_product_sales_channel.py
+++ /dev/null
@@ -1,71 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example sets the product sales channel.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignCriterionService.mutate
-"""
-
-__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import adwords
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-
-# ProductSalesChannel is a fixedId criterion, with the possible values
-# defined here.
-ONLINE = '200'
-LOCAL = '201'
-
-
-def main(client, campaign_id):
- campaign_criterion_service = client.GetService(
- 'CampaignCriterionService', version='v201406')
-
- product_sales_channel = {
- 'xsi_type': 'ProductSalesChannel',
- 'id': ONLINE
- }
-
- campaign_criterion = {
- 'campaignId': campaign_id,
- 'criterion': product_sales_channel
- }
-
- operations = [{
- 'operator': 'ADD',
- 'operand': campaign_criterion
- }]
-
- result = campaign_criterion_service.mutate(operations)
-
- for criterion in result['value']:
- print ('Added ProductSalesChannel CampaignCriterion with ID: %s'
- % (criterion['criterion']['id']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201406/targeting/__init__.py b/examples/adwords/v201406/targeting/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/examples/adwords/v201406/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201406/targeting/add_campaign_targeting_criteria.py
deleted file mode 100755
index 538b5661..00000000
--- a/examples/adwords/v201406/targeting/add_campaign_targeting_criteria.py
+++ /dev/null
@@ -1,159 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds various types of targeting criteria to a given campaign.
-
-To get campaigns, run get_campaigns.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignCriterionService.mutate
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-
-
-def main(client, campaign_id):
- # Initialize appropriate service.
- campaign_criterion_service = client.GetService(
- 'CampaignCriterionService', version='v201406')
-
- # Create locations. The IDs can be found in the documentation or retrieved
- # with the LocationCriterionService.
- california = {
- 'xsi_type': 'Location',
- 'id': '21137'
- }
- mexico = {
- 'xsi_type': 'Location',
- 'id': '2484'
- }
-
- # Create languages. The IDs can be found in the documentation or retrieved
- # with the ConstantDataService.
- english = {
- 'xsi_type': 'Language',
- 'id': '1000'
- }
- spanish = {
- 'xsi_type': 'Language',
- 'id': '1003'
- }
-
- # Create location groups. The IDs can be found in the documentation or
- # retrieved with the LocationCriterionService.
- florida_tier3 = {
- 'xsi_type': 'LocationGroups',
- 'matchingFunction': {
- 'operator': 'AND',
- 'lhsOperand': [{
- 'xsi_type': 'IncomeOperand',
- # Tiers are numbered 1-10, and represent 10% segments of earners.
- # For example, TIER_1 is the top 10%, TIER_2 is the 80-90%, etc.
- # Tiers 6 through 10 are grouped into TIER_6_TO_10.
- 'tier': 'TIER_3'
- }],
- 'rhsOperand': [{
- 'xsi_type': 'GeoTargetOperand',
- 'locations': [1015116] # Miami, FL
- }]
- },
- }
- florida_downtown = {
- 'xsi_type': 'LocationGroups',
- 'matchingFunction': {
- 'operator': 'AND',
- 'lhsOperand': [{
- 'xsi_type': 'PlacesOfInterestOperand',
- # Other valid options: AIRPORT, UNIVERSITY.
- 'category': 'DOWNTOWN',
- }],
- 'rhsOperand': [{
- 'xsi_type': 'GeoTargetOperand',
- 'locations': [1015116] # Miami, FL
- }]
- }
- }
- # Distance targeting. Area of 10 miles around targets above.
- distance_10_miles = {
- 'xsi_type': 'LocationGroups',
- 'matchingFunction': {
- 'operator': 'IDENTITY',
- 'lhsOperand': [{
- 'xsi_type': 'LocationExtensionOperand',
- 'radius': {
- 'xsi_type': 'ConstantOperand',
- 'type': 'DOUBLE',
- 'unit': 'MILES',
- 'doubleValue': 10
- }
-
- }]
- }
- }
- # Create a negative campaign criterion operation.
- negative_campaign_criterion_operand = {
- 'xsi_type': 'NegativeCampaignCriterion',
- 'campaignId': campaign_id,
- 'criterion': {
- 'xsi_type': 'Keyword',
- 'matchType': 'BROAD',
- 'text': 'jupiter cruise'
- }
- }
-
- # Create operations
- operations = []
- for criterion in [california, mexico, english, spanish, florida_tier3,
- florida_downtown, distance_10_miles]:
- operations.append({
- 'operator': 'ADD',
- 'operand': {
- 'campaignId': campaign_id,
- 'criterion': criterion
- }
- })
- # Add the negative campaign criterion.
- operations.append({
- 'operator': 'ADD',
- 'operand': negative_campaign_criterion_operand
- })
-
- # Make the mutate request.
- result = campaign_criterion_service.mutate(operations)
-
- # Display the resulting campaign criteria.
- for campaign_criterion in result['value']:
- print ('Campaign criterion with campaign id \'%s\', criterion id \'%s\', '
- 'and type \'%s\' was added.'
- % (campaign_criterion['campaignId'],
- campaign_criterion['criterion']['id'],
- campaign_criterion['criterion']['type']))
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201406/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201406/targeting/add_demographic_targeting_criteria.py
deleted file mode 100755
index 77b77b29..00000000
--- a/examples/adwords/v201406/targeting/add_demographic_targeting_criteria.py
+++ /dev/null
@@ -1,99 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds demographic criteria to an ad group.
-
-To get a list of ad groups, run get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupCriterionService.mutate
-"""
-
-__author__ = 'Joseph Dilallo'
-
-from googleads import adwords
-
-
-GENDER_MALE = '10'
-AGE_RANGE_UNDETERMINED = '503999'
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Initialize appropriate service.
- ad_group_criterion_service = client.GetService(
- 'AdGroupCriterionService', version='v201406')
-
- # Create the ad group criteria.
- ad_group_criteria = [
- # Targeting criterion.
- {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Gender',
- # Create gender criteria. The IDs can be found in the
- # documentation:
- # https://developers.google.com/adwords/api/docs/appendix/genders.
- 'id': GENDER_MALE
- }
- },
- # Exclusion criterion.
- {
- 'xsi_type': 'NegativeAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'AgeRange',
- # Create age range criteria. The IDs can be found in the
- # documentation:
- # https://developers.google.com/adwords/api/docs/appendix/ages.
- 'id': AGE_RANGE_UNDETERMINED
- }
- }
- ]
-
- # Create operations.
- operations = []
- for criterion in ad_group_criteria:
- operations.append({
- 'operator': 'ADD',
- 'operand': criterion
- })
-
- response = ad_group_criterion_service.mutate(operations)
-
- if response and response['value']:
- criteria = response['value']
- for ad_group_criterion in criteria:
- criterion = ad_group_criterion['criterion']
- print ('Ad group criterion with ad group ID %s, criterion ID %s and '
- 'type \'%s\' was added.' %
- (ad_group_criterion['adGroupId'], criterion['id'],
- criterion['type']))
- else:
- print 'No criteria were returned.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201406/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201406/targeting/get_campaign_targeting_criteria.py
deleted file mode 100755
index e1ea10c0..00000000
--- a/examples/adwords/v201406/targeting/get_campaign_targeting_criteria.py
+++ /dev/null
@@ -1,89 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example illustrates how to retrieve all the campaign targets.
-
-To set campaign targets, run add_campaign_targeting_criteria.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignCriterionService.get
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-PAGE_SIZE = 500
-
-
-def main(client):
- # Initialize appropriate service.
- campaign_criterion_service = client.GetService(
- 'CampaignCriterionService', version='v201406')
-
- # Construct selector and get all campaign targets.
- offset = 0
- selector = {
- 'fields': ['CampaignId', 'Id', 'CriteriaType', 'PlatformName',
- 'LanguageName', 'LocationName', 'KeywordText'],
- 'predicates': [{
- 'field': 'CriteriaType',
- 'operator': 'IN',
- 'values': ['KEYWORD', 'LANGUAGE', 'LOCATION', 'PLATFORM']
- }],
- 'paging': {
- 'startIndex': str(offset),
- 'numberResults': str(PAGE_SIZE)
- }
- }
- more_pages = True
- while more_pages:
- page = campaign_criterion_service.get(selector)
-
- # Display results.
- if 'entries' in page:
- for campaign_criterion in page['entries']:
- negative = ''
- if (campaign_criterion['CampaignCriterion.Type']
- == 'NegativeCampaignCriterion'):
- negative = 'Negative '
- criterion = campaign_criterion['criterion']
- criteria = (criterion['text'] if 'text' in criterion else
- criterion['platformName'] if 'platformName' in criterion
- else criterion['name'] if 'name' in criterion else
- criterion['locationName'] if 'locationName' in criterion
- else None)
- print ('%sCampaign Criterion found for Campaign ID %s with type %s and '
- 'criteria "%s".' % (negative, campaign_criterion['campaignId'],
- criterion['type'], criteria))
- else:
- print 'No campaign targets were found.'
- offset += PAGE_SIZE
- selector['paging']['startIndex'] = str(offset)
- more_pages = offset < int(page['totalNumEntries'])
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201406/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201406/targeting/get_targetable_languages_and_carriers.py
deleted file mode 100755
index a22c345b..00000000
--- a/examples/adwords/v201406/targeting/get_targetable_languages_and_carriers.py
+++ /dev/null
@@ -1,60 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Retrieves all languages and carriers available for targeting.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ConstantDataService.getLanguageCriterion
-Tags: ConstantDataService.getCarrierCriterion
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-def main(client):
- # Initialize appropriate service.
- constant_data_service = client.GetService(
- 'ConstantDataService', version='v201406')
-
- # Get all languages.
- languages = constant_data_service.getLanguageCriterion()
-
- # Display results.
- for language in languages:
- print ('Language with name \'%s\' and ID \'%s\' was found.'
- % (language['name'], language['id']))
-
- # Get all carriers.
- carriers = constant_data_service.getCarrierCriterion()
-
- # Display results.
- for carrier in carriers:
- print ('Carrier with name \'%s\', ID \'%s\', and country code \'%s\' was '
- 'found.' % (carrier['name'], carrier['id'], carrier['countryCode']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201406/targeting/lookup_location.py b/examples/adwords/v201406/targeting/lookup_location.py
deleted file mode 100755
index a49d2055..00000000
--- a/examples/adwords/v201406/targeting/lookup_location.py
+++ /dev/null
@@ -1,86 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all LocationCriterion.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: LocationCriterionService.get
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-def GetLocationString(location):
- return '%s (%s)' % (location['locationName'], location['displayType']
- if 'displayType' in location else None)
-
-
-def main(client):
- # Initialize appropriate service.
- location_criterion_service = client.GetService(
- 'LocationCriterionService', version='v201406')
-
- location_names = ['Paris', 'Quebec', 'Spain', 'Deutchland']
-
- # Create the selector.
- selector = {
- 'fields': ['Id', 'LocationName', 'DisplayType', 'CanonicalName',
- 'ParentLocations', 'Reach', 'TargetingStatus'],
- 'predicates': [{
- 'field': 'LocationName',
- 'operator': 'IN',
- 'values': location_names
- }, {
- 'field': 'Locale',
- 'operator': 'EQUALS',
- 'values': ['en']
- }]
- }
-
- # Make the get request.
- location_criteria = location_criterion_service.get(selector)
-
- # Display the resulting location criteria.
- for location_criterion in location_criteria:
- parent_string = ''
- if ('parentLocations' in location_criterion['location']
- and location_criterion['location']['parentLocations']):
- parent_string = ', '.join([GetLocationString(parent)for parent in
- location_criterion['location']
- ['parentLocations']])
- print ('The search term \'%s\' returned the location \'%s\' of type \'%s\''
- ' with parent locations \'%s\', reach \'%s\' and id \'%s\' (%s)'
- % (location_criterion['searchTerm'],
- location_criterion['location']['locationName'],
- location_criterion['location']['displayType'], parent_string,
- location_criterion['reach']
- if 'reach' in location_criterion else None,
- location_criterion['location']['id'],
- location_criterion['location']['targetingStatus']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201409/__init__.py b/examples/adwords/v201409/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/examples/adwords/v201409/account_management/__init__.py b/examples/adwords/v201409/account_management/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/examples/adwords/v201409/account_management/create_account.py b/examples/adwords/v201409/account_management/create_account.py
deleted file mode 100755
index 363deb80..00000000
--- a/examples/adwords/v201409/account_management/create_account.py
+++ /dev/null
@@ -1,67 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example illustrates how to create an account.
-
-By default this account will only be accessible via parent MCC.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreateAccountService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from datetime import datetime
-
-from googleads import adwords
-
-
-def main(client):
- # Initialize appropriate service.
- managed_customer_service = client.GetService(
- 'ManagedCustomerService', version='v201409')
-
- today = datetime.today().strftime('%Y%m%d %H:%M:%S')
- # Construct operations and add campaign.
- operations = [{
- 'operator': 'ADD',
- 'operand': {
- 'name': 'Account created with ManagedCustomerService on %s' % today,
- 'currencyCode': 'EUR',
- 'dateTimeZone': 'Europe/London',
- }
- }]
-
- # Create the account. It is possible to create multiple accounts with one
- # request by sending an array of operations.
- accounts = managed_customer_service.mutate(operations)
-
- # Display results.
- for account in accounts['value']:
- print ('Account with customer ID \'%s\' was successfully created.'
- % account['customerId'])
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
- main(adwords_client)
diff --git a/examples/adwords/v201409/account_management/get_account_changes.py b/examples/adwords/v201409/account_management/get_account_changes.py
deleted file mode 100755
index a7817923..00000000
--- a/examples/adwords/v201409/account_management/get_account_changes.py
+++ /dev/null
@@ -1,102 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets the changes in the account during the last 24 hours.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomerSyncService.get
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-import datetime
-
-from googleads import adwords
-
-
-def main(client):
- # Initialize appropriate service.
- customer_sync_service = client.GetService(
- 'CustomerSyncService', version='v201409')
- campaign_service = client.GetService('CampaignService', version='v201409')
-
- # Construct selector and get all campaigns.
- selector = {
- 'fields': ['Id', 'Name', 'Status']
- }
- campaigns = campaign_service.get(selector)
- campaign_ids = []
- if 'entries' in campaigns:
- for campaign in campaigns['entries']:
- campaign_ids.append(campaign['id'])
- else:
- print 'No campaigns were found.'
- return
-
- # Construct selector and get all changes.
- today = datetime.datetime.today()
- yesterday = today - datetime.timedelta(1)
- selector = {
- 'dateTimeRange': {
- 'min': yesterday.strftime('%Y%m%d %H%M%S'),
- 'max': today.strftime('%Y%m%d %H%M%S')
- },
- 'campaignIds': campaign_ids
- }
- account_changes = customer_sync_service.get(selector)
-
- # Display results.
- if account_changes:
- if 'lastChangeTimestamp' in account_changes:
- print 'Most recent changes: %s' % account_changes['lastChangeTimestamp']
- if account_changes['changedCampaigns']:
- for data in account_changes['changedCampaigns']:
- print ('Campaign with id \'%s\' has change status \'%s\'.'
- % (data['campaignId'], data['campaignChangeStatus']))
- if (data['campaignChangeStatus'] != 'NEW' and
- data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'):
- print ' Added ad extensions: %s' % data.get('addedAdExtensions')
- print ' Removed ad extensions: %s' % data.get('deletedAdExtensions')
- print (' Added campaign criteria: %s'
- % data.get('addedCampaignCriteria'))
- print (' Removed campaign criteria: %s'
- % data.get('deletedCampaignCriteria'))
- print (' Campaign targeting changed: %s'
- % data.get('campaignTargetingChanged'))
- if data.get('changedAdGroups'):
- for ad_group_data in data['changedAdGroups']:
- print (' Ad group with id \'%s\' has change status \'%s\'.'
- % (ad_group_data['adGroupId'],
- ad_group_data['adGroupChangeStatus']))
- if ad_group_data['adGroupChangeStatus'] != 'NEW':
- print ' Changed ads: %s' % ad_group_data['changedAds']
- print (' Changed criteria: %s'
- % ad_group_data['changedCriteria'])
- print (' Removed criteria: %s'
- % ad_group_data['deletedCriteria'])
- else:
- print 'No changes were found.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
- main(adwords_client)
diff --git a/examples/adwords/v201409/account_management/get_account_hierarchy.py b/examples/adwords/v201409/account_management/get_account_hierarchy.py
deleted file mode 100755
index 7b5f1ae4..00000000
--- a/examples/adwords/v201409/account_management/get_account_hierarchy.py
+++ /dev/null
@@ -1,97 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets the account hierarchy under the current account.
-
-Note: this code example won't work with test accounts. See
-https://developers.google.com/adwords/api/docs/test-accounts
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ServicedAccountService.get
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-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 = '-' * depth * 2
- print '%s%s, %s' % (prefix, account['customerId'], account['name'])
- if account['customerId'] in links:
- for child_link in links[account['customerId']]:
- child_account = accounts[child_link['clientCustomerId']]
- DisplayAccountTree(child_account, accounts, links, depth + 1)
-
-
-def main(client):
- # Initialize appropriate service.
- managed_customer_service = client.GetService(
- 'ManagedCustomerService', version='v201409')
-
- # Construct selector to get all accounts.
- selector = {
- 'fields': ['CustomerId', 'Name']
- }
- # Get serviced account graph.
- graph = managed_customer_service.get(selector)
- if 'entries' in graph and graph['entries']:
- # Create map from customerId to parent and child links.
- child_links = {}
- parent_links = {}
- if 'links' in graph:
- for link in graph['links']:
- if link['managerCustomerId'] not in child_links:
- child_links[link['managerCustomerId']] = []
- child_links[link['managerCustomerId']].append(link)
- if link['clientCustomerId'] not in parent_links:
- parent_links[link['clientCustomerId']] = []
- parent_links[link['clientCustomerId']].append(link)
- # Create map from customerID to account and find root account.
- accounts = {}
- root_account = None
- for account in graph['entries']:
- accounts[account['customerId']] = account
- if account['customerId'] not in parent_links:
- root_account = account
- # Display account tree.
- if root_account:
- print 'CustomerId, Name'
- DisplayAccountTree(root_account, accounts, child_links, 0)
- else:
- print 'Unable to determine a root account'
- else:
- print 'No serviced accounts were found'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
- main(adwords_client)
diff --git a/examples/adwords/v201409/advanced_operations/__init__.py b/examples/adwords/v201409/advanced_operations/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/examples/adwords/v201409/advanced_operations/add_ad_customizer.py b/examples/adwords/v201409/advanced_operations/add_ad_customizer.py
deleted file mode 100755
index c2ad3b64..00000000
--- a/examples/adwords/v201409/advanced_operations/add_ad_customizer.py
+++ /dev/null
@@ -1,251 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Adds an ad customizer feed.
-
-Associates the feed with customer and adds an ad that
-uses the feed to populate dynamic data.
-
-Tags: CustomerFeedService.mutate, FeedItemService.mutate
-Tags: FeedMappingService.mutate, FeedService.mutate
-Tags: AdGroupAdService.mutate
-"""
-
-__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)',
- 'yufeng.dev@gmail.com (Yufeng Guo)')
-
-# Import appropriate classes from the client library.
-from googleads import adwords
-
-# See the Placeholder reference page for a list of all the placeholder types
-# and fields:
-# https://developers.google.com/adwords/api/docs/appendix/placeholders
-PLACEHOLDER_AD_CUSTOMIZER = '10'
-PLACEHOLDER_FIELD_INTEGER = '1'
-PLACEHOLDER_FIELD_FLOAT = '2'
-PLACEHOLDER_FIELD_PRICE = '3'
-PLACEHOLDER_FIELD_DATE = '4'
-PLACEHOLDER_FIELD_STRING = '5'
-
-ADGROUPS = [
- 'INSERT_ADGROUP_ID_HERE',
- 'INSERT_ADGROUP_ID_HERE'
-]
-
-FEEDNAME = 'INSERT_FEED_NAME_HERE'
-
-
-def main(client, adgroups):
- # Initialize appropriate services.
- ad_group_ad_service = client.GetService('AdGroupAdService', version='v201409')
- customer_feed_service = client.GetService(
- 'CustomerFeedService', version='v201409')
- feed_item_service = client.GetService('FeedItemService', version='v201409')
- feed_mapping_service = client.GetService(
- 'FeedMappingService', version='v201409')
- feed_service = client.GetService('FeedService', version='v201409')
-
- # First, create a customizer feed. One feed per account can be used for all
- # ads.
- customizer_feed = {
- 'name': FEEDNAME,
- 'attributes': [
- {'type': 'STRING', 'name': 'Name'},
- {'type': 'STRING', 'name': 'Price'},
- {'type': 'DATE_TIME', 'name': 'Date'}
- ]
- }
-
- feed_service_operation = {
- 'operator': 'ADD',
- 'operand': customizer_feed
- }
-
- response = feed_service.mutate([feed_service_operation])
-
- if response and 'value' in response:
- feed = response['value'][0]
- feed_data = {
- 'feedId': feed['id'],
- 'nameId': feed['attributes'][0]['id'],
- 'priceId': feed['attributes'][1]['id'],
- 'dateId': feed['attributes'][2]['id']
- }
- print ('Feed with name \'%s\' and ID %s was added with:'
- '\tName attribute ID %s and price attribute ID %s and date attribute'
- 'ID %s') % (feed['name'], feed['id'], feed_data['nameId'],
- feed_data['priceId'], feed_data['dateId'])
- else:
- raise Exception('No feeds were added')
-
- # Creating feed mapping to map the fields with customizer IDs.
- feed_mapping = {
- 'placeholderType': PLACEHOLDER_AD_CUSTOMIZER,
- 'feedId': feed_data['feedId'],
- 'attributeFieldMappings': [
- {
- 'feedAttributeId': feed_data['nameId'],
- 'fieldId': PLACEHOLDER_FIELD_STRING
- },
- {
- 'feedAttributeId': feed_data['priceId'],
- 'fieldId': PLACEHOLDER_FIELD_PRICE
- },
- {
- 'feedAttributeId': feed_data['dateId'],
- 'fieldId': PLACEHOLDER_FIELD_DATE
- }
- ]
- }
-
- feed_mapping_operation = {
- 'operator': 'ADD',
- 'operand': feed_mapping
- }
-
- response = feed_mapping_service.mutate([feed_mapping_operation])
-
- if response and 'value' in response:
- feed_mapping = response['value'][0]
- print ('Feed mapping with ID %s and placeholder type %s was saved for feed'
- ' with ID %s.') % (feed_mapping['feedMappingId'],
- feed_mapping['placeholderType'],
- feed_mapping['feedId'])
- else:
- raise Exception('No feed mappings were added.')
-
- # Now adding feed items -- the values we'd like to place.
- items_data = [
- {
- 'name': 'Mars',
- 'price': '$1234.56',
- 'date': '20140601 000000',
- 'adGroupId': adgroups[0]
- },
- {
- 'name': 'Venus',
- 'price': '$1450.00',
- 'date': '20140615 120000',
- 'adGroupId': adgroups[1]
- }
- ]
-
- feed_items = [{'feedId': feed_data['feedId'],
- 'adGroupTargeting': {
- 'TargetingAdGroupId': item['adGroupId']
- },
- 'attributeValues': [
- {
- 'feedAttributeId': feed_data['nameId'],
- 'stringValue': item['name']
- },
- {
- 'feedAttributeId': feed_data['priceId'],
- 'stringValue': item['price']
- },
- {
- 'feedAttributeId': feed_data['dateId'],
- 'stringValue': item['date']
- }
- ]} for item in items_data]
-
- feed_item_operations = [{
- 'operator': 'ADD',
- 'operand': feed_item
- } for feed_item in feed_items]
-
- response = feed_item_service.mutate(feed_item_operations)
-
- if response and 'value' in response:
- for feed_item in response['value']:
- print 'Feed item with ID %s was added.' % feed_item['feedItemId']
- else:
- raise Exception('No feed items were added.')
-
- # Finally, creating a customer (account-level) feed with a matching function
- # that determines when to use this feed. For this case we use the "IDENTITY"
- # matching function that is always 'true' just to associate this feed with
- # the customer. The targeting is done within the feed items using the
- # :campaign_targeting, :ad_group_targeting, or :keyword_targeting attributes.
- matching_function = {
- 'operator': 'IDENTITY',
- 'lhsOperand': [
- {
- 'xsi_type': 'ConstantOperand',
- 'type': 'BOOLEAN',
- 'booleanValue': 'true'
- }
- ]
- }
-
- customer_feed = {
- 'feedId': feed_data['feedId'],
- 'matchingFunction': matching_function,
- 'placeholderTypes': [PLACEHOLDER_AD_CUSTOMIZER]
- }
-
- customer_feed_operation = {
- 'operator': 'ADD',
- 'operand': customer_feed
- }
-
- response = customer_feed_service.mutate([customer_feed_operation])
-
- if response and 'value' in response:
- feed = response['value'][0]
- print 'Customer feed with ID %s was added.' % feed['feedId']
- else:
- raise Exception('No customer feeds were added.')
-
- # All set! We can now create ads with customizations.
- text_ad = {
- 'xsi_type': 'TextAd',
- 'headline': 'Luxury Cruise to {=%s.Name}' % FEEDNAME,
- 'description1': 'Only {=%s.Price}' % FEEDNAME,
- 'description2': 'Offer ends in {=countdown(%s.Date)}!' % FEEDNAME,
- 'finalUrls': ['http://www.example.com'],
- 'displayUrl': 'www.example.com'
- }
-
- # We add the same ad to both ad groups. When they serve, they will show
- # different values, since they match different feed items.
- operations = [{
- 'operator': 'ADD',
- 'operand': {
- 'adGroupId': adgroup,
- 'ad': text_ad
- }
- } for adgroup in adgroups]
-
- print operations
-
- response = ad_group_ad_service.mutate(operations)
-
- print '===ad group ad service==='
- print response
-
- if response and 'value' in response:
- for ad in response['value']:
- print ('\tCreated an ad with ID \'%s\', type \'%s\', and status \'%s\'.'
- % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status']))
- else:
- raise Exception('No ads were added.')
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
- main(adwords_client, ADGROUPS)
diff --git a/examples/adwords/v201409/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201409/advanced_operations/add_ad_group_bid_modifier.py
deleted file mode 100755
index 16cac4c7..00000000
--- a/examples/adwords/v201409/advanced_operations/add_ad_group_bid_modifier.py
+++ /dev/null
@@ -1,78 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Adds an ad group level mobile bid modifier override for a campaign.
-
-To get your ad groups, run get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupBidModifierService.mutate
-"""
-
-__author__ = 'Joseph DiLallo'
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-BID_MODIFIER = 'INSERT_BID_MODIFIER_HERE'
-
-
-def main(client, ad_group_id, bid_modifier):
- # Initialize appropriate service.
- ad_group_bid_modifier_service = client.GetService(
- 'AdGroupBidModifierService', version='v201409')
-
- # Mobile criterion ID.
- criterion_id = '30001'
-
- # Prepare to add an ad group level override.
- operation = {
- # Use 'ADD' to add a new modifier and 'SET' to update an existing one. A
- # modifier can be removed with the 'REMOVE' operator.
- 'operator': 'ADD',
- 'operand': {
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Platform',
- 'id': criterion_id
- },
- 'bidModifier': bid_modifier
- }
- }
-
- # Add ad group level mobile bid modifier.
- response = ad_group_bid_modifier_service.mutate([operation])
- if response and response['value']:
- modifier = response['value'][0]
- value = modifier['bidModifier'] if 'bidModifier' in modifier else 'unset'
- print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s was updated with '
- 'ad group level modifier: %s' %
- (modifier['campaignId'], modifier['adGroupId'],
- modifier['criterion']['id'], value))
- else:
- print 'No modifiers were added.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID, BID_MODIFIER)
diff --git a/examples/adwords/v201409/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201409/advanced_operations/add_click_to_download_ad.py
deleted file mode 100755
index a6cf1956..00000000
--- a/examples/adwords/v201409/advanced_operations/add_click_to_download_ad.py
+++ /dev/null
@@ -1,114 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates a click-to-download ad in a given ad group.
-
-This type of ad is also known as an app promotion ad. To list ad groups, run
-get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupAdService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = 'Joseph DiLallo'
-
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Initialize appropriate service.
- ad_group_ad_service = client.GetService('AdGroupAdService', version='v201409')
-
- # Create the template elements for the ad. You can refer to
- # https://developers.google.com/adwords/api/docs/appendix/templateads
- # for the list of available template fields.
- ad_data = {
- 'uniqueName': 'adData',
- 'fields': [
- {
- 'name': 'headline',
- 'fieldText': 'Enjoy your drive in Mars',
- 'type': 'TEXT'
- },
- {
- 'name': 'description1',
- 'fieldText': 'Realistic physics simulation',
- 'type': 'TEXT'
- },
- {
- 'name': 'description2',
- 'fieldText': 'Race against players online',
- 'type': 'TEXT'
- },
- {
- 'name': 'appId',
- 'fieldText': 'com.example.demogame',
- 'type': 'TEXT'
- },
- {
- 'name': 'appStore',
- 'fieldText': '2',
- 'type': 'ENUM'
- }
- ]
- }
-
- # Create click to download ad.
- click_to_download_app_ad = {
- 'xsi_type': 'TemplateAd',
- 'name': 'Ad for demo game',
- 'templateId': '353',
- 'finalUrls': [
- 'http://play.google.com/store/apps/details?id=com.example.demogame'
- ],
- 'displayUrl': 'play.google.com',
- 'templateElements': [ad_data]
- }
-
- # Create ad group ad.
- ad_group_ad = {
- 'adGroupId': ad_group_id,
- 'ad': click_to_download_app_ad,
- # Optional.
- 'status': 'PAUSED'
- }
-
- # Add ad.
- ads = ad_group_ad_service.mutate([
- {'operator': 'ADD', 'operand': ad_group_ad}
- ])
- # Display results.
- if 'value' in ads:
- for ad in ads['value']:
- print ('Added new click-to-download ad to ad group ID \'%s\' '
- 'with URL \'%s\'.' % (ad['ad']['id'], ad['ad']['finalUrls'][0]))
- else:
- print 'No ads were added.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201409/advanced_operations/add_text_ad_with_upgraded_urls.py b/examples/adwords/v201409/advanced_operations/add_text_ad_with_upgraded_urls.py
deleted file mode 100755
index d9675246..00000000
--- a/examples/adwords/v201409/advanced_operations/add_text_ad_with_upgraded_urls.py
+++ /dev/null
@@ -1,114 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds a text add that uses advanced features of upgraded URLS.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupAdService.mutate
-"""
-
-__author__ = 'Mark Saniscalchi'
-
-from googleads import adwords
-from googleads import errors
-
-
-ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE'
-
-
-def main(client, adgroup_id):
- # Initialize appropriate service.
- adgroup_ad_service = client.GetService('AdGroupAdService', version='v201409')
-
- # Create the text ad
- text_ad = {
- 'xsi_type': 'TextAd',
- 'headline': 'Luxury Cruise to Mars',
- 'description1': 'Visit the Red Planet in style.',
- 'description2': 'Low-gravity fun for everyone!',
- 'displayUrl': 'www.example.com',
- # Specify a tracking URL for 3rd party tracking provider. You may specify
- # one at customer, campaign, ad group, ad, criterion or feed item levels.
- 'trackingUrlTemplate': ('http://tracker.example.com/?season={_season}'
- '&promocode={_promocode}&u={lpurl}'),
- 'urlCustomParameters': {
- 'parameters': [
- # Since your tracking URL has two custom parameters, provide
- # their values too. This can be provided at campaign, ad group,
- # ad, criterion, or feed item levels.
- {
- 'key': 'season',
- 'value': 'christmas'
- },
- {
- 'key': 'promocode',
- 'value': 'NYC123'
- }
- ]
- },
- # Specify a list of final URLs. This field cannot be set if URL
- # field is set, or finalUrls is unset. This may be specified at ad,
- # criterion, and feed item levels.
- 'finalUrls': [
- 'http://www.example.com/cruise/space/',
- 'http://www.example.com/locations/mars/'
- ],
- # Specify a list of final mobile URLs. This field cannot be set if URL
- # field is set, or finalUrls is unset. This may be specified at ad,
- # criterion, and feed item levels.
- 'finalMobileUrls': [
- 'http://mobile.example.com/cruise/space/',
- 'http://mobile.example.com/locations/mars/'
- ]
- }
-
- text_adgroup_ad = {
- 'adGroupId': adgroup_id,
- 'ad': text_ad,
- # Optional: Set the status.
- 'status': 'PAUSED'
- }
-
- operations = [{
- 'operator': 'ADD',
- 'operand': text_adgroup_ad
- }]
-
- response = adgroup_ad_service.mutate(operations)
-
- if 'value' in response:
- for adgroup_ad in response['value']:
- print ('AdGroupAd with ID %s and display URL \'%s\'was added.'
- % (adgroup_ad['ad']['id'], adgroup_ad['ad']['displayUrl']))
- print 'Upgraded URL properties:'
- print 'Final Urls: %s' % adgroup_ad['ad']['finalUrls']
- print 'Final Mobile URLs: %s' % adgroup_ad['ad']['finalMobileUrls']
- print ('Tracking URL template: %s'
- % adgroup_ad['ad']['trackingUrlTemplate'])
- print 'Custom parameters: %s' % adgroup_ad['ad']['urlCustomParameters']
- else:
- raise errors.GoogleAdsError('Failed to create AdGroupAd.')
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, ADGROUP_ID)
diff --git a/examples/adwords/v201409/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201409/advanced_operations/get_ad_group_bid_modifier.py
deleted file mode 100755
index 7bd8e214..00000000
--- a/examples/adwords/v201409/advanced_operations/get_ad_group_bid_modifier.py
+++ /dev/null
@@ -1,76 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Retrieves the ad group level bid modifiers for a campaign.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupBidModifierService.get
-"""
-
-__author__ = 'Joseph DiLallo'
-
-from googleads import adwords
-
-
-PAGE_SIZE = 500
-
-
-def main(client):
- # Initialize appropriate service.
- ad_group_bid_modifier_service = client.GetService(
- 'AdGroupBidModifierService', version='v201409')
-
- # Get all ad group bid modifiers for the campaign.
- selector = {
- 'fields': ['CampaignId', 'AdGroupId', 'BidModifier', 'Id'],
- 'paging': {
- 'startIndex': '0',
- 'numberResults': str(PAGE_SIZE)
- }
- }
-
- # Set initial values.
- offset, page = 0, {}
- more_results = True
-
- while more_results:
- page = ad_group_bid_modifier_service.get(selector)
- if page['entries']:
- for modifier in page['entries']:
- value = (modifier['bidModifier'] if 'bidModifier' in modifier
- else 'unset')
- print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s has ad group '
- 'level modifier: %s' %
- (modifier['campaignId'], modifier['adGroupId'],
- modifier['criterion']['id'], value))
-
- # Increment values to request the next page.
- offset += PAGE_SIZE
- selector['paging']['startIndex'] = str(offset)
- else:
- print 'No ad group bid modifiers returned.'
- more_results = int(page['totalNumEntries']) > offset
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201409/advanced_operations/upload_offline_conversions.py b/examples/adwords/v201409/advanced_operations/upload_offline_conversions.py
deleted file mode 100755
index b45759c6..00000000
--- a/examples/adwords/v201409/advanced_operations/upload_offline_conversions.py
+++ /dev/null
@@ -1,101 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Imports offline conversion values for specific clicks into your account.
-
-To get the Google Click ID for a click, run a CLICK_PERFORMANCE_REPORT.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ConversionTrackerService.mutate, OfflineConversionFeedService.mutate
-"""
-
-__author__ = 'Joseph DiLallo'
-
-from googleads import adwords
-
-
-CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE'
-# Your click ID must be less than 30 days old.
-CLICK_ID = 'INSERT_GOOGLE_CLICK_ID_HERE'
-# The conversion time must be more recent than the time of the click.
-CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE'
-CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE'
-
-
-def main(client, conversion_name, click_id, conversion_time, conversion_value):
- # Initialize appropriate services.
- conversion_tracker_service = client.GetService('ConversionTrackerService',
- version='v201409')
-
- offline_conversion_feed_service = client.GetService(
- 'OfflineConversionFeedService', version='v201409')
-
- # Once created, this entry will be visible under
- # Tools and Analysis->Conversion and will have "Source = Import".
- upload_conversion = {
- 'xsi_type': 'UploadConversion',
- 'category': 'PAGE_VIEW',
- 'name': conversion_name,
- 'viewthroughLookbackWindow': '30',
- 'ctcLookbackWindow': '90'
- }
-
- upload_conversion_operation = {
- 'operator': 'ADD',
- 'operand': upload_conversion
- }
-
- response = conversion_tracker_service.mutate(
- [upload_conversion_operation])
- new_upload_conversion = response['value']
-
- print ('New upload conversion type with name \'%s\' and ID \'%s\' was '
- 'created.' % (new_upload_conversion['name'],
- new_upload_conversion['id']))
-
- # Associate offline conversions with the upload conversion we created.
- feed = {
- 'conversionName': conversion_name,
- 'conversionTime': conversion_time,
- 'conversionValue': conversion_value,
- 'googleClickId': click_id
- }
-
- offline_conversion_operation = {
- 'operator': 'ADD',
- 'operand': feed
- }
-
- offline_conversion_response = offline_conversion_feed_service.mutate(
- [offline_conversion_operation])
- new_feed = offline_conversion_response['value']
-
- print ('Uploaded offline conversion value of \'%s\' for Google Click ID '
- '\'%s\' to \'%s\'.' % (new_feed['conversionValue'],
- new_feed['googleClickId'],
- new_feed['conversionName']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CONVERSION_NAME, CLICK_ID, CONVERSION_TIME,
- CONVERSION_VALUE)
diff --git a/examples/adwords/v201409/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201409/advanced_operations/use_shared_bidding_strategy.py
deleted file mode 100755
index 6e880095..00000000
--- a/examples/adwords/v201409/advanced_operations/use_shared_bidding_strategy.py
+++ /dev/null
@@ -1,176 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Adds a Shared Bidding Strategy and uses it to construct a campaign.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: BiddingStrategyService.mutate
-Tags: BudgetService.mutate, CampaignService.mutate
-"""
-
-__author__ = 'Joseph DiLallo'
-
-import uuid
-
-from googleads import adwords
-
-
-# Enter a shared budget ID to re-use an existing budget or leave as None to
-# create a new one.
-BUDGET_ID = None
-
-
-def main(client, budget_id):
- bidding_strategy = CreateBiddingStrategy(client)
-
- if budget_id is None:
- budget = CreateSharedBudget(client)
- budget_id = budget['budgetId']
-
- CreateCampaignWithBiddingStrategy(client, bidding_strategy['id'], budget_id)
-
-
-def CreateBiddingStrategy(client):
- """Creates a bidding strategy object.
-
- Args:
- client: AdWordsClient the client to run the example with.
-
- Returns:
- dict An object representing a bidding strategy.
- """
- # Initialize appropriate service.
- bidding_strategy_service = client.GetService(
- 'BiddingStrategyService', version='v201409')
-
- # Create a shared bidding strategy.
- shared_bidding_strategy = {
- 'name': 'Maximize Clicks %s' % uuid.uuid4(),
- 'biddingScheme': {
- 'xsi_type': 'TargetSpendBiddingScheme',
- # Optionally set additional bidding scheme parameters.
- 'bidCeiling': {
- 'microAmount': '2000000'
- }
- }
- }
-
- # Create operation.
- operation = {
- 'operator': 'ADD',
- 'operand': shared_bidding_strategy
- }
-
- response = bidding_strategy_service.mutate([operation])
- new_bidding_strategy = response['value'][0]
-
- print ('Shared bidding strategy with name \'%s\' and ID \'%s\' of type \'%s\''
- 'was created.' %
- (new_bidding_strategy['name'], new_bidding_strategy['id'],
- new_bidding_strategy['biddingScheme']['BiddingScheme.Type']))
-
- return new_bidding_strategy
-
-
-def CreateSharedBudget(client):
- """Creates an explicit budget to be used only to create the Campaign.
-
- Args:
- client: AdWordsClient the client to run the example with.
-
- Returns:
- dict An object representing a shared budget.
- """
- # Initialize appropriate service.
- budget_service = client.GetService('BudgetService', version='v201409')
-
- # Create a shared budget
- budget = {
- 'name': 'Shared Interplanetary Budget #%s' % uuid.uuid4(),
- 'period': 'DAILY',
- 'amount': {
- 'microAmount': '2000000'
- },
- 'deliveryMethod': 'STANDARD',
- 'isExplicitlyShared': 'true'
- }
-
- # Create operation.
- operation = {
- 'operator': 'ADD',
- 'operand': budget
- }
-
- response = budget_service.mutate([operation])
- return response['value'][0]
-
-
-def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id):
- """Create a Campaign with a Shared Bidding Strategy.
-
- Args:
- client: AdWordsClient the client to run the example with.
- bidding_strategy_id: string the bidding strategy ID to use.
- budget_id: string the shared budget ID to use.
-
- Returns:
- dict An object representing a campaign.
- """
- # Initialize appropriate service.
- campaign_service = client.GetService('CampaignService', version='v201409')
-
- # Create campaign.
- campaign = {
- 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(),
- 'budget': {
- 'budgetId': budget_id
- },
- 'biddingStrategyConfiguration': {
- 'biddingStrategyId': bidding_strategy_id
- },
- 'advertisingChannelType': 'SEARCH',
- 'networkSetting': {
- 'targetGoogleSearch': 'true',
- 'targetSearchNetwork': 'true',
- 'targetContentNetwork': 'true'
- }
- }
-
- # Create operation.
- operation = {
- 'operator': 'ADD',
- 'operand': campaign
- }
-
- response = campaign_service.mutate([operation])
- new_campaign = response['value'][0]
-
- print ('Campaign with name \'%s\', ID \'%s\' and bidding scheme ID \'%s\' '
- 'was created.' %
- (new_campaign['name'], new_campaign['id'],
- new_campaign['biddingStrategyConfiguration']['biddingStrategyId']))
-
- return new_campaign
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
- main(adwords_client, BUDGET_ID)
diff --git a/examples/adwords/v201409/basic_operations/__init__.py b/examples/adwords/v201409/basic_operations/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/examples/adwords/v201409/basic_operations/add_ad_groups.py b/examples/adwords/v201409/basic_operations/add_ad_groups.py
deleted file mode 100755
index e3fff74d..00000000
--- a/examples/adwords/v201409/basic_operations/add_ad_groups.py
+++ /dev/null
@@ -1,116 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds ad groups to a given campaign.
-
-To get ad groups, run get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README..
-
-Tags: AdGroupService.mutate
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-import uuid
-
-from googleads import adwords
-
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-
-
-def main(client, campaign_id):
- # Initialize appropriate service.
- ad_group_service = client.GetService('AdGroupService', version='v201409')
-
- # Construct operations and add ad groups.
- operations = [{
- 'operator': 'ADD',
- 'operand': {
- 'campaignId': campaign_id,
- 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(),
- 'status': 'ENABLED',
- 'biddingStrategyConfiguration': {
- 'bids': [
- {
- 'xsi_type': 'CpcBid',
- 'bid': {
- 'microAmount': '1000000'
- },
- }
- ]
- },
- 'settings': [
- {
- # Targeting restriction settings - these settings only affect
- # serving for the Display Network.
- 'xsi_type': 'TargetingSetting',
- 'details': [
- # Restricting to serve ads that match your ad group
- # placements. This is equivalent to choosing
- # "Target and bid" in the UI.
- {
- 'xsi_type': 'TargetingSettingDetail',
- 'criterionTypeGroup': 'PLACEMENT',
- 'targetAll': 'false',
- },
- # Using your ad group verticals only for bidding. This is
- # equivalent to choosing "Bid only" in the UI.
- {
- 'xsi_type': 'TargetingSettingDetail',
- 'criterionTypeGroup': 'VERTICAL',
- 'targetAll': 'true',
- },
- ]
- }
- ]
- }
- }, {
- 'operator': 'ADD',
- 'operand': {
- 'campaignId': campaign_id,
- 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(),
- 'status': 'ENABLED',
- 'biddingStrategyConfiguration': {
- 'bids': [
- {
- 'xsi_type': 'CpcBid',
- 'bid': {
- 'microAmount': '1000000'
- }
- }
- ]
- }
- }
- }]
- ad_groups = ad_group_service.mutate(operations)
-
- # Display results.
- for ad_group in ad_groups['value']:
- print ('Ad group with name \'%s\' and id \'%s\' was added.'
- % (ad_group['name'], ad_group['id']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201409/basic_operations/add_campaigns.py b/examples/adwords/v201409/basic_operations/add_campaigns.py
deleted file mode 100755
index 58baacff..00000000
--- a/examples/adwords/v201409/basic_operations/add_campaigns.py
+++ /dev/null
@@ -1,131 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds campaigns.
-
-To get campaigns, run get_campaigns.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignService.mutate
-Tags: BudgetService.mutate
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-import datetime
-import uuid
-
-from googleads import adwords
-
-
-def main(client):
- # Initialize appropriate services.
- campaign_service = client.GetService('CampaignService', version='v201409')
- budget_service = client.GetService('BudgetService', version='v201409')
-
- # Create a budget, which can be shared by multiple campaigns.
- budget = {
- 'name': 'Interplanetary budget #%s' % uuid.uuid4(),
- 'amount': {
- 'microAmount': '50000000'
- },
- 'deliveryMethod': 'STANDARD',
- 'period': 'DAILY'
- }
-
- budget_operations = [{
- 'operator': 'ADD',
- 'operand': budget
- }]
-
- # Add the budget.
- budget_id = budget_service.mutate(budget_operations)['value'][0][
- 'budgetId']
-
- # Construct operations and add campaigns.
- operations = [{
- 'operator': 'ADD',
- 'operand': {
- 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(),
- 'status': 'PAUSED',
- 'advertisingChannelType': 'SEARCH',
- 'biddingStrategyConfiguration': {
- 'biddingStrategyType': 'MANUAL_CPC',
- },
- 'endDate': (datetime.datetime.now() +
- datetime.timedelta(365)).strftime('%Y%m%d'),
- # Note that only the budgetId is required
- 'budget': {
- 'budgetId': budget_id
- },
- 'networkSetting': {
- 'targetGoogleSearch': 'true',
- 'targetSearchNetwork': 'true',
- 'targetContentNetwork': 'false',
- 'targetPartnerSearchNetwork': 'false'
- },
- # Optional fields
- 'startDate': (datetime.datetime.now() +
- datetime.timedelta(1)).strftime('%Y%m%d'),
- 'adServingOptimizationStatus': 'ROTATE',
- 'frequencyCap': {
- 'impressions': '5',
- 'timeUnit': 'DAY',
- 'level': 'ADGROUP'
- },
- 'settings': [
- {
- 'xsi_type': 'GeoTargetTypeSetting',
- 'positiveGeoTargetType': 'DONT_CARE',
- 'negativeGeoTargetType': 'DONT_CARE'
- }
- ]
- }
- }, {
- 'operator': 'ADD',
- 'operand': {
- 'name': 'Interplanetary Cruise banner #%s' % uuid.uuid4(),
- 'status': 'PAUSED',
- 'biddingStrategyConfiguration': {
- 'biddingStrategyType': 'MANUAL_CPC'
- },
- 'endDate': (datetime.datetime.now() +
- datetime.timedelta(365)).strftime('%Y%m%d'),
- # Note that only the budgetId is required
- 'budget': {
- 'budgetId': budget_id
- },
- 'advertisingChannelType': 'DISPLAY'
- }
- }]
- campaigns = campaign_service.mutate(operations)
-
- # Display results.
- for campaign in campaigns['value']:
- print ('Campaign with name \'%s\' and id \'%s\' was added.'
- % (campaign['name'], campaign['id']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201409/basic_operations/add_keywords.py b/examples/adwords/v201409/basic_operations/add_keywords.py
deleted file mode 100755
index 588bde53..00000000
--- a/examples/adwords/v201409/basic_operations/add_keywords.py
+++ /dev/null
@@ -1,97 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds ad group criteria to an ad group.
-
-To get ad groups, run get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupCriterionService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Initialize appropriate service.
- ad_group_criterion_service = client.GetService(
- 'AdGroupCriterionService', version='v201409')
-
- # Construct keyword ad group criterion object.
- keyword1 = {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Keyword',
- 'matchType': 'BROAD',
- 'text': 'mars'
- },
- # These fields are optional.
- 'userStatus': 'PAUSED',
- 'finalUrls': {
- 'urls': ['http://example.com/mars']
- }
- }
-
- keyword2 = {
- 'xsi_type': 'NegativeAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Keyword',
- 'matchType': 'EXACT',
- 'text': 'pluto'
- }
- }
-
- # Construct operations and add ad group criteria.
- operations = [
- {
- 'operator': 'ADD',
- 'operand': keyword1
- },
- {
- 'operator': 'ADD',
- 'operand': keyword2
- }
- ]
- ad_group_criteria = ad_group_criterion_service.mutate(
- operations)['value']
-
- # Display results.
- for criterion in ad_group_criteria:
- print ('Keyword ad group criterion with ad group id \'%s\', criterion id '
- '\'%s\', text \'%s\', and match type \'%s\' was added.'
- % (criterion['adGroupId'], criterion['criterion']['id'],
- criterion['criterion']['text'],
- criterion['criterion']['matchType']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201409/basic_operations/add_text_ads.py b/examples/adwords/v201409/basic_operations/add_text_ads.py
deleted file mode 100755
index 2b5ad425..00000000
--- a/examples/adwords/v201409/basic_operations/add_text_ads.py
+++ /dev/null
@@ -1,98 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds several text ads to a given ad group.
-
-To get ad_group_id, run get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupAdService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Initialize appropriate service.
- ad_group_ad_service = client.GetService('AdGroupAdService', version='v201409')
-
- # Construct operations and add ads.
- # If needed, you could specify an exemption request here, e.g.:
- # 'exemptionRequests': [{
- # # This comes back in a PolicyViolationError.
- # 'key' {
- # 'policyName': '...',
- # 'violatingText': '...'
- # }
- # }]
- operations = [
- {
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'AdGroupAd',
- 'adGroupId': ad_group_id,
- 'ad': {
- 'xsi_type': 'TextAd',
- 'finalUrls': ['http://www.example.com'],
- 'displayUrl': 'example.com',
- 'description1': 'Visit the Red Planet in style.',
- 'description2': 'Low-gravity fun for everyone!',
- 'headline': 'Luxury Cruise to Mars'
- },
- # Optional fields.
- 'status': 'PAUSED'
- }
- },
- {
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'AdGroupAd',
- 'adGroupId': ad_group_id,
- 'ad': {
- 'xsi_type': 'TextAd',
- 'finalUrls': ['http://www.example.com'],
- 'displayUrl': 'example.com',
- 'description1': 'Enjoy your stay at Red Planet.',
- 'description2': 'Buy your tickets now!',
- 'headline': 'Luxury Cruise to Mars'
- }
- }
- }
- ]
- ads = ad_group_ad_service.mutate(operations)
-
- # Display results.
- for ad in ads['value']:
- print ('Ad with id \'%s\' and of type \'%s\' was added.'
- % (ad['ad']['id'], ad['ad']['Ad.Type']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201409/basic_operations/get_ad_groups.py b/examples/adwords/v201409/basic_operations/get_ad_groups.py
deleted file mode 100755
index 3355c3af..00000000
--- a/examples/adwords/v201409/basic_operations/get_ad_groups.py
+++ /dev/null
@@ -1,80 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all ad groups for a given campaign.
-
-To add an ad group, run add_ad_group.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupService.get
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-PAGE_SIZE = 500
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-
-
-def main(client, campaign_id):
- # Initialize appropriate service.
- ad_group_service = client.GetService('AdGroupService', version='v201409')
-
- # Construct selector and get all ad groups.
- offset = 0
- selector = {
- 'fields': ['Id', 'Name', 'Status'],
- 'predicates': [
- {
- 'field': 'CampaignId',
- 'operator': 'EQUALS',
- 'values': [campaign_id]
- }
- ],
- 'paging': {
- 'startIndex': str(offset),
- 'numberResults': str(PAGE_SIZE)
- }
- }
- more_pages = True
- while more_pages:
- page = ad_group_service.get(selector)
-
- # Display results.
- if 'entries' in page:
- for ad_group in page['entries']:
- print ('Ad group with name \'%s\', id \'%s\' and status \'%s\' was '
- 'found.' % (ad_group['name'], ad_group['id'],
- ad_group['status']))
- else:
- print 'No ad groups were found.'
- offset += PAGE_SIZE
- selector['paging']['startIndex'] = str(offset)
- more_pages = offset < int(page['totalNumEntries'])
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201409/basic_operations/get_campaigns.py b/examples/adwords/v201409/basic_operations/get_campaigns.py
deleted file mode 100755
index b931e7b2..00000000
--- a/examples/adwords/v201409/basic_operations/get_campaigns.py
+++ /dev/null
@@ -1,77 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all campaigns.
-
-To add a campaign, run add_campaign.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignService.get
-"""
-
-__author__ = 'Joseph DiLallo'
-
-import logging
-import time
-
-from googleads import adwords
-
-logging.basicConfig(level=logging.INFO)
-logging.getLogger('suds.transport').setLevel(logging.DEBUG)
-
-
-PAGE_SIZE = 100
-
-
-def main(client):
- # Initialize appropriate service.
- campaign_service = client.GetService('CampaignService', version='v201409')
-
- # Construct selector and get all campaigns.
- offset = 0
- selector = {
- 'fields': ['Id', 'Name', 'Status'],
- 'paging': {
- 'startIndex': str(offset),
- 'numberResults': str(PAGE_SIZE)
- }
- }
-
- more_pages = True
- while more_pages:
- page = campaign_service.get(selector)
-
- # Display results.
- if 'entries' in page:
- for campaign in page['entries']:
- print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was '
- 'found.' % (campaign['id'], campaign['name'],
- campaign['status']))
- else:
- print 'No campaigns were found.'
- offset += PAGE_SIZE
- selector['paging']['startIndex'] = str(offset)
- more_pages = offset < int(page['totalNumEntries'])
- time.sleep(1)
-
-
-if __name__ == '__main__':
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
- main(adwords_client)
diff --git a/examples/adwords/v201409/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201409/basic_operations/get_campaigns_with_awql.py
deleted file mode 100755
index e3c38e47..00000000
--- a/examples/adwords/v201409/basic_operations/get_campaigns_with_awql.py
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all campaigns with AWQL.
-
-To add a campaign, run add_campaign.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignService.query
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-import time
-
-from googleads import adwords
-
-
-PAGE_SIZE = 100
-
-
-def main(client):
- # Initialize appropriate service.
- campaign_service = client.GetService('CampaignService', version='v201409')
-
- # Construct query and get all campaigns.
- offset = 0
- query = 'SELECT Id, Name, Status ORDER BY Name'
-
- more_pages = True
- while more_pages:
- page = campaign_service.query(query + ' LIMIT %s, %s' % (offset, PAGE_SIZE))
-
- # Display results.
- if 'entries' in page:
- for campaign in page['entries']:
- print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was '
- 'found.' % (campaign['id'], campaign['name'],
- campaign['status']))
- else:
- print 'No campaigns were found.'
- offset += PAGE_SIZE
- more_pages = offset < int(page['totalNumEntries'])
- time.sleep(1)
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
- main(adwords_client)
diff --git a/examples/adwords/v201409/basic_operations/get_keywords.py b/examples/adwords/v201409/basic_operations/get_keywords.py
deleted file mode 100755
index ee83c7e3..00000000
--- a/examples/adwords/v201409/basic_operations/get_keywords.py
+++ /dev/null
@@ -1,81 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all ad group criteria in an account.
-
-To add keywords, run add_keywords.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupCriterionService.get
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-PAGE_SIZE = 500
-
-
-def main(client):
- # Initialize appropriate service.
- ad_group_criterion_service = client.GetService(
- 'AdGroupCriterionService', version='v201409')
-
- # Construct selector and get all ad group criteria.
- offset = 0
- selector = {
- 'fields': ['AdGroupId', 'Id', 'Text', 'KeywordMatchType', 'PlacementUrl'],
- 'predicates': [{
- 'field': 'CriteriaType',
- 'operator': 'EQUALS',
- 'values': ['KEYWORD']
- }],
- 'paging': {
- 'startIndex': str(offset),
- 'numberResults': str(PAGE_SIZE)
- }
- }
- more_pages = True
- while more_pages:
- page = ad_group_criterion_service.get(selector)
-
- # Display results.
- if 'entries' in page:
- for criterion in page['entries']:
- print ('Keyword ad group criterion with ad group id \'%s\', criterion '
- 'id \'%s\', text \'%s\', and match type \'%s\' was found.'
- % (criterion['adGroupId'], criterion['criterion']['id'],
- criterion['criterion']['text'],
- criterion['criterion']['matchType']))
- else:
- print 'No keywords were found.'
- offset += PAGE_SIZE
- selector['paging']['startIndex'] = str(offset)
- more_pages = offset < int(page['totalNumEntries'])
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201409/basic_operations/get_text_ads.py b/examples/adwords/v201409/basic_operations/get_text_ads.py
deleted file mode 100755
index 10186fb3..00000000
--- a/examples/adwords/v201409/basic_operations/get_text_ads.py
+++ /dev/null
@@ -1,85 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all text ads for a given ad group.
-
-To add an ad, run add_text_ads.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupAdService.get
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-PAGE_SIZE = 500
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Initialize appropriate service.
- ad_group_ad_service = client.GetService('AdGroupAdService', version='v201409')
-
- # Construct selector and get all ads for a given ad group.
- offset = 0
- selector = {
- 'fields': ['Id', 'AdGroupId', 'Status'],
- 'predicates': [
- {
- 'field': 'AdGroupId',
- 'operator': 'EQUALS',
- 'values': [ad_group_id]
- },
- {
- 'field': 'AdType',
- 'operator': 'EQUALS',
- 'values': ['TEXT_AD']
- }
- ],
- 'paging': {
- 'startIndex': str(offset),
- 'numberResults': str(PAGE_SIZE)
- }
- }
- more_pages = True
- while more_pages:
- page = ad_group_ad_service.get(selector)
-
- # Display results.
- if 'entries' in page:
- for ad in page['entries']:
- print ('Ad with id \'%s\', status \'%s\', and of type \'%s\' was found.'
- % (ad['ad']['id'], ad['status'], ad['ad']['Ad.Type']))
- else:
- print 'No ads were found.'
- offset += PAGE_SIZE
- selector['paging']['startIndex'] = str(offset)
- more_pages = offset < int(page['totalNumEntries'])
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201409/basic_operations/pause_ad.py b/examples/adwords/v201409/basic_operations/pause_ad.py
deleted file mode 100755
index e47e1c69..00000000
--- a/examples/adwords/v201409/basic_operations/pause_ad.py
+++ /dev/null
@@ -1,65 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates status for a given ad.
-
-To get ads, run get_text_ads.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupAdService.mutate
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-AD_ID = 'INSERT_AD_ID_HERE'
-
-
-def main(client, ad_group_id, ad_id):
- # Initialize appropriate service.
- ad_group_ad_service = client.GetService('AdGroupAdService', version='v201409')
-
- # Construct operations and update an ad.
- operations = [{
- 'operator': 'SET',
- 'operand': {
- 'adGroupId': ad_group_id,
- 'ad': {
- 'id': ad_id,
- },
- 'status': 'PAUSED'
- }
- }]
- ads = ad_group_ad_service.mutate(operations)
-
- # Display results.
- for ad in ads['value']:
- print 'Ad with id \'%s\' was updated.'% ad['ad']['id']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID, AD_ID)
diff --git a/examples/adwords/v201409/basic_operations/remove_ad.py b/examples/adwords/v201409/basic_operations/remove_ad.py
deleted file mode 100755
index 5003d458..00000000
--- a/examples/adwords/v201409/basic_operations/remove_ad.py
+++ /dev/null
@@ -1,66 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example deletes an ad using the 'REMOVE' operator.
-
-To get ads, run get_text_ads.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupAdService.mutate
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-AD_ID = 'INSERT_AD_ID_HERE'
-
-
-def main(client, ad_group_id, ad_id):
- # Initialize appropriate service.
- ad_group_ad_service = client.GetService('AdGroupAdService', version='v201409')
-
- # Construct operations and delete ad.
- operations = [{
- 'operator': 'REMOVE',
- 'operand': {
- 'xsi_type': 'AdGroupAd',
- 'adGroupId': ad_group_id,
- 'ad': {
- 'id': ad_id
- }
- }
- }]
- result = ad_group_ad_service.mutate(operations)
-
- # Display results.
- for ad in result['value']:
- print ('Ad with id \'%s\' and type \'%s\' was deleted.'
- % (ad['ad']['id'], ad['ad']['Ad.Type']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID, AD_ID)
diff --git a/examples/adwords/v201409/basic_operations/remove_ad_group.py b/examples/adwords/v201409/basic_operations/remove_ad_group.py
deleted file mode 100755
index 8f2b245c..00000000
--- a/examples/adwords/v201409/basic_operations/remove_ad_group.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example deletes an ad group by setting the status to 'REMOVED'.
-
-To get ad groups, run get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupService.mutate
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Initialize appropriate service.
- ad_group_service = client.GetService('AdGroupService', version='v201409')
-
- # Construct operations and delete ad group.
- operations = [{
- 'operator': 'SET',
- 'operand': {
- 'id': ad_group_id,
- 'status': 'REMOVED'
- }
- }]
- result = ad_group_service.mutate(operations)
-
- # Display results.
- for ad_group in result['value']:
- print ('Ad group with name \'%s\' and id \'%s\' was deleted.'
- % (ad_group['name'], ad_group['id']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201409/basic_operations/remove_campaign.py b/examples/adwords/v201409/basic_operations/remove_campaign.py
deleted file mode 100755
index b93021d0..00000000
--- a/examples/adwords/v201409/basic_operations/remove_campaign.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example deletes a campaign by setting the status to 'REMOVED'.
-
-To get campaigns, run get_campaigns.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignService.mutate
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-
-
-def main(client, campaign_id):
- # Initialize appropriate service.
- campaign_service = client.GetService('CampaignService', version='v201409')
-
- # Construct operations and delete campaign.
- operations = [{
- 'operator': 'SET',
- 'operand': {
- 'id': campaign_id,
- 'status': 'REMOVED'
- }
- }]
- result = campaign_service.mutate(operations)
-
- # Display results.
- for campaign in result['value']:
- print ('Campaign with name \'%s\' and id \'%s\' was deleted.'
- % (campaign['name'], campaign['id']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201409/basic_operations/remove_keyword.py b/examples/adwords/v201409/basic_operations/remove_keyword.py
deleted file mode 100755
index 5189f67e..00000000
--- a/examples/adwords/v201409/basic_operations/remove_keyword.py
+++ /dev/null
@@ -1,72 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example deletes an ad group criterion using the 'REMOVE' operator.
-
-To get ad group criteria, run get_keywords.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupCriterionService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-CRITERION_ID = 'INSERT_CRITERION_ID_HERE'
-
-
-def main(client, ad_group_id, criterion_id):
- # Initialize appropriate service.
- ad_group_criterion_service = client.GetService(
- 'AdGroupCriterionService', version='v201409')
-
- # Construct operations and delete ad group criteria.
- operations = [
- {
- 'operator': 'REMOVE',
- 'operand': {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'id': criterion_id
- }
- }
- }
- ]
- result = ad_group_criterion_service.mutate(operations)
-
- # Display results.
- for criterion in result['value']:
- print ('Ad group criterion with ad group id \'%s\', criterion id \'%s\', '
- 'and type \'%s\' was deleted.'
- % (criterion['adGroupId'], criterion['criterion']['id'],
- criterion['criterion']['Criterion.Type']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID, CRITERION_ID)
diff --git a/examples/adwords/v201409/basic_operations/update_ad_group.py b/examples/adwords/v201409/basic_operations/update_ad_group.py
deleted file mode 100755
index 56708e1a..00000000
--- a/examples/adwords/v201409/basic_operations/update_ad_group.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates status for a given ad group.
-
-To get ad groups, run get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupService.mutate
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Initialize appropriate service.
- ad_group_service = client.GetService('AdGroupService', version='v201409')
-
- # Construct operations and update an ad group.
- operations = [{
- 'operator': 'SET',
- 'operand': {
- 'id': ad_group_id,
- 'status': 'PAUSED'
- }
- }]
- ad_groups = ad_group_service.mutate(operations)
-
- # Display results.
- for ad_group in ad_groups['value']:
- print ('Ad group with name \'%s\' and id \'%s\' was updated.'
- % (ad_group['name'], ad_group['id']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201409/basic_operations/update_campaign.py b/examples/adwords/v201409/basic_operations/update_campaign.py
deleted file mode 100755
index 8d8bd43c..00000000
--- a/examples/adwords/v201409/basic_operations/update_campaign.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates a campaign by setting its status to PAUSED.
-
-To get campaigns, run get_campaigns.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignService.mutate
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-
-
-def main(client, campaign_id):
- # Initialize appropriate service.
- campaign_service = client.GetService('CampaignService', version='v201409')
-
- # Construct operations and update campaign.
- operations = [{
- 'operator': 'SET',
- 'operand': {
- 'id': campaign_id,
- 'status': 'PAUSED'
- }
- }]
- campaigns = campaign_service.mutate(operations)
-
- # Display results.
- for campaign in campaigns['value']:
- print ('Campaign with name \'%s\' and id \'%s\' was updated.'
- % (campaign['name'], campaign['id']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201409/basic_operations/update_keyword.py b/examples/adwords/v201409/basic_operations/update_keyword.py
deleted file mode 100755
index 2f5382b1..00000000
--- a/examples/adwords/v201409/basic_operations/update_keyword.py
+++ /dev/null
@@ -1,87 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates the bid of a keyword.
-
-To add a keyword, run add_keywords.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupCriterionService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE'
-
-
-def main(client, ad_group_id, criterion_id):
- # Initialize appropriate service.
- ad_group_criterion_service = client.GetService(
- 'AdGroupCriterionService', version='v201409')
-
- # Construct operations and update bids.
-
- operations = [{
- 'operator': 'SET',
- 'operand': {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'id': criterion_id,
- },
- 'biddingStrategyConfiguration': {
- 'bids': [
- {
- 'xsi_type': 'CpcBid',
- 'bid': {
- 'microAmount': '1000000'
- }
- }
- ]
- }
- }
- }]
- ad_group_criteria = ad_group_criterion_service.mutate(operations)
-
- # Display results.
- if 'value' in ad_group_criteria:
- for criterion in ad_group_criteria['value']:
- if criterion['criterion']['Criterion.Type'] == 'Keyword':
- print ('Ad group criterion with ad group id \'%s\' and criterion id '
- '\'%s\' currently has bids:'
- % (criterion['adGroupId'], criterion['criterion']['id']))
- for bid in criterion['biddingStrategyConfiguration']['bids']:
- print '\tType: \'%s\', value: %s' % (bid['Bids.Type'],
- bid['bid']['microAmount'])
- else:
- print 'No ad group criteria were updated.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID, CRITERION_ID)
diff --git a/examples/adwords/v201409/campaign_management/__init__.py b/examples/adwords/v201409/campaign_management/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/examples/adwords/v201409/campaign_management/add_campaign_labels.py b/examples/adwords/v201409/campaign_management/add_campaign_labels.py
deleted file mode 100755
index 55f5e3ff..00000000
--- a/examples/adwords/v201409/campaign_management/add_campaign_labels.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds a label to multiple campaigns.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignService.mutateLabel
-"""
-
-__author__ = 'Mark Saniscalchi'
-
-from googleads import adwords
-
-
-CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE'
-CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE'
-LABEL_ID = 'INSERT_LABEL_ID_HERE'
-
-
-def main(client, campaign_id1, campaign_id2, label_id):
- # Initialize appropriate service.
- campaign_service = client.GetService('CampaignService', version='v201409')
-
- operations = [
- {
- 'operator': 'ADD',
- 'operand': {
- 'campaignId': campaign_id1,
- 'labelId': label_id,
- }
- },
- {
- 'operator': 'ADD',
- 'operand': {
- 'campaignId': campaign_id2,
- 'labelId': label_id,
- }
- }
- ]
-
- result = campaign_service.mutateLabel(operations)
-
- # Display results.
- for label in result['value']:
- print ('CampaignLabel with campaignId \'%s\' and labelId \'%s\' was added.'
- % (label['campaignId'], label['labelId']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2, LABEL_ID)
diff --git a/examples/adwords/v201409/campaign_management/add_experiment.py b/examples/adwords/v201409/campaign_management/add_experiment.py
deleted file mode 100755
index 564cb7b4..00000000
--- a/examples/adwords/v201409/campaign_management/add_experiment.py
+++ /dev/null
@@ -1,132 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates an experiment.
-
-The created experiment is using a query percentage of 10, which defines what
-fraction of auctions should go to the control split (90%) vs. the experiment
-split (10%), then adds experimental bid changes for an ad group, and adds an
-experiment-only keyword. To get campaigns, run get_campaigns.py. To get ad
-groups, run get_ad_groups.py. To get keywords, run get_keywords.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ExperimentService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-import datetime
-import uuid
-
-from googleads import adwords
-
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, campaign_id, ad_group_id):
- # Initialize appropriate service.
- experiment_service = client.GetService('ExperimentService', version='v201409')
- ad_group_service = client.GetService('AdGroupService', version='v201409')
- ad_group_criterion_service = client.GetService(
- 'AdGroupCriterionService', version='v201409')
-
- # Construct operations and add experiment.
- tomorrow = datetime.datetime.now() + datetime.timedelta(1)
- thirty_days = datetime.datetime.now() + datetime.timedelta(30)
- operations = [{
- 'operator': 'ADD',
- 'operand': {
- 'campaignId': campaign_id,
- 'name': 'Interplanetary Experiment #%s' % uuid.uuid4(),
- 'queryPercentage': '10',
- 'startDateTime': tomorrow.strftime('%Y%m%d %H%M%S'),
- # Optional fields.
- 'status': 'ENABLED',
- 'endDateTime': thirty_days.strftime('%Y%m%d %H%M%S')
- }
- }]
- result = experiment_service.mutate(operations)
-
- # Display results.
- for experiment in result['value']:
- print ('Experiment with name \'%s\' and id \'%s\' was added.'
- % (experiment['name'], experiment['id']))
-
- # Construct operations and update ad group.
- operations = [{
- 'operator': 'SET',
- 'operand': {
- 'id': ad_group_id,
- 'experimentData': {
- 'xsi_type': 'AdGroupExperimentData',
- 'experimentId': experiment['id'],
- 'experimentDeltaStatus': 'MODIFIED',
- 'experimentBidMultipliers': {
- 'xsi_type': 'ManualCPCAdGroupExperimentBidMultipliers',
- 'maxCpcMultiplier': {
- 'multiplier': '0.5'
- }
- }
- }
- }
- }]
- result = ad_group_service.mutate(operations)
-
- # Display results.
- for ad_group in result['value']:
- print ('Ad group with name \'%s\' and id \'%s\' was updated in the '
- 'experiment.' % (ad_group['name'], ad_group['id']))
-
- # Construct operations and add ad group crierion.
- operations = [{
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group['id'],
- 'criterion': {
- 'xsi_type': 'Keyword',
- 'matchType': 'BROAD',
- 'text': 'mars cruise'
- },
- 'experimentData': {
- 'xsi_type': 'BiddableAdGroupCriterionExperimentData',
- 'experimentId': experiment['id'],
- 'experimentDeltaStatus': 'EXPERIMENT_ONLY'
- }
- }
- }]
- result = ad_group_criterion_service.mutate(operations)
-
- # Display results.
- for criterion in result['value']:
- print ('Ad group criterion with ad group id \'%s\' and criterion '
- 'id \'%s\' was added to the experiment.'
- % (criterion['adGroupId'], criterion['criterion']['id']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID, AD_GROUP_ID)
diff --git a/examples/adwords/v201409/campaign_management/add_keywords_in_bulk.py b/examples/adwords/v201409/campaign_management/add_keywords_in_bulk.py
deleted file mode 100755
index f7fe5fa9..00000000
--- a/examples/adwords/v201409/campaign_management/add_keywords_in_bulk.py
+++ /dev/null
@@ -1,141 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code sample illustrates how to perform asynchronous requests.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: MutateJobService.mutate
-Tags: MutateJobService.get
-Tags: MutateJobService.getResult
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-import random
-import re
-import time
-
-from googleads import adwords
-from googleads import errors
-
-
-RETRY_INTERVAL = 10
-RETRIES_COUNT = 30
-KEYWORD_NUMBER = 100
-INDEX_REGEX = r'operations\[(\d+)\].operand'
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Initialize appropriate service.
- mutate_job_service = client.GetService('MutateJobService', version='v201409')
-
- # Create list of all operations for the job.
- operations = []
-
- # Create AdGroupCriterionOperations to add keywords.
- for i in range(KEYWORD_NUMBER):
- keyword = 'mars%d' % i
- if random.randint(1, 10) == 1:
- keyword += '!!!'
- operations.append({
- 'xsi_type': 'AdGroupCriterionOperation',
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Keyword',
- 'matchType': 'BROAD',
- 'text': keyword
- }
- }
- })
-
- # You can specify up to 3 job IDs that must successfully complete before
- # this job can be processed.
- policy = {
- 'prerequisiteJobIds': []
- }
-
- # Call mutate to create a new job.
- response = mutate_job_service.mutate(operations, policy)
-
- if not response:
- raise errors.GoogleAdsError('Failed to submit a job; aborting.')
-
- job_id = response['id']
- print 'Job with ID %s was successfully created.' % job_id
-
- # Create selector to retrieve job status and wait for it to complete.
- selector = {
- 'xsi_type': 'BulkMutateJobSelector',
- 'jobIds': [job_id]
- }
-
- time.sleep(RETRY_INTERVAL)
- # Poll for job status until it's finished.
- print 'Retrieving job status...'
- for i in range(RETRIES_COUNT):
- job_status_response = mutate_job_service.get(selector)
- status = job_status_response[0]['status']
- if status in ('COMPLETED', 'FAILED'):
- break
- print ('[%d] Current status is \'%s\', waiting %d seconds to retry...' %
- (i, status, RETRY_INTERVAL))
- time.sleep(RETRY_INTERVAL)
-
- if status == 'FAILED':
- raise errors.GoogleAdsError('Job failed with reason: \'%s\'' %
- job_status_response[0]['failure_reason'])
- if status in ('PROCESSING', 'PENDING'):
- raise errors.GoogleAdsError('Job did not complete within %d seconds' %
- (RETRY_INTERVAL * (RETRIES_COUNT - 1)))
-
- # Status must be COMPLETED.
- # Get the job result. Here we re-use the same selector.
- result_response = mutate_job_service.getResult(selector)
-
- # Output results.
- index = 0
- for result in result_response['SimpleMutateResult']['results']:
- if 'PlaceHolder' in result:
- print 'Operation [%d] - FAILED' % index
- else:
- print 'Operation [%d] - SUCCEEDED' % index
- index += 1
-
- # Output errors
- for error in result_response['SimpleMutateResult']['errors']:
- index = int(re.search(INDEX_REGEX, error['fieldPath']).group(1))
- reason = error['reason']
- keyword = operations[index]['operand']['criterion']['text']
- print ('ERROR - keyword \'%s\' failed due to \'%s\'' %
- (keyword, reason))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201409/campaign_management/add_location_extension.py b/examples/adwords/v201409/campaign_management/add_location_extension.py
deleted file mode 100755
index 17c6dfa9..00000000
--- a/examples/adwords/v201409/campaign_management/add_location_extension.py
+++ /dev/null
@@ -1,114 +0,0 @@
-#!/usr/bin/python
-# -*- coding: UTF-8 -*-
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds a campaign ad extension to a given campaign.
-
-To get campaigns, run get_campaigns.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: GeoLocationService.get, CampaignAdExtensionService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-
-
-def main(client, campaign_id):
- # Initialize appropriate service.
- geo_location_service = client.GetService(
- 'GeoLocationService', version='v201409')
- campaign_ad_extension_service = client.GetService(
- 'CampaignAdExtensionService', version='v201409')
-
- # Construct selector and get geo location info for given addresses.
- selector = {
- 'addresses': [
- {
- 'streetAddress': '1600 Amphitheatre Parkway',
- 'cityName': 'Mountain View',
- 'provinceCode': 'US-CA',
- 'provinceName': 'California',
- 'postalCode': '94043',
- 'countryCode': 'US'
- },
- {
- 'streetAddress': u'38 avenue de l\'Opéra',
- 'cityName': 'Paris',
- 'postalCode': '75002',
- 'countryCode': 'FR'
- }
- ]
- }
- geo_locations = geo_location_service.get(selector)
-
- # Construct operations and add campaign ad extension.
- operations = [
- {
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'CampaignAdExtension',
- 'campaignId': campaign_id,
- 'adExtension': {
- 'xsi_type': 'LocationExtension',
- 'address': geo_locations[0]['address'],
- 'geoPoint': geo_locations[0]['geoPoint'],
- 'encodedLocation': geo_locations[0]['encodedLocation'],
- 'source': 'ADWORDS_FRONTEND',
- # Optional fields.
- 'companyName': 'ACME Inc.',
- 'phoneNumber': '(650) 253-0000'
- }
- }
- },
- {
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'CampaignAdExtension',
- 'campaignId': campaign_id,
- 'adExtension': {
- 'xsi_type': 'LocationExtension',
- 'address': geo_locations[1]['address'],
- 'geoPoint': geo_locations[1]['geoPoint'],
- 'encodedLocation': geo_locations[1]['encodedLocation'],
- 'source': 'ADWORDS_FRONTEND'
- }
- }
- }
- ]
- ad_extensions = campaign_ad_extension_service.mutate(operations)
-
- # Display results.
- for ad_extension in ad_extensions['value']:
- print ('Campaign ad extension with id \'%s\' and status \'%s\' was added.'
- % (ad_extension['adExtension']['id'], ad_extension['status']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201409/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201409/campaign_management/get_all_disapproved_ads.py
deleted file mode 100755
index ce70f54f..00000000
--- a/examples/adwords/v201409/campaign_management/get_all_disapproved_ads.py
+++ /dev/null
@@ -1,78 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all disapproved ads for a given campaign.
-
-To add an ad, run add_ads.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupAdService.get
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-
-
-def main(client, campaign_id):
- # Initialize appropriate service.
- ad_group_ad_service = client.GetService('AdGroupAdService', version='v201409')
-
- # Construct selector and get all ads for a given ad group.
- selector = {
- 'fields': ['Id', 'AdGroupAdDisapprovalReasons'],
- 'predicates': [
- {
- 'field': 'CampaignId',
- 'operator': 'EQUALS',
- 'values': [campaign_id]
- },
- {
- 'field': 'AdGroupCreativeApprovalStatus',
- 'operator': 'IN',
- 'values': ['DISAPPROVED']
- }
- ]
- }
- ads = ad_group_ad_service.get(selector)
-
- # Display results.
- if 'entries' in ads:
- for ad in ads['entries']:
- print ('Ad with id \'%s\' was disapproved for the following reasons: '
- % (ad['ad']['id']))
- if ad['ad'].get('disapprovalReasons'):
- for reason in ad['ad']['disapprovalReasons']:
- print '\t%s' % reason
- else:
- print '\tReason not provided.'
- else:
- print 'No disapproved ads were found.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201409/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201409/campaign_management/get_all_disapproved_ads_with_awql.py
deleted file mode 100755
index 4937b293..00000000
--- a/examples/adwords/v201409/campaign_management/get_all_disapproved_ads_with_awql.py
+++ /dev/null
@@ -1,67 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all disapproved ads for a given campaign with AWQL.
-
-To add an ad, run add_ads.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupAdService.get
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-
-
-def main(client, campaign_id):
- # Initialize appropriate service.
- ad_group_ad_service = client.GetService('AdGroupAdService', version='v201409')
-
- # Construct query and get all ads for a given campaign.
- query = ('SELECT Id, AdGroupAdDisapprovalReasons '
- 'WHERE CampaignId = %s AND '
- 'AdGroupCreativeApprovalStatus = DISAPPROVED '
- 'ORDER BY Id' % campaign_id)
- ads = ad_group_ad_service.query(query)
-
- # Display results.
- if 'entries' in ads:
- for ad in ads['entries']:
- print ('Ad with id \'%s\' was disapproved for the following reasons: '
- % (ad['ad']['id']))
- if ad['ad'].get('disapprovalReasons'):
- for reason in ad['ad']['disapprovalReasons']:
- print '\t%s' % reason
- else:
- print '\tReason not provided.'
- else:
- print 'No disapproved ads were found.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201409/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201409/campaign_management/get_campaigns_by_label.py
deleted file mode 100755
index 151c7836..00000000
--- a/examples/adwords/v201409/campaign_management/get_campaigns_by_label.py
+++ /dev/null
@@ -1,88 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all campaigns with a specific label.
-
-To add a label to campaigns, run add_campaign_labels.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignService.get
-"""
-
-__author__ = 'Mark Saniscalchi'
-
-import time
-
-from googleads import adwords
-
-
-LABEL_ID = 'INSERT_LABEL_ID_HERE'
-PAGE_SIZE = 100
-
-
-def main(client, label_id):
- # Initialize appropriate service.
- campaign_service = client.GetService('CampaignService', version='v201409')
-
- offset = 0
- selector = {
- 'fields': ['Id', 'Name', 'Labels'],
- # Labels filtering is performed by ID. You can use CONTAINS_ANY to select
- # campaigns with any of the label IDs, CONTAINS_ALL to select campaigns
- # with all of the label IDs, or CONTAINS_NONE to select campaigns with
- # none of the label IDs.
- 'ordering': {
- 'field': 'Name',
- 'sortOrder': 'ASCENDING'
- },
- 'paging': {
- 'startIndex': str(offset),
- 'numberResults': str(PAGE_SIZE)
- },
- 'predicates': {
- 'field': 'Labels',
- 'operator': 'CONTAINS_ANY',
- 'values': [label_id]
- }
- }
-
- more_pages = True
- while more_pages:
- page = campaign_service.get(selector)
-
- # Display results.
- if 'entries' in page:
- for campaign in page['entries']:
- print ('Campaign found with Id \'%s\', name \'%s\', and labels: %s'
- % (campaign['id'], campaign['name'], campaign['labels']))
- else:
- print 'No campaigns were found.'
-
- offset += PAGE_SIZE
- selector['paging']['startIndex'] = str(offset)
- more_pages = offset < int(page['totalNumEntries'])
- time.sleep(1)
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, LABEL_ID)
diff --git a/examples/adwords/v201409/campaign_management/promote_experiment.py b/examples/adwords/v201409/campaign_management/promote_experiment.py
deleted file mode 100755
index cc7441f0..00000000
--- a/examples/adwords/v201409/campaign_management/promote_experiment.py
+++ /dev/null
@@ -1,65 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example promotes an experiment.
-
-Promoting an experiment permanently applies all the experimental changes made to
-its related ad groups, criteria and ads. To add an experiment, run
-add_experiment.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ExperimentService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-EXPERIMENT_ID = 'INSERT_EXPERIMENT_ID_HERE'
-
-
-def main(client, experiment_id):
- # Initialize appropriate service.
- experiment_service = client.GetService('ExperimentService', version='v201409')
-
- # Construct operations and promote experiment.
- operations = [{
- 'operator': 'SET',
- 'operand': {
- 'id': experiment_id,
- 'status': 'PROMOTED'
- }
- }]
- result = experiment_service.mutate(operations)
-
- # Display results.
- for experiment in result['value']:
- print ('Experiment with name \'%s\' and id \'%s\' was promoted.'
- % (experiment['name'], experiment['id']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, EXPERIMENT_ID)
diff --git a/examples/adwords/v201409/campaign_management/set_ad_parameters.py b/examples/adwords/v201409/campaign_management/set_ad_parameters.py
deleted file mode 100755
index 2d250429..00000000
--- a/examples/adwords/v201409/campaign_management/set_ad_parameters.py
+++ /dev/null
@@ -1,107 +0,0 @@
-#!/usr/bin/python
-# -*- coding: utf-8 -*-
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds a text ad with ad parameters.
-
-To get ad groups, run get_ad_groups.py. To get keywords, run add_keywords.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupAdService.mutate, AdParamService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE'
-
-
-def main(client, ad_group_id, criterion_id):
- # Initialize appropriate service.
- ad_group_ad_service = client.GetService('AdGroupAdService', version='v201409')
- ad_param_service = client.GetService('AdParamService', version='v201409')
-
- # Construct operations for adding text ad object and add to an ad group.
- operations = [{
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'AdGroupAd',
- 'adGroupId': ad_group_id,
- 'ad': {
- 'xsi_type': 'TextAd',
- 'finalUrls': {
- 'urls': ['http://www.example.com']
- },
- 'displayUrl': 'example.com',
- 'description1': 'Low-gravity fun for {param1:cheap}.',
- 'description2': 'Only {param2:a few} seats left!',
- 'headline': 'Luxury Mars Cruises'
- },
- 'status': 'ENABLED'
- }
- }]
- ads = ad_group_ad_service.mutate(operations)['value']
-
- # Display results.
- for ad in ads:
- print ('Text ad with id \'%s\' was successfully added to an ad group with '
- 'id \'%s\'.' % (ad['adGroupId'], ad['ad']['id']))
-
- # Construct operations for setting ad parameters.
- operations = [
- {
- 'operator': 'SET',
- 'operand': {
- 'adGroupId': ad_group_id,
- 'criterionId': criterion_id,
- 'insertionText': u'£100',
- 'paramIndex': '1'
- }
- },
- {
- 'operator': 'SET',
- 'operand': {
- 'adGroupId': ad_group_id,
- 'criterionId': criterion_id,
- 'insertionText': '50',
- 'paramIndex': '2'
- }
- }
- ]
- ad_params = ad_param_service.mutate(operations)
-
- # Display results.
- for ad_param in ad_params:
- print ('Ad parameter with text \'%s\' was successfully set for criterion '
- 'with id \'%s\' and ad group id \'%s\'.'
- % (ad_param['insertionText'], ad_param['criterionId'],
- ad_param['adGroupId']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID, CRITERION_ID)
diff --git a/examples/adwords/v201409/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201409/campaign_management/set_criterion_bid_modifier.py
deleted file mode 100755
index dabdb07b..00000000
--- a/examples/adwords/v201409/campaign_management/set_criterion_bid_modifier.py
+++ /dev/null
@@ -1,82 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example sets a bid modifier for the mobile platform on given campaign.
-
-To get campaigns, run get_campaigns.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignCriterionService.mutate
-"""
-
-__author__ = ('api.dklimkin@gmail.com (Danial Klimkin)',
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-BID_MODIFIER = '1.5'
-
-
-def main(client, campaign_id, bid_modifier):
- # Initialize appropriate service.
- campaign_criterion_service = client.GetService(
- 'CampaignCriterionService', version='v201409')
-
- # Create mobile platform.The ID can be found in the documentation.
- # https://developers.google.com/adwords/api/docs/appendix/platforms
- mobile = {
- 'xsi_type': 'Platform',
- 'id': '30001'
- }
-
- # Create campaign criterion with modified bid.
- campaign_criterion = {
- 'campaignId': campaign_id,
- 'criterion': mobile,
- 'bidModifier': bid_modifier
- }
-
- # Create operations.
- operations = [
- {
- 'operator': 'SET',
- 'operand': campaign_criterion
- }
- ]
-
- # Make the mutate request.
- result = campaign_criterion_service.mutate(operations)
-
- # Display the resulting campaign criteria.
- for campaign_criterion in result['value']:
- print ('Campaign criterion with campaign id \'%s\' and criterion id \'%s\' '
- 'was updated with bid modifier \'%s\'.'
- % (campaign_criterion['campaignId'],
- campaign_criterion['criterion']['id'],
- campaign_criterion['bidModifier']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID, BID_MODIFIER)
diff --git a/examples/adwords/v201409/campaign_management/validate_text_ad.py b/examples/adwords/v201409/campaign_management/validate_text_ad.py
deleted file mode 100755
index f3b67794..00000000
--- a/examples/adwords/v201409/campaign_management/validate_text_ad.py
+++ /dev/null
@@ -1,91 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example shows how to use validateOnly SOAP header.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-import suds
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Initialize appropriate service with validate only flag enabled.
- client.validate_only = True
- ad_group_ad_service = client.GetService('AdGroupAdService', version='v201409')
-
- # Construct operations to add a text ad.
- operations = [{
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'AdGroupAd',
- 'adGroupId': ad_group_id,
- 'ad': {
- 'xsi_type': 'TextAd',
- 'finalUrls': {
- 'urls': ['http://www.example.com']
- },
- 'displayUrl': 'example.com',
- 'description1': 'Visit the Red Planet in style.',
- 'description2': 'Low-gravity fun for everyone!',
- 'headline': 'Luxury Cruise to Mars'
- }
- }
- }]
- ad_group_ad_service.mutate(operations)
- # No error means the request is valid.
-
- # Now let's check an invalid ad using a very long line to trigger an error.
- operations = [{
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'AdGroupAd',
- 'adGroupId': ad_group_id,
- 'ad': {
- 'xsi_type': 'TextAd',
- 'url': 'http://www.example.com',
- 'displayUrl': 'example.com',
- 'description1': 'Visit the Red Planet in style.',
- 'description2': 'Low-gravity fun for all astronauts in orbit',
- 'headline': 'Luxury Cruise to Mars'
- }
- }
- }]
- try:
- ad_group_ad_service.mutate(operations)
- except suds.WebFault, e:
- print 'Validation correctly failed with \'%s\'.' % str(e)
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201409/error_handling/__init__.py b/examples/adwords/v201409/error_handling/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/examples/adwords/v201409/error_handling/handle_partial_failures.py b/examples/adwords/v201409/error_handling/handle_partial_failures.py
deleted file mode 100755
index a3c3c246..00000000
--- a/examples/adwords/v201409/error_handling/handle_partial_failures.py
+++ /dev/null
@@ -1,124 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example demonstrates how to handle partial failures.
-
-To get ad groups, run get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupCriterionService.mutate
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-import re
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Enable partial failure.
- client.partial_failure = True
-
- # Initialize appropriate service.
- ad_group_criterion_service = client.GetService(
- 'AdGroupCriterionService', version='v201409')
-
- # Construct keyword ad group criteria objects.
- keywords = [
- {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Keyword',
- 'matchType': 'BROAD',
- 'text': 'mars cruise'
- }
- },
- {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Keyword',
- 'matchType': 'BROAD',
- 'text': r'inv\@lid cruise'
- }
- },
- {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Keyword',
- 'matchType': 'BROAD',
- 'text': 'venus cruise'
- }
- },
- {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Keyword',
- 'matchType': 'BROAD',
- 'text': r'b\(a\)d keyword cruise'
- }
- }
- ]
-
- # Construct operations and add ad group criteria.
- operations = []
- for keyword in keywords:
- operations.append(
- {
- 'operator': 'ADD',
- 'operand': keyword
- })
- result = ad_group_criterion_service.mutate(operations)
-
- # Display results.
- for criterion in result['value']:
- if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion':
- print ('Added keyword ad group criterion with ad group id \'%s\', '
- 'criterion id \'%s\', text \'%s\', and match type \'%s\' was '
- 'added.'
- % (criterion['adGroupId'], criterion['criterion']['id'],
- criterion['criterion']['text'],
- criterion['criterion']['matchType']))
-
- for error in result['partialFailureErrors']:
- index = re.findall(r'operations\[(.*)\]\.', error['fieldPath'])
- if index:
- print ('Keyword ad group criterion with ad group id \'%s\' and text '
- '\'%s\' triggered a failure for the following reason: \'%s\'.'
- % (keywords[int(index[0])]['adGroupId'],
- keywords[int(index[0])]['criterion']['text'],
- error['errorString']))
- else:
- print 'The following failure has occurred: \'%s\'.' % error['errorString']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201409/error_handling/handle_policy_violation_error.py b/examples/adwords/v201409/error_handling/handle_policy_violation_error.py
deleted file mode 100755
index 16aa6e22..00000000
--- a/examples/adwords/v201409/error_handling/handle_policy_violation_error.py
+++ /dev/null
@@ -1,117 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example demonstrates how to handle policy violation errors.
-
-To get ad groups, run get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupAdService.mutate
-"""
-
-__author__ = 'Joseph DiLallo'
-
-import re
-
-import suds
-
-from googleads import adwords
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- ad_group_ad_service = client.GetService('AdGroupAdService', 'v201409')
-
- # Create text ad.
- text_ad_operation = {
- 'operator': 'ADD',
- 'operand': {
- 'adGroupId': ad_group_id,
- 'ad': {
- # The 'xsi_type' field allows you to specify the xsi:type of the
- # object being created. It's only necessary when you must provide
- # an explicit type that the client library can't infer.
- 'xsi_type': 'TextAd',
- 'headline': 'Mars Cruise!!!',
- 'description1': 'Visit the Red Planet in style.',
- 'description2': 'Low-gravity fun for everyone!',
- 'finalUrls': ['http://www.example.com'],
- 'displayUrl': 'www.example.com',
- }
- }
- }
-
- operations = [text_ad_operation]
-
- # Validate the ad.
- try:
- # Enable "validate only" to check for errors.
- client.validate_only = True
- ad_group_ad_service.mutate(operations)
- print 'Validation successful, no errors returned.'
- except suds.WebFault, e:
- for error in e.fault.detail.ApiExceptionFault.errors:
- if error['ApiError.Type'] == 'PolicyViolationError':
- operation_index = re.findall(r'operations\[(.*)\]\.',
- error['fieldPath'])
- if operation_index:
- operation = operations[int(operation_index[0])]
- print ('Ad with headline \'%s\' violated %s policy \'%s\'.' %
- (operation['operand']['ad']['headline'],
- 'exemptable' if error['isExemptable'] else 'non-exemptable',
- error['externalPolicyName']))
- if error['isExemptable'].lower() == 'true':
- # Add exemption request to the operation.
- print ('Adding exemption request for policy name \'%s\' on text '
- '\'%s\'.' %
- (error['key']['policyName'], error['key']['violatingText']))
- if 'exemptionRequests' not in operation:
- operation['exemptionRequests'] = []
- operation['exemptionRequests'].append({
- 'key': error['key']
- })
- else:
- # Remove non-exemptable operation
- print 'Removing the operation from the request.'
- operations.delete(operation)
- else:
- # Non-policy error returned, re-throw exception.
- raise e
-
- # Add these ads. Disable "validate only" so the ads will get created.
- client.validate_only = False
- if operations:
- response = ad_group_ad_service.mutate(operations)
- if response and response['value']:
- ads = response['value']
- print 'Added %s ad(s) to ad group %s.' % (len(ads), ad_group_id)
- for ad in ads:
- print (' Ad id is %s, type is %s and status is \'%s\'.' %
- (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status']))
- else:
- print 'No ads were added.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201409/extensions/__init__.py b/examples/adwords/v201409/extensions/__init__.py
deleted file mode 100644
index b4d63e00..00000000
--- a/examples/adwords/v201409/extensions/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Extension examples."""
diff --git a/examples/adwords/v201409/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201409/extensions/add_google_my_business_location_extensions.py
deleted file mode 100755
index d3408644..00000000
--- a/examples/adwords/v201409/extensions/add_google_my_business_location_extensions.py
+++ /dev/null
@@ -1,158 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-
-"""Adds a feed that syncs feed items from a Google My Business (GMB) account.
-
-This example associates the feed with a customer.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomerFeedService.mutate, FeedService.mutate
-"""
-
-__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)',
- 'Joseph DiLallo')
-
-import time
-import uuid
-
-# Import appropriate modules from the client library.
-import suds
-
-from googleads import adwords
-from googleads import errors
-
-GMB_EMAIL_ADDRESS = 'INSERT_GMB_EMAIL_ADDRESS_HERE'
-# To obtain an access token for your Places account, you can run the
-# generate_refresh_token.py example and manually replace the scope with
-# "https://www.google.com/local/add".
-GMB_ACCESS_TOKEN = 'INSERT_GMB_OAUTH_ACCESS_TOKEN_HERE'
-
-# If the gmb_email_address above is for a GMB manager instead of
-# the GMB account owner, then set business_account_identifier to the
-# +Page ID of a location for which the manager has access. See the
-# location extensions guide at
-# https://developers.google.com/adwords/api/docs/guides/feed-services-locations
-# for details.
-BUSINESS_ACCOUNT_IDENTIFIER = None
-
-# The placeholder type for location extensions.
-# See the Placeholder reference page for a list of all the placeholder types
-# and fields:
-# https://developers.google.com/adwords/api/docs/appendix/placeholders
-PLACEHOLDER_LOCATION = 7
-
-# The maximum number of CustomerFeed ADD operation attempts to make before
-# throwing an exception.
-MAX_CUSTOMER_FEED_ADD_ATTEMPTS = 10
-
-
-def main(client, gmb_email_address, gmb_access_token,
- business_account_identifier=None):
- # Create a feed that will sync to the Google Places account specified by
- # gmb_email_address. Do not add FeedAttributes to this object,
- # as AdWords will add them automatically because this will be a
- # system generated feed.
- feed = {
- 'name': 'GMB feed #%s' % uuid.uuid4(),
- 'systemFeedGenerationData': {
- 'xsi_type': 'PlacesLocationFeedData',
- 'oAuthInfo': {
- 'httpMethod': 'GET',
- 'httpRequestUrl': 'https://www.googleapis.com/auth/adwords',
- 'httpAuthorizationHeader': 'Bearer %s' % gmb_access_token
- },
- 'emailAddress': gmb_email_address,
- },
- # Since this feed's feed items will be managed by AdWords, you must set
- # its origin to ADWORDS.
- 'origin': 'ADWORDS'
- }
-
- # Only include the business_account_identifier if it's specified.
- if business_account_identifier:
- feed['systemFeedGenerationData']['businessAccountIdentifier'] = (
- business_account_identifier
- )
-
- # Create an operation to add the feed.
- gmb_operations = [{
- 'operator': 'ADD',
- 'operand': feed
- }]
-
- gmb_response = client.GetService('FeedService', version='v201409').mutate(
- gmb_operations)
- added_feed = gmb_response['value'][0]
- print 'Added GMB feed with ID: %d\n' % added_feed['id']
-
- # Add a CustomerFeed that associates the feed with this customer for the
- # LOCATION placeholder type.
- customer_feed = {
- 'feedId': added_feed['id'],
- 'placeholderTypes': [PLACEHOLDER_LOCATION],
- # Create a matching function that will always evaluate to True.
- 'matchingFunction': {
- 'operator': 'IDENTITY',
- 'lhsOperand': {
- 'xsi_type': 'ConstantOperand',
- 'type': 'BOOLEAN',
- 'booleanValue': True
- }
- }
- }
-
- customer_feed_operation = {
- 'xsi_type': 'CustomerFeedOperation',
- 'operator': 'ADD',
- 'operand': customer_feed
- }
-
- customer_feed_service = client.GetService(
- 'CustomerFeedService', version='v201409')
- added_customer_feed = None
-
- i = 0
- while i < MAX_CUSTOMER_FEED_ADD_ATTEMPTS and added_customer_feed is None:
- try:
- added_customer_feed = customer_feed_service.mutate([
- customer_feed_operation])['value'][0]
- except suds.WebFault:
- # Wait using exponential backoff policy
- sleep_seconds = 2 ** i
- print ('Attempt %d to add the CustomerFeed was not successful.'
- 'Waiting %d seconds before trying again.\n' % (i, sleep_seconds))
-
- time.sleep(sleep_seconds)
- i += 1
-
- if added_customer_feed is None:
- raise errors.GoogleAdsError(
- 'Could not create the CustomerFeed after %s attempts. Please retry the '
- 'CustomerFeed ADD operation later.' % MAX_CUSTOMER_FEED_ADD_ATTEMPTS)
-
- print ('Added CustomerFeed for feed ID %d and placeholder type %d\n'
- % (added_customer_feed['id'], added_customer_feed['placeholderTypes']))
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
- main(adwords_client, GMB_EMAIL_ADDRESS, GMB_ACCESS_TOKEN,
- BUSINESS_ACCOUNT_IDENTIFIER)
diff --git a/examples/adwords/v201409/extensions/add_site_links.py b/examples/adwords/v201409/extensions/add_site_links.py
deleted file mode 100755
index e1c6079e..00000000
--- a/examples/adwords/v201409/extensions/add_site_links.py
+++ /dev/null
@@ -1,128 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Adds sitelinks to a campaign using the CampaignExtensionSettingService.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignExtensionSettingService.mutate, CustomerService.get
-Api: AdWordsOnly
-"""
-
-__author__ = 'Mark Saniscalchi'
-
-from datetime import datetime
-
-
-from googleads import adwords
-from googleads import errors
-from pytz import timezone
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-
-
-def main(client, campaign_id):
- # Initialize appropriate services.
- campaign_extension_setting_service = client.GetService(
- 'CampaignExtensionSettingService', version='v201409')
- customer_service = client.GetService('CustomerService', version='v201409')
-
- customer_tz = timezone(customer_service.get()['dateTimeZone'])
- time_fmt = '%s %s' % ('%Y%m%d %H%M%S', customer_tz)
-
- # Create the sitelinks
- sitelink1 = {
- 'xsi_type': 'SitelinkFeedItem',
- 'sitelinkText': 'Store Hours',
- 'sitelinkUrl': 'http://www.example.com/storehours'
- }
-
- # Show the Thanksgiving specials link only from 20 - 27 Nov.
- sitelink2 = {
- 'xsi_type': 'SitelinkFeedItem',
- 'sitelinkText': 'Thanksgiving Specials',
- 'sitelinkUrl': 'http://www.example.com/thanksgiving',
- # The time zone of the start and end date/times must match the time zone
- # of the customer.
- 'startTime': datetime(datetime.now().year, 11, 20, 0, 0, 0, 0,
- customer_tz).strftime(time_fmt),
- 'endTime': datetime(datetime.now().year, 11, 27, 23, 59, 59, 59,
- customer_tz).strftime(time_fmt)
- }
-
- # Show the wifi details primarily for high end mobile users.
- sitelink3 = {
- 'xsi_type': 'SitelinkFeedItem',
- 'sitelinkText': 'Wifi Available',
- 'sitelinkUrl': 'http://www.example.com/mobile/wifi',
- # See https://developers.google.com/adwords/api/docs/appendix/platforms
- # for device criteria IDs.
- 'devicePreference': {'devicePreference': '30001'}
- }
-
- # Show the happy hours link only during Mon - Fri 6PM to 9PM.
- sitelink4 = {
- 'xsi_type': 'SitelinkFeedItem',
- 'sitelinkText': 'Happy hours',
- 'sitelinkUrl': 'http://www.example.com/happyhours',
- 'scheduling': {
- 'feedItemSchedules': [
- {
- 'dayOfWeek': day,
- 'startHour': '18',
- 'startMinute': 'ZERO',
- 'endHour': '21',
- 'endMinute': 'ZERO'
- } for day in ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY',
- 'FRIDAY']
- ]
- }
- }
-
- # Create your Campaign Extension Settings. This associates the sitelinks
- # to your campaign.
- campaign_extension_setting = {
- 'campaignId': campaign_id,
- 'extensionType': 'SITELINK',
- 'extensionSetting': {
- 'extensions': [sitelink1, sitelink2, sitelink3, sitelink4]
- }
- }
-
- operation = {
- 'operator': 'ADD',
- 'operand': campaign_extension_setting
- }
-
- # Add the extensions.
- response = campaign_extension_setting_service.mutate([operation])
-
- if 'value' in response:
- print ('Extension setting with type "%s" was added to campaignId "%d".' %
- (response['value'][0]['extensionType'],
- response['value'][0]['campaignId']))
- else:
- raise errors.GoogleAdsError('No extension settings were added.')
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201409/extensions/add_site_links_using_feeds.py b/examples/adwords/v201409/extensions/add_site_links_using_feeds.py
deleted file mode 100755
index 7049faaa..00000000
--- a/examples/adwords/v201409/extensions/add_site_links_using_feeds.py
+++ /dev/null
@@ -1,265 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds a sitelinks feed and associates it with a campaign.
-
-To add sitelinks using the simpler ExtensionSetting services, see:
-add_sitelinks.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignFeedService.mutate, FeedItemService.mutate
-Tags: FeedMappingService.mutate, FeedService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = 'Joseph DiLallo'
-
-import uuid
-
-from googleads import adwords
-from googleads import errors
-
-# See the Placeholder reference page for a list of all the placeholder types and
-# fields.
-# https://developers.google.com/adwords/api/docs/appendix/placeholders.html
-PLACEHOLDER_SITELINKS = '1'
-PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = '1'
-PLACEHOLDER_FIELD_SITELINK_FINAL_URL = '5'
-PLACEHOLDER_FIELD_LINE_1_TEXT = '3'
-PLACEHOLDER_FIELD_LINE_2_TEXT = '4'
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-
-
-def main(client, campaign_id):
- # Initialize appropriate service.
- feed_service = client.GetService('FeedService', version='v201409')
- feed_item_service = client.GetService('FeedItemService', version='v201409')
- feed_mapping_service = client.GetService(
- 'FeedMappingService', version='v201409')
- campaign_feed_service = client.GetService(
- 'CampaignFeedService', version='v201409')
-
- sitelinks_data = {}
-
- # Create site links feed first.
- site_links_feed = {
- 'name': 'Feed For Site Links #%s' % uuid.uuid4(),
- 'attributes': [
- {'type': 'STRING', 'name': 'Link Text'},
- {'type': 'URL_LIST', 'name': 'Link Final URLs'},
- {'type': 'STRING', 'name': 'Line 1 Description'},
- {'type': 'STRING', 'name': 'Line 2 Description'}
- ]
- }
-
- response = feed_service.mutate([
- {'operator': 'ADD', 'operand': site_links_feed}
- ])
-
- if 'value' in response:
- feed = response['value'][0]
- link_text_feed_attribute_id = feed['attributes'][0]['id']
- final_url_feed_attribute_id = feed['attributes'][1]['id']
- line_1_feed_attribute_id = feed['attributes'][2]['id']
- line_2_feed_attribute_id = feed['attributes'][3]['id']
- print ('Feed with name \'%s\' and ID \'%s\' was added with' %
- (feed['name'], feed['id']))
- print ('\tText attribute ID \'%s\' and Final URL attribute ID \'%s\'.' %
- (link_text_feed_attribute_id, final_url_feed_attribute_id))
- print ('\tLine 1 attribute ID \'%s\' and Line 2 attribute ID \'%s\'.' %
- (line_1_feed_attribute_id, line_2_feed_attribute_id))
- sitelinks_data['feedId'] = feed['id']
- sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id
- sitelinks_data['finalUrlFeedId'] = final_url_feed_attribute_id
- sitelinks_data['line1FeedId'] = line_1_feed_attribute_id
- sitelinks_data['line2FeedId'] = line_2_feed_attribute_id
- else:
- raise errors.GoogleAdsError('No feeds were added.')
-
- # Create site links feed items.
- items_data = [
- {'text': 'Home', 'url': 'http://www.example.com',
- 'line1': 'Home line 1', 'line2': 'Home line 2'},
- {'text': 'Stores', 'url': 'http://www.example.com/stores',
- 'line1': 'Stores line 1', 'line2': 'Stores line 2'},
- {'text': 'On Sale', 'url': 'http://www.example.com/sale',
- 'line1': 'On Sale line 1', 'line2': 'On Sale line 2'},
- {'text': 'Support', 'url': 'http://www.example.com/support',
- 'line1': 'Support line 1', 'line2': 'Support line 2'},
- {'text': 'Products', 'url': 'http://www.example.com/products',
- 'line1': 'Products line 1', 'line2': 'Products line 2'},
- {'text': 'About', 'url': 'http://www.example.com/about',
- 'line1': 'About line 1', 'line2': 'About line 2'}
- ]
-
- feed_items = []
- for item in items_data:
- feed_items.append({
- 'feedId': sitelinks_data['feedId'],
- 'attributeValues': [
- {
- 'feedAttributeId': sitelinks_data['linkTextFeedId'],
- 'stringValue': item['text']
- },
- {
- 'feedAttributeId': sitelinks_data['finalUrlFeedId'],
- 'stringValue': item['url']
- },
- {
- 'feedAttributeId': sitelinks_data['line1FeedId'],
- 'stringValue': item['line1']
- },
- {
- 'feedAttributeId': sitelinks_data['line2FeedId'],
- 'stringValue': item['line2']
- }
- ],
- # Optional: use the 'startTime' and 'endTime' keys to specify the time
- # period for the feed to deliver. The example below will make the feed
- # start now and stop in one month.
- # Make sure you specify the datetime in the customer's time zone. You
- # can retrieve this from customer['dateTimeZone'].
- #
- # ['startTime']: datetime.datetime.now().strftime('%Y%m%d %H%M%S')
- # ['endTime']: (datetime.datetime.now() +
- # relativedelta(months=1)).strftime('%Y%m%d %H%M%S')
-
- # Optional: use the 'scheduling' key to specify time and days of the
- # week for feed to deliver. This is a Beta feature.
- })
-
- feed_items_operations = [{'operator': 'ADD', 'operand': item} for item
- in feed_items]
-
- response = feed_item_service.mutate(feed_items_operations)
- if 'value' in response:
- sitelinks_data['feedItemIds'] = []
- for feed_item in response['value']:
- print 'Feed item with ID %s was added.' % feed_item['feedItemId']
- sitelinks_data['feedItemIds'].append(feed_item['feedItemId'])
- else:
- raise errors.GoogleAdsError('No feed items were added.')
-
- # Create site links feed mapping.
-
- feed_mapping = {
- 'placeholderType': PLACEHOLDER_SITELINKS,
- 'feedId': sitelinks_data['feedId'],
- 'attributeFieldMappings': [
- {
- 'feedAttributeId': sitelinks_data['linkTextFeedId'],
- 'fieldId': PLACEHOLDER_FIELD_SITELINK_LINK_TEXT
- },
- {
- 'feedAttributeId': sitelinks_data['finalUrlFeedId'],
- 'fieldId': PLACEHOLDER_FIELD_SITELINK_FINAL_URL
- },
- {
- 'feedAttributeId': sitelinks_data['line1FeedId'],
- 'fieldId': PLACEHOLDER_FIELD_LINE_1_TEXT
- },
- {
- 'feedAttributeId': sitelinks_data['line2FeedId'],
- 'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT
- }
- ]
- }
-
- response = feed_mapping_service.mutate([
- {'operator': 'ADD', 'operand': feed_mapping}
- ])
- if 'value' in response:
- feed_mapping = response['value'][0]
- print ('Feed mapping with ID %s and placeholder type %s was saved for feed'
- ' with ID %s.' %
- (feed_mapping['feedMappingId'], feed_mapping['placeholderType'],
- feed_mapping['feedId']))
- else:
- raise errors.GoogleAdsError('No feed mappings were added.')
-
- # Create site links campaign feed.
- operands = []
- for feed_item_id in sitelinks_data['feedItemIds']:
- operands.append({
- 'xsi_type': 'ConstantOperand',
- 'type': 'LONG',
- 'longValue': feed_item_id
- })
-
- feed_item_function = {
- 'operator': 'IN',
- 'lhsOperand': [
- {'xsi_type': 'RequestContextOperand', 'contextType': 'FEED_ITEM_ID'}
- ],
- 'rhsOperand': operands
- }
-
- # Optional: to target to a platform, define a function and 'AND' it with the
- # feed item ID link:
- platform_function = {
- 'operator': 'EQUALS',
- 'lhsOperand': [
- {
- 'xsi_type': 'RequestContextOperand',
- 'contextType': 'DEVICE_PLATFORM'
- }
- ],
- 'rhsOperand': [
- {
- 'xsi_type': 'ConstantOperand',
- 'type': 'STRING',
- 'stringValue': 'Mobile'
- }
- ]
- }
- combined_function = {
- 'operator': 'AND',
- 'lhsOperand': [
- {'xsi_type': 'FunctionOperand', 'value': feed_item_function},
- {'xsi_type': 'FunctionOperand', 'value': platform_function}
- ]
- }
-
- campaign_feed = {
- 'feedId': sitelinks_data['feedId'],
- 'campaignId': campaign_id,
- 'matchingFunction': combined_function,
- # Specifying placeholder types on the CampaignFeed allows the same feed
- # to be used for different placeholders in different Campaigns.
- 'placeholderTypes': [PLACEHOLDER_SITELINKS]
- }
-
- response = campaign_feed_service.mutate([
- {'operator': 'ADD', 'operand': campaign_feed}
- ])
- if 'value' in response:
- campaign_feed = response['value'][0]
- print ('Campaign with ID %s was associated with feed with ID %s.' %
- (campaign_feed['campaignId'], campaign_feed['feedId']))
- else:
- raise errors.GoogleAdsError('No campaign feeds were added.')
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201409/migration/__init__.py b/examples/adwords/v201409/migration/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/examples/adwords/v201409/migration/upgrade_ad_url.py b/examples/adwords/v201409/migration/upgrade_ad_url.py
deleted file mode 100755
index ffeba4ba..00000000
--- a/examples/adwords/v201409/migration/upgrade_ad_url.py
+++ /dev/null
@@ -1,82 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example upgrades an ad to use upgraded URLs.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupAdService.get, AdGroupAdService.upgradeUrl
-"""
-
-__author__ = 'Mark Saniscalchi'
-
-from googleads import adwords
-from googleads import errors
-
-
-ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE'
-AD_ID = 'INSERT_AD_ID_HERE'
-
-
-def main(client, adgroup_id, ad_id):
- # Initialize appropriate service.
- adgroup_ad_service = client.GetService('AdGroupAdService', version='v201409')
-
- selector = {
- 'fields': ['Id', 'Url'],
- 'predicates': [
- {
- 'field': 'AdGroupId',
- 'operator': 'EQUALS',
- 'values': [adgroup_id]
- },
- {
- 'field': 'Id',
- 'operator': 'EQUALS',
- 'values': [ad_id]
- }
- ]
- }
-
- page = adgroup_ad_service.get(selector)
-
- adgroup_ad = page['entries'][0] if page['entries'] else None
-
- if not adgroup_ad:
- raise errors.GoogleAdsError('Ad not found.')
-
- ad_url_upgrade = {
- 'adId': adgroup_ad['ad']['id'],
- 'finalUrl': adgroup_ad['ad']['url']
- }
-
- adgroup_ad = adgroup_ad_service.upgradeUrl([ad_url_upgrade])[0]
-
- if adgroup_ad:
- print ('AdGroupAd with ID %s and destination URL \'%s\' was upgraded.'
- % (adgroup_ad['id'], adgroup_ad['finalUrls'][0]))
- else:
- raise errors.GoogleAdsError('Failed to create AdGroupAd.')
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, ADGROUP_ID, AD_ID)
diff --git a/examples/adwords/v201409/misc/__init__.py b/examples/adwords/v201409/misc/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/examples/adwords/v201409/misc/get_all_images_and_videos.py b/examples/adwords/v201409/misc/get_all_images_and_videos.py
deleted file mode 100755
index 194af246..00000000
--- a/examples/adwords/v201409/misc/get_all_images_and_videos.py
+++ /dev/null
@@ -1,80 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all images and videos.
-
-To upload an image, run upload_image.py. To upload video, see:
-http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=39454.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: MediaService.get
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-PAGE_SIZE = 500
-
-
-def main(client):
- # Initialize appropriate service.
- media_service = client.GetService('MediaService', version='v201409')
-
- # Construct selector and get all images.
- offset = 0
- selector = {
- 'fields': ['MediaId', 'Type', 'Width', 'Height', 'MimeType'],
- 'predicates': [{
- 'field': 'Type',
- 'operator': 'IN',
- 'values': ['IMAGE', 'VIDEO']
- }],
- 'paging': {
- 'startIndex': str(offset),
- 'numberResults': str(PAGE_SIZE)
- }
- }
- more_pages = True
- while more_pages:
- page = media_service.get(selector)
-
- # Display results.
- if 'entries' in page:
- for image in page['entries']:
- dimensions = dict([(entry['key'], entry['value'])
- for entry in image['dimensions']])
- print ('Media with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\''
- ' was found.' % (image['mediaId'], dimensions['FULL']['height'],
- dimensions['FULL']['width'], image['mimeType']))
- else:
- print 'No images/videos were found.'
- offset += PAGE_SIZE
- selector['paging']['startIndex'] = str(offset)
- more_pages = offset < int(page['totalNumEntries'])
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201409/misc/upload_image.py b/examples/adwords/v201409/misc/upload_image.py
deleted file mode 100755
index 7b9aa88b..00000000
--- a/examples/adwords/v201409/misc/upload_image.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example uploads an image.
-
-To get images, run get_all_images.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: MediaService.upload
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-import base64
-
-from googleads import adwords
-
-
-IMAGE_FILENAME = 'INSERT_IMAGE_PATH_HERE'
-
-
-def main(client, image_filename):
- # Initialize appropriate service.
- media_service = client.GetService('MediaService', version='v201409')
-
- with open(image_filename, 'r') as image_handle:
- image_data = base64.encodestring(image_handle.read())
-
- # Construct media and upload image.
- media = [{
- 'xsi_type': 'Image',
- 'data': image_data,
- 'type': 'IMAGE'
- }]
- media = media_service.upload(media)[0]
-
- # Display results.
- if media:
- dimensions = dict([(entry['key'], entry['value'])
- for entry in media['dimensions']])
- print ('Image with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\' was'
- ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'],
- dimensions['FULL']['width'], media['mimeType']))
- else:
- print 'No images were uploaded.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, IMAGE_FILENAME)
diff --git a/examples/adwords/v201409/optimization/__init__.py b/examples/adwords/v201409/optimization/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/examples/adwords/v201409/optimization/estimate_keyword_traffic.py b/examples/adwords/v201409/optimization/estimate_keyword_traffic.py
deleted file mode 100755
index d1bae290..00000000
--- a/examples/adwords/v201409/optimization/estimate_keyword_traffic.py
+++ /dev/null
@@ -1,131 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example retrieves keyword traffic estimates.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: TrafficEstimatorService.get
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-def main(client):
- # Initialize appropriate service.
- traffic_estimator_service = client.GetService(
- 'TrafficEstimatorService', version='v201409')
-
- # Construct selector object and retrieve traffic estimates.
- keywords = [
- {'text': 'mars cruise', 'matchType': 'BROAD'},
- {'text': 'cheap cruise', 'matchType': 'PHRASE'},
- {'text': 'cruise', 'matchType': 'EXACT'}
- ]
- negative_keywords = [
- {'text': 'moon walk', 'matchType': 'BROAD'}
- ]
- keyword_estimate_requests = []
- for keyword in keywords:
- keyword_estimate_requests.append({
- 'keyword': {
- 'xsi_type': 'Keyword',
- 'matchType': keyword['matchType'],
- 'text': keyword['text']
- }
- })
-
- for keyword in negative_keywords:
- keyword_estimate_requests.append({
- 'keyword': {
- 'xsi_type': 'Keyword',
- 'matchType': keyword['matchType'],
- 'text': keyword['text']
- },
- 'isNegative': 'true'
- })
-
- selector = {
- 'campaignEstimateRequests': [{
- 'adGroupEstimateRequests': [{
- 'keywordEstimateRequests': keyword_estimate_requests,
- 'maxCpc': {
- 'xsi_type': 'Money',
- 'microAmount': '1000000'
- }
- }],
- 'criteria': [
- {
- 'xsi_type': 'Location',
- 'id': '2840' # United States.
- },
- {
- 'xsi_type': 'Language',
- 'id': '1000' # English.
- }
- ]
- }]
- }
- estimates = traffic_estimator_service.get(selector)
-
- # Display results.
- ad_group_estimate = estimates['campaignEstimates'][0]['adGroupEstimates'][0]
- keyword_estimates = ad_group_estimate['keywordEstimates']
- for index in xrange(len(keyword_estimates)):
- keyword = keyword_estimate_requests[index]['keyword']
- estimate = keyword_estimates[index]
- if keyword_estimate_requests[index].get('isNegative', False):
- continue
-
- # Find the mean of the min and max values.
- if (estimate['min']['clicksPerDay'] and estimate['max']['clicksPerDay'] and
- estimate['min']['impressionsPerDay'] and
- estimate['max']['impressionsPerDay']):
- mean_avg_cpc = (int(estimate['min']['averageCpc']['microAmount']) +
- int(estimate['max']['averageCpc']['microAmount'])) / 2
- mean_avg_pos = (float(estimate['min']['averagePosition']) +
- float(estimate['max']['averagePosition'])) / 2
- mean_clicks = (float(estimate['min']['clicksPerDay']) +
- float(estimate['max']['clicksPerDay'])) / 2
- mean_total_cost = (int(estimate['min']['totalCost']['microAmount']) +
- int(estimate['max']['totalCost']['microAmount'])) / 2
- else:
- # Default to 0 if no clicks/impressions per day.
- mean_avg_cpc = 0
- mean_avg_pos = 0
- mean_clicks = 0
- mean_total_cost = 0
-
- print ('Results for the keyword with text \'%s\' and match type \'%s\':'
- % (keyword['text'], keyword['matchType']))
- print ' Estimated average CPC: %s' % mean_avg_cpc
- print ' Estimated ad position: %s' % mean_avg_pos
- print ' Estimated daily clicks: %s' % mean_clicks
- print ' Estimated daily cost: %s' % mean_total_cost
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201409/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201409/optimization/get_keyword_bid_simulations.py
deleted file mode 100755
index 4e0197b1..00000000
--- a/examples/adwords/v201409/optimization/get_keyword_bid_simulations.py
+++ /dev/null
@@ -1,88 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets a bid landscape for an ad group and a criterion.
-
-To get ad groups, run get_ad_groups.py. To get criteria, run get_keywords.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: BidLandscapeService.getBidLandscape
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-CRITERION_ID = 'INSERT_CRITERION_ID_HERE'
-
-
-def main(client, ad_group_id, criterion_id):
- # Initialize appropriate service.
- data_service = client.GetService('DataService', version='v201409')
-
- # Construct bid landscape selector object and retrieve bid landscape.
- selector = {
- 'fields': ['AdGroupId', 'CriterionId', 'StartDate', 'EndDate', 'Bid',
- 'LocalClicks', 'LocalCost', 'MarginalCpc', 'LocalImpressions'],
- 'predicates': [
- {
- 'field': 'AdGroupId',
- 'operator': 'EQUALS',
- 'values': [ad_group_id]
- },
- {
- 'field': 'CriterionId',
- 'operator': 'EQUALS',
- 'values': [criterion_id]
- }
- ]
- }
- bid_landscapes = data_service.getCriterionBidLandscape(selector)
-
- # Display results.
- if 'entries' in bid_landscapes:
- for bid_landscape in bid_landscapes['entries']:
- if bid_landscape['BidLandscape.Type'] == 'CriterionBidLandscape':
- print ('Criterion bid landscape with ad group id \'%s\', criterion id '
- '\'%s\', start date \'%s\', end date \'%s\', with landscape '
- 'points was found:'
- % (bid_landscape['adGroupId'], bid_landscape['criterionId'],
- bid_landscape['startDate'], bid_landscape['endDate']))
- for bid_landscape_point in bid_landscape['landscapePoints']:
- print (' bid: %s => clicks: %s, cost: %s, marginalCpc: %s, '
- 'impressions: %s'
- % (bid_landscape_point['bid']['microAmount'],
- bid_landscape_point['clicks'],
- bid_landscape_point['cost']['microAmount'],
- bid_landscape_point['marginalCpc']['microAmount'],
- bid_landscape_point['impressions']))
- else:
- print 'No bid landscapes found.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID, CRITERION_ID)
diff --git a/examples/adwords/v201409/optimization/get_keyword_ideas.py b/examples/adwords/v201409/optimization/get_keyword_ideas.py
deleted file mode 100755
index ec91a490..00000000
--- a/examples/adwords/v201409/optimization/get_keyword_ideas.py
+++ /dev/null
@@ -1,95 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example retrieves keywords that are related to a given keyword.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: TargetingIdeaService.get
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-PAGE_SIZE = 100
-
-
-def main(client):
- # Initialize appropriate service.
- targeting_idea_service = client.GetService(
- 'TargetingIdeaService', version='v201409')
-
- # Construct selector object and retrieve related keywords.
- offset = 0
- selector = {
- 'searchParameters': [
- {
- 'xsi_type': 'RelatedToQuerySearchParameter',
- 'queries': ['space cruise']
- },
- {
- # Language setting (optional).
- # The ID can be found in the documentation:
- # https://developers.google.com/adwords/api/docs/appendix/languagecodes
- 'xsi_type': 'LanguageSearchParameter',
- 'languages': [{'id': '1000'}]
- }
- ],
- 'ideaType': 'KEYWORD',
- 'requestType': 'IDEAS',
- 'requestedAttributeTypes': ['KEYWORD_TEXT', 'SEARCH_VOLUME',
- 'CATEGORY_PRODUCTS_AND_SERVICES'],
- 'paging': {
- 'startIndex': str(offset),
- 'numberResults': str(PAGE_SIZE)
- }
- }
- more_pages = True
- while more_pages:
- page = targeting_idea_service.get(selector)
-
- # Display results.
- if 'entries' in page:
- for result in page['entries']:
- attributes = {}
- for attribute in result['data']:
- attributes[attribute['key']] = getattr(attribute['value'], 'value',
- '0')
- print ('Keyword with \'%s\' text and average monthly search volume '
- '\'%s\' was found with Products and Services categories: %s.'
- % (attributes['KEYWORD_TEXT'],
- attributes['SEARCH_VOLUME'],
- attributes['CATEGORY_PRODUCTS_AND_SERVICES']))
- print
- else:
- print 'No related keywords were found.'
- offset += PAGE_SIZE
- selector['paging']['startIndex'] = str(offset)
- more_pages = offset < int(page['totalNumEntries'])
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201409/remarketing/__init__.py b/examples/adwords/v201409/remarketing/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/examples/adwords/v201409/remarketing/add_audience.py b/examples/adwords/v201409/remarketing/add_audience.py
deleted file mode 100755
index 36dd9f02..00000000
--- a/examples/adwords/v201409/remarketing/add_audience.py
+++ /dev/null
@@ -1,107 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds a remarketing user list (a.k.a. audience).
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: UserListService.mutate
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-import uuid
-
-from googleads import adwords
-
-
-def main(client):
- # Initialize appropriate service.
- user_list_service = client.GetService(
- 'AdwordsUserListService', version='v201409')
- conversion_tracker_service = client.GetService(
- 'ConversionTrackerService', version='v201409')
-
- # Construct operations and add a user list.
- operations = [
- {
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'BasicUserList',
- 'name': 'Mars cruise customers #%s' % uuid.uuid4(),
- 'description': 'A list of mars cruise customers in the last year',
- 'membershipLifeSpan': '365',
- 'conversionTypes': [
- {
- 'name': ('Mars cruise customers #%s'
- % uuid.uuid4())
- }
- ],
- # Optional field.
- 'status': 'OPEN',
- }
- }
- ]
- result = user_list_service.mutate(operations)
-
- # Display results.
- if 'value' in result:
- conversion_ids = []
- for user_list in result['value']:
- if user_list['conversionTypes']:
- for conversion_type in user_list['conversionTypes']:
- conversion_ids.append(conversion_type['id'])
-
- selector = {
- 'fields': ['Name', 'Status', 'Category'],
- 'predicates': [{
- 'field': 'Id',
- 'operator': 'IN',
- 'values': conversion_ids
- }],
- 'ordering': [{
- 'field': 'Name',
- 'sortOrder': 'ASCENDING'
- }]
- }
-
- pages = conversion_tracker_service.get(selector)
- conversions_map = {}
- if pages['entries']:
- for conversion_tracker in pages['entries']:
- conversions_map[conversion_tracker['id']] = conversion_tracker
-
- for user_list in result['value']:
- print ('User list with name \'%s\' and ID \'%s\' was added.'
- % (user_list['name'], user_list['id']))
- if user_list['conversionTypes']:
- for conversion_type in user_list['conversionTypes']:
- conversion_tracker = conversions_map[conversion_type['id']]
- print ('Conversion type code snippet associated to the list:\n%s\n'
- % conversion_tracker['snippet'])
- else:
- print 'No user lists were added.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201409/remarketing/add_conversion_tracker.py b/examples/adwords/v201409/remarketing/add_conversion_tracker.py
deleted file mode 100755
index f21bdeb6..00000000
--- a/examples/adwords/v201409/remarketing/add_conversion_tracker.py
+++ /dev/null
@@ -1,77 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the 'License');
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an 'AS IS' BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds an AdWords conversion.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ConversionTrackerService.mutate
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-import uuid
-
-from googleads import adwords
-
-
-def main(client):
- # Initialize appropriate service.
- conversion_tracker_service = client.GetService(
- 'ConversionTrackerService', version='v201409')
-
- # Construct operations and add conversion_tracker.
- operations = [
- {
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'AdWordsConversionTracker',
- 'name': 'Mars cruise customers #%s' % uuid.uuid4(),
- 'category': 'DEFAULT',
- 'markupLanguage': 'HTML',
- 'textFormat': 'HIDDEN',
- # Optional fields.
- 'status': 'ENABLED',
- 'viewthroughLookbackWindow': '15',
- 'isProductAdsChargeable': 'true',
- 'productAdsChargeableConversionWindow': '15',
- 'conversionPageLanguage': 'en',
- 'backgroundColor': '#0000FF',
- 'defaultRevenueValue': '23.41',
- 'alwaysUseDefaultRevenueValue': 'true'
- }
- }
- ]
- conversion_trackers = conversion_tracker_service.mutate(operations)
-
- # Display results.
- for conversion_tracker in conversion_trackers['value']:
- print ('Conversion tracker with id \'%s\', name \'%s\', status \'%s\' '
- 'and category \'%s\' and snippet \n\'%s\'\n was added.\n' %
- (conversion_tracker['id'], conversion_tracker['name'],
- conversion_tracker['status'], conversion_tracker['category'],
- conversion_tracker['snippet']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201409/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201409/remarketing/add_rule_based_user_lists.py
deleted file mode 100755
index d4cdada1..00000000
--- a/examples/adwords/v201409/remarketing/add_rule_based_user_lists.py
+++ /dev/null
@@ -1,186 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the 'License');
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an 'AS IS' BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds two rule-based remarketing user lists.
-
-Adds two rule-based remarketing user lists; one with no site visit date
-restrictions and another that will only include users who visit your site in
-the next six months.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdwordsUserListService.mutate
-"""
-
-__author__ = 'Mark Saniscalchi'
-
-import calendar
-from datetime import date
-from datetime import datetime
-from datetime import timedelta
-
-from googleads import adwords
-
-
-def main(client):
- # Initialize appropriate service.
- adwords_user_list_service = client.GetService(
- 'AdwordsUserListService', version='v201409')
-
- # First rule item group - users who visited the checkout page and had more
- # than one item in their shopping cart.
- checkout_rule_item = {
- 'StringRuleItem': {
- 'key': {
- 'name': 'ecomm_pagetype'
- },
- 'op': 'EQUALS',
- 'value': 'checkout'
- }
- }
-
- cart_size_rule_item = {
- 'NumberRuleItem': {
- 'key': {
- 'name': 'cartsize'
- },
- 'op': 'GREATER_THAN',
- 'value': '1.0'
- }
- }
-
- # Combine the two rule items into a RuleItemGroup so AdWords will logically
- # AND the rules together.
- checkout_multiple_item_group = {
- 'items': [checkout_rule_item, cart_size_rule_item]
- }
-
- # Second rule item group - users who checked out within the next 3 months.
- today = date.today()
- start_date_rule_item = {
- 'DateRuleItem': {
- 'key': {
- 'name': 'checkoutdate'
- },
- 'op': 'AFTER',
- 'value': today.strftime('%Y%m%d')
- }
- }
-
- three_months_later = AddMonths(today, 3)
-
- three_months_later_rule_item = {
- 'DateRuleItem': {
- 'key': {
- 'name': 'checkoutdate'
- },
- 'op': 'BEFORE',
- 'value': three_months_later.strftime('%Y%m%d')
- }
- }
-
- # Combine the date rule items into a RuleItemGroup
- checked_out_date_range_item_group = {
- 'items': [start_date_rule_item, three_months_later_rule_item]
- }
-
- # Combine the rule item groups into a Rule so AdWords will logically OR the
- # groups together.
- rule = {
- 'groups': [
- checkout_multiple_item_group,
- checked_out_date_range_item_group
- ]
- }
-
- # Create the user list with no restrictions on site visit date.
- expression_user_list = {
- 'xsi_type': 'ExpressionRuleUserList',
- 'name': 'Expression-based user list created at %s'
- % datetime.today().strftime('%Y%m%d %H:%M:%S'),
- 'description': 'Users who checked out in three month window OR visited'
- ' the checkout page with more than one item in their'
- ' cart.',
- 'rule': rule
- }
-
- # Create the user list restricted to users who visit your site within the next
- # six months.
- end_date = AddMonths(today, 6)
-
- date_user_list = {
- 'xsi_type': 'DateSpecificRuleUserList',
- 'name': 'Date rule user list created at %s'
- % datetime.today().strftime('%Y%m%d %H:%M:%S'),
- 'description': 'Users who visited the site between %s and %s and checked'
- ' out in three month window OR visited the checkout page'
- ' with more than one item in their cart.'
- % (today.strftime('%Y%m%d'), end_date.strftime('%Y%m%d')),
- 'rule': rule,
- 'startDate': today.strftime('%Y%m%d'),
- 'endDate': end_date.strftime('%Y%m%d')
- }
-
- # Create operations to add the user lists.
- operations = [
- {
- 'operand': user_list,
- 'operator': 'ADD',
- } for user_list in [expression_user_list, date_user_list]
- ]
-
- # Submit the operations.
- user_lists = adwords_user_list_service.mutate(operations)
-
- # Display results.
- for user_list in user_lists['value']:
- print (('User list added with ID %d, name "%s", status "%s", list type'
- ' "%s", accountUserListStatus "%s", description "%s".') %
- (user_list['id'], user_list['name'],
- user_list['status'], user_list['listType'],
- user_list['accountUserListStatus'], user_list['description']))
-
-
-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 number of months to add.
-
- Returns:
- A date equal to the start date incremented by the given number of months.
- """
- current_date = start_date
- i = 0
- while i < months:
- month_days = calendar.monthrange(current_date.year, current_date.month)[1]
- current_date += timedelta(days=month_days)
- i += 1
- return current_date
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201409/reporting/__init__.py b/examples/adwords/v201409/reporting/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/examples/adwords/v201409/reporting/download_criteria_report.py b/examples/adwords/v201409/reporting/download_criteria_report.py
deleted file mode 100755
index 3211018e..00000000
--- a/examples/adwords/v201409/reporting/download_criteria_report.py
+++ /dev/null
@@ -1,65 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example downloads a criteria performance report.
-
-To get report fields, run get_report_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ReportDefinitionService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = 'Joseph DiLallo'
-
-import logging
-import sys
-
-from googleads import adwords
-
-logging.basicConfig(level=logging.INFO)
-logging.getLogger('suds.transport').setLevel(logging.DEBUG)
-
-
-def main(client):
- report_downloader = client.GetReportDownloader(version='v201409')
-
- # Create report definition.
- report = {
- 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT',
- 'dateRangeType': 'LAST_7_DAYS',
- 'reportType': 'CRITERIA_PERFORMANCE_REPORT',
- 'downloadFormat': 'CSV',
- 'selector': {
- 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType',
- 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost']
- },
- # Enable to get rows with zero impressions.
- 'includeZeroImpressions': 'false'
- }
-
- # You can provide a file object to write the output to. For this demonstration
- # we use sys.stdout to write the report to the screen.
- report_downloader.DownloadReport(report, sys.stdout)
-
-
-if __name__ == '__main__':
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
- main(adwords_client)
diff --git a/examples/adwords/v201409/reporting/download_criteria_report_as_stream.py b/examples/adwords/v201409/reporting/download_criteria_report_as_stream.py
deleted file mode 100755
index 62dccee1..00000000
--- a/examples/adwords/v201409/reporting/download_criteria_report_as_stream.py
+++ /dev/null
@@ -1,77 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example retrieves the report download stream.
-
-To get report fields, run get_report_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ReportDefinitionService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = 'Mark Saniscalchi'
-
-import logging
-import sys
-
-from googleads import adwords
-import StringIO
-
-logging.basicConfig(level=logging.INFO)
-logging.getLogger('suds.transport').setLevel(logging.DEBUG)
-
-
-def main(client):
- report_downloader = client.GetReportDownloader(version='v201409')
-
- # Create report definition.
- report = {
- 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT',
- 'dateRangeType': 'LAST_7_DAYS',
- 'reportType': 'CRITERIA_PERFORMANCE_REPORT',
- 'downloadFormat': 'CSV',
- 'selector': {
- 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType',
- 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost']
- },
- # Enable to get rows with zero impressions.
- 'includeZeroImpressions': 'false'
- }
-
- # Retrieve the report stream and print it out
- report_data = StringIO.StringIO()
- stream_data = report_downloader.DownloadReportAsStream(report)
-
- try:
- while True:
- chunk = stream_data.read(adwords.CHUNK_SIZE)
- if not chunk: break
- report_data.write(chunk.decode() if sys.version_info[0] == 3
- and getattr(report_data, 'mode', 'w') == 'w' else chunk)
- print report_data.getvalue()
- finally:
- report_data.close()
- stream_data.close()
-
-
-if __name__ == '__main__':
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
- main(adwords_client)
diff --git a/examples/adwords/v201409/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201409/reporting/download_criteria_report_as_stream_with_awql.py
deleted file mode 100755
index d0151e8c..00000000
--- a/examples/adwords/v201409/reporting/download_criteria_report_as_stream_with_awql.py
+++ /dev/null
@@ -1,82 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example downloads a criteria performance report as a string with AWQL.
-
-To get report fields, run get_report_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ReportDefinitionService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-import logging
-import StringIO
-import sys
-
-
-from googleads import adwords
-
-
-logging.basicConfig(level=logging.INFO)
-logging.getLogger('suds.transport').setLevel(logging.DEBUG)
-
-# Specify where to download the file here.
-PATH = '/tmp/report_download.csv'
-
-
-def main(client):
- # Initialize appropriate service.
- report_downloader = client.GetReportDownloader(version='v201409')
-
- # Create report query.
- report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, '
- 'FinalUrls, Impressions, Clicks, Cost '
- 'FROM CRITERIA_PERFORMANCE_REPORT '
- 'WHERE Status IN [ENABLED, PAUSED] '
- 'DURING LAST_7_DAYS')
-
- print report_downloader.DownloadReportAsStringWithAwql(report_query, 'CSV')
-
- # Retrieve the report stream and print it out
- report_data = StringIO.StringIO()
- stream_data = report_downloader.DownloadReportAsStreamWithAwql(report_query,
- 'CSV')
-
- try:
- while True:
- chunk = stream_data.read(adwords.CHUNK_SIZE)
- if not chunk: break
- report_data.write(chunk.decode() if sys.version_info[0] == 3
- and getattr(report_data, 'mode', 'w') == 'w' else chunk)
- print report_data.getvalue()
- finally:
- report_data.close()
- stream_data.close()
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201409/reporting/download_criteria_report_as_string.py b/examples/adwords/v201409/reporting/download_criteria_report_as_string.py
deleted file mode 100755
index f6ba8c74..00000000
--- a/examples/adwords/v201409/reporting/download_criteria_report_as_string.py
+++ /dev/null
@@ -1,64 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example downloads a criteria performance report as a string.
-
-To get report fields, run get_report_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ReportDefinitionService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = 'Mark Saniscalchi'
-
-import logging
-import sys
-
-from googleads import adwords
-
-logging.basicConfig(level=logging.INFO)
-logging.getLogger('suds.transport').setLevel(logging.DEBUG)
-
-
-def main(client):
- report_downloader = client.GetReportDownloader(version='v201409')
-
- # Create report definition.
- report = {
- 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT',
- 'dateRangeType': 'LAST_7_DAYS',
- 'reportType': 'CRITERIA_PERFORMANCE_REPORT',
- 'downloadFormat': 'CSV',
- 'selector': {
- 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType',
- 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost']
- },
- # Enable to get rows with zero impressions.
- 'includeZeroImpressions': 'false'
- }
-
- # Print out the report as a string
- print report_downloader.DownloadReportAsString(report)
-
-
-if __name__ == '__main__':
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
- main(adwords_client)
diff --git a/examples/adwords/v201409/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201409/reporting/download_criteria_report_as_string_with_awql.py
deleted file mode 100755
index f07df0f9..00000000
--- a/examples/adwords/v201409/reporting/download_criteria_report_as_string_with_awql.py
+++ /dev/null
@@ -1,58 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example downloads a criteria performance report as a string with AWQL.
-
-To get report fields, run get_report_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ReportDefinitionService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-# Specify where to download the file here.
-PATH = '/tmp/report_download.csv'
-
-
-def main(client):
- # Initialize appropriate service.
- report_downloader = client.GetReportDownloader(version='v201409')
-
- # Create report query.
- report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, '
- 'FinalUrls, Impressions, Clicks, Cost '
- 'FROM CRITERIA_PERFORMANCE_REPORT '
- 'WHERE Status IN [ENABLED, PAUSED] '
- 'DURING LAST_7_DAYS')
-
- print report_downloader.DownloadReportAsStringWithAwql(report_query, 'CSV')
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201409/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201409/reporting/download_criteria_report_with_awql.py
deleted file mode 100755
index 627d3cf0..00000000
--- a/examples/adwords/v201409/reporting/download_criteria_report_with_awql.py
+++ /dev/null
@@ -1,61 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example downloads a criteria performance report with AWQL.
-
-To get report fields, run get_report_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ReportDefinitionService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-# Specify where to download the file here.
-PATH = '/tmp/report_download.csv'
-
-
-def main(client, path):
- # Initialize appropriate service.
- report_downloader = client.GetReportDownloader(version='v201409')
-
- # Create report query.
- report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, '
- 'FinalUrls, Impressions, Clicks, Cost '
- 'FROM CRITERIA_PERFORMANCE_REPORT '
- 'WHERE Status IN [ENABLED, PAUSED] '
- 'DURING LAST_7_DAYS')
-
- with open(path, 'w') as output_file:
- report_downloader.DownloadReportWithAwql(report_query, 'CSV', output_file)
-
- print 'Report was downloaded to \'%s\'.' % path
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, PATH)
diff --git a/examples/adwords/v201409/reporting/get_report_fields.py b/examples/adwords/v201409/reporting/get_report_fields.py
deleted file mode 100755
index 5cb7e131..00000000
--- a/examples/adwords/v201409/reporting/get_report_fields.py
+++ /dev/null
@@ -1,56 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets report fields.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ReportDefinitionService.getReportFields
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-REPORT_TYPE = 'INSERT_REPORT_TYPE_HERE'
-
-
-def main(client, report_type):
- # Initialize appropriate service.
- report_definition_service = client.GetService(
- 'ReportDefinitionService', version='v201409')
-
- # Get report fields.
- fields = report_definition_service.getReportFields(report_type)
-
- # Display results.
- print 'Report type \'%s\' contains the following fields:' % report_type
- for field in fields:
- print ' - %s (%s)' % (field['fieldName'], field['fieldType'])
- if 'enumValues' in field:
- print ' := [%s]' % ', '.join(field['enumValues'])
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, REPORT_TYPE)
diff --git a/examples/adwords/v201409/shopping/add_product_partition_tree.py b/examples/adwords/v201409/shopping/add_product_partition_tree.py
deleted file mode 100755
index 9bc821a3..00000000
--- a/examples/adwords/v201409/shopping/add_product_partition_tree.py
+++ /dev/null
@@ -1,285 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates a ProductPartition tree.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupCriterionService.mutate
-"""
-
-__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import adwords
-
-ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-class ProductPartitionHelper(object):
- """A helper for creating ProductPartition trees."""
-
- # The next temporary criterion ID to be used.
- # When creating our tree we need to specify the parent-child relationships
- # between nodes. However, until a criterion has been created on the server we
- # do not have a criterion ID with which to refer to it.
- # Instead we can specify temporary IDs that are specific to a single mutate
- # request. Once the criteria have been created they are assigned an ID as
- # normal and the temporary ID will no longer refer to it.
- # A valid temporary ID is any negative integer.
- next_id = -1
-
- # The set of mutate operations needed to create the current tree.
- operations = []
-
- def __init__(self, adgroup_id):
- """Initializer.
-
- Args:
- adgroup_id: The ID of the AdGroup that we wish to attach the partition
- tree to.
- """
- self.adgroup_id = adgroup_id
-
- 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',
- 'partitionType': 'SUBDIVISION',
- 'id': str(self.next_id)
- }
-
- # The root has neither a parent nor a value.
- if parent is not None:
- division['parentCriterionId'] = parent['id']
- division['caseValue'] = value
-
- adgroup_criterion = {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': self.adgroup_id,
- 'criterion': division
- }
-
- self.CreateAddOperation(adgroup_criterion)
- self.next_id -= 1
-
- return division
-
- 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.
- """
- unit = {
- 'xsi_type': 'ProductPartition',
- 'partitionType': 'UNIT'
- }
-
- # The root node has neither a parent nor a value.
- if parent is not None:
- unit['parentCriterionId'] = parent['id']
- unit['caseValue'] = value
-
- if bid_amount is not None and bid_amount > 0:
- bidding_strategy_configuration = {
- 'bids': [{
- 'xsi_type': 'CpcBid',
- 'bid': {
- 'xsi_type': 'Money',
- 'microAmount': str(bid_amount)
- }
- }]
- }
-
- adgroup_criterion = {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'biddingStrategyConfiguration': bidding_strategy_configuration
- }
- else:
- adgroup_criterion = {
- 'xsi_type': 'NegativeAdGroupCriterion'
- }
-
- adgroup_criterion['adGroupId'] = self.adgroup_id
- adgroup_criterion['criterion'] = unit
-
- self.CreateAddOperation(adgroup_criterion)
-
- return unit
-
- def GetOperations(self):
- """Returns the set of mutate operations needed to create the current tree.
-
- Returns:
- The set of operations
- """
- return self.operations
-
- def CreateAddOperation(self, criterion):
- """Creates an AdGroupCriterionOperation for the given criterion.
-
- Args:
- criterion: The criterion we want to add.
- """
- operation = {
- 'operator': 'ADD',
- 'operand': criterion
- }
-
- self.operations.append(operation)
-
-
-def main(client, adgroup_id):
- """Runs the example."""
- adgroup_criterion_service = client.GetService(
- 'AdGroupCriterionService', version='v201409')
-
- helper = ProductPartitionHelper(adgroup_id)
-
- # The most trivial partition tree has only a unit node as the root, e.g.:
- # helper.CreateUnit(bid_amount=100000)
-
- root = helper.CreateSubdivision()
-
- new_product_canonical_condition = {
- 'xsi_type': 'ProductCanonicalCondition',
- 'condition': 'NEW'
- }
-
- used_product_canonical_condition = {
- 'xsi_type': 'ProductCanonicalCondition',
- 'condition': 'USED'
- }
-
- other_product_canonical_condition = {
- 'xsi_type': 'ProductCanonicalCondition',
- }
-
- helper.CreateUnit(root, new_product_canonical_condition, 200000)
- helper.CreateUnit(root, used_product_canonical_condition, 100000)
- other_condition = helper.CreateSubdivision(
- root, other_product_canonical_condition)
-
- cool_product_brand = {
- 'xsi_type': 'ProductBrand',
- 'value': 'CoolBrand'
- }
-
- cheap_product_brand = {
- 'xsi_type': 'ProductBrand',
- 'value': 'CheapBrand'
- }
-
- other_product_brand = {
- 'xsi_type': 'ProductBrand',
- }
-
- helper.CreateUnit(other_condition, cool_product_brand, 900000)
- helper.CreateUnit(other_condition, cheap_product_brand, 10000)
- other_brand = helper.CreateSubdivision(other_condition, other_product_brand)
-
- # The value for the bidding category is a fixed ID for the 'Luggage & Bags'
- # category. You can retrieve IDs for categories from the ConstantDataService.
- # See the 'GetProductTaxonomy' example for more details.
- luggage_category = {
- 'xsi_type': 'ProductBiddingCategory',
- 'type': 'BIDDING_CATEGORY_L1',
- 'value': '-5914235892932915235'
- }
-
- generic_category = {
- 'xsi_type': 'ProductBiddingCategory',
- 'type': 'BIDDING_CATEGORY_L1',
- }
-
- helper.CreateUnit(other_brand, luggage_category, 750000)
- helper.CreateUnit(other_brand, generic_category, 110000)
-
- # Make the mutate request
- result = adgroup_criterion_service.mutate(helper.GetOperations())
-
- children = {}
-
- root_node = None
-
- # For each criterion, make an array containing each of its children.
- # We always create the parent before the child, so we can rely on that here.
- for adgroup_criterion in result['value']:
- children[adgroup_criterion['criterion']['id']] = []
-
- if 'parentCriterionId' in adgroup_criterion['criterion']:
- children[adgroup_criterion['criterion']['parentCriterionId']].append(
- adgroup_criterion['criterion'])
- else:
- root_node = adgroup_criterion['criterion']
-
- # Show the tree
- DisplayTree(root_node, 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_value = node['caseValue']
- node_type = case_value['ProductDimension.Type']
-
- if node_type == 'ProductCanonicalCondition':
- value = (case_value['condition'] if 'condition' in case_value
- else 'OTHER')
- elif node_type == 'ProductBiddingCategory':
- value = '%s(%s)' % (case_value['type'], case_value['value']
- if 'value' in case_value else 'OTHER')
- else:
- value = (case_value['value'] if 'value' in case_value else 'OTHER')
-
- print ('%sid: %s, node_type: %s, value: %s\n'
- % (' ' * level, node['id'], node_type, value))
-
- for child_node in children[node['id']]:
- DisplayTree(child_node, children, level + 1)
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, ADGROUP_ID)
-
diff --git a/examples/adwords/v201409/shopping/add_product_scope.py b/examples/adwords/v201409/shopping/add_product_scope.py
deleted file mode 100755
index 690e26d4..00000000
--- a/examples/adwords/v201409/shopping/add_product_scope.py
+++ /dev/null
@@ -1,107 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Restricts products that will be included in a campaign with a ProductScope.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignCriterionService.mutate
-"""
-
-__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import adwords
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-
-
-def main(client, campaign_id):
- campaign_criterion_service = client.GetService(
- 'CampaignCriterionService', version='v201409')
-
- product_scope = {
- 'xsi_type': 'ProductScope',
- # This set of dimensions is for demonstration purposes only. It would be
- # extremely unlikely that you want to include so many dimensions in your
- # product scope.
- 'dimensions': [
- {
- 'xsi_type': 'ProductBrand',
- 'value': 'Nexus'
- },
- {
- 'xsi_type': 'ProductCanonicalCondition',
- 'condition': 'NEW'
- },
- {
- 'xsi_type': 'ProductCustomAttribute',
- 'type': 'CUSTOM_ATTRIBUTE_0',
- 'value': 'my attribute value'
- },
- {
- 'xsi_type': 'ProductOfferId',
- 'value': 'book1'
- },
- {
- 'xsi_type': 'ProductType',
- 'type': 'PRODUCT_TYPE_L1',
- 'value': 'Media'
- },
- {
- 'xsi_type': 'ProductType',
- 'type': 'PRODUCT_TYPE_L2',
- 'value': 'Books'
- },
- # The value for the bidding category is a fixed ID for the "Luggage
- # & Bags" category. You can retrieve IDs for categories from the
- # ConstantDataService. See the "GetProductCategoryTaxonomy" example
- # for more details.
- {
- 'xsi_type': 'ProductBiddingCategory',
- 'type': 'BIDDING_CATEGORY_L1',
- 'value': '-5914235892932915235'
- }
- ]
- }
-
- campaign_criterion = {
- 'campaignId': campaign_id,
- 'criterion': product_scope
- }
-
- operations = [{
- 'operator': 'ADD',
- 'operand': campaign_criterion
- }]
-
- # Make the request
- result = campaign_criterion_service.mutate(operations)
-
- for criterion in result['value']:
- print ('Created a ProductScope criterion with Id: %s'
- % criterion['criterion']['id'])
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201409/shopping/add_shopping_campaign.py b/examples/adwords/v201409/shopping/add_shopping_campaign.py
deleted file mode 100755
index 0748cc24..00000000
--- a/examples/adwords/v201409/shopping/add_shopping_campaign.py
+++ /dev/null
@@ -1,122 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds a Shopping campaign.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignService.mutate, AdGroupService.mutate, AdGroupAdService.mutate
-"""
-
-__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import adwords
-
-BUDGET_ID = 'INSERT_BUDGET_ID_HERE'
-MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE'
-
-
-def main(client, budget_id, merchant_id):
- campaign_service = client.GetService('CampaignService', version='v201409')
- ad_group_service = client.GetService('AdGroupService', version='v201409')
- ad_group_ad_service = client.GetService('AdGroupAdService', version='v201409')
-
- # Create campaign
- campaign = {
- 'name': 'Shopping campaign #%s' % uuid.uuid4(),
- # The advertisingChannelType is what makes this a shopping campaign
- 'advertisingChannelType': 'SHOPPING',
- # Set shared budget (required)
- 'budget': {
- 'budgetId': budget_id
- },
- 'biddingStrategyConfiguration': {
- 'biddingStrategyType': 'MANUAL_CPC'
- },
- 'settings': [
- # All shopping campaigns need a ShoppingSetting
- {
- 'xsi_type': 'ShoppingSetting',
- 'salesCountry': 'US',
- 'campaignPriority': '0',
- 'merchantId': merchant_id
- }
- ]
- }
-
- campaign_operations = [{
- 'operator': 'ADD',
- 'operand': campaign
- }]
-
- result = campaign_service.mutate(campaign_operations)
-
- for campaign in result['value']:
- print ('Campaign with name \'%s\' and ID \'%s\' was added.'
- % (campaign['name'], campaign['id']))
-
- # Create the AdGroup
- adgroup = {
- 'campaignId': campaign['id'],
- 'name': 'AdGroup #%s' % uuid.uuid4()
- }
-
- adgroup_operations = {
- 'operator': 'ADD',
- 'operand': adgroup
- }
-
- # Make the mutate request to add the AdGroup to the Shopping Campaign
- ad_group_result = ad_group_service.mutate(adgroup_operations)
-
- for adgroup in ad_group_result['value']:
- print ('AdGroup with name \'%s\' and ID \'%s\' was added.'
- % (adgroup['name'], adgroup['id']))
-
- # Create an AdGroup Ad
- adgroup_ad = {
- 'adGroupId': adgroup['id'],
- # Create ProductAd
- 'ad': {
- 'xsi_type': 'ProductAd',
- 'Ad.Type': 'ProductAd'
- }
- }
-
- ad_operation = {
- 'operator': 'ADD',
- 'operand': adgroup_ad
- }
-
- # Make the mutate request to add the ProductAd to the AdGroup
- ad_result = ad_group_ad_service.mutate([ad_operation])
-
- for adgroup_ad in ad_result['value']:
- print 'ProductAd with ID \'%s\' was added.' % adgroup_ad['ad']['id']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, BUDGET_ID, MERCHANT_ID)
diff --git a/examples/adwords/v201409/shopping/get_product_category_taxonomy.py b/examples/adwords/v201409/shopping/get_product_category_taxonomy.py
deleted file mode 100755
index b544d5f6..00000000
--- a/examples/adwords/v201409/shopping/get_product_category_taxonomy.py
+++ /dev/null
@@ -1,99 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example fetches the set of valid ProductBiddingCategories.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ConstantDataService.getProductBiddingCategoryData
-"""
-
-__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import adwords
-
-
-def main(client):
- service = client.GetService('ConstantDataService', version='v201409')
-
- selector = {
- 'predicates': [
- {
- 'field': 'Country',
- 'operator': 'IN',
- 'values': ['US']
- }
- ]
- }
-
- result = service.getProductBiddingCategoryData(selector)
-
- bidding_categories = {}
- root_categories = []
-
- for product_bidding_category in result:
- category_id = product_bidding_category['dimensionValue']['value']
- parent_id = None
- name = product_bidding_category['displayValue'][0]['value']
-
- # Note: There may be cases where there isn't a value.
- if ('parentDimensionValue' in product_bidding_category and
- 'value' in product_bidding_category['parentDimensionValue']):
- parent_id = product_bidding_category['parentDimensionValue']['value']
-
- if category_id not in bidding_categories:
- bidding_categories[category_id] = {}
-
- category = bidding_categories[category_id]
-
- if parent_id is not None:
- if parent_id not in bidding_categories:
- bidding_categories[parent_id] = {}
-
- parent = bidding_categories[parent_id]
-
- if 'children' not in parent:
- parent['children'] = []
-
- parent['children'].append(category)
- else:
- root_categories.append(category)
-
- category['id'] = category_id
- category['name'] = name
-
- DisplayCategories(root_categories)
-
-
-def DisplayCategories(categories, prefix=''):
- for category in categories:
- print '%s%s [%s]' % (prefix, category['name'], category['id'])
-
- if 'children' in category:
- DisplayCategories(category['children'], '%s%s > ' % (prefix,
- category['name']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201409/targeting/__init__.py b/examples/adwords/v201409/targeting/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/examples/adwords/v201409/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201409/targeting/add_campaign_targeting_criteria.py
deleted file mode 100755
index e446c210..00000000
--- a/examples/adwords/v201409/targeting/add_campaign_targeting_criteria.py
+++ /dev/null
@@ -1,159 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds various types of targeting criteria to a given campaign.
-
-To get campaigns, run get_campaigns.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignCriterionService.mutate
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-
-
-def main(client, campaign_id):
- # Initialize appropriate service.
- campaign_criterion_service = client.GetService(
- 'CampaignCriterionService', version='v201409')
-
- # Create locations. The IDs can be found in the documentation or retrieved
- # with the LocationCriterionService.
- california = {
- 'xsi_type': 'Location',
- 'id': '21137'
- }
- mexico = {
- 'xsi_type': 'Location',
- 'id': '2484'
- }
-
- # Create languages. The IDs can be found in the documentation or retrieved
- # with the ConstantDataService.
- english = {
- 'xsi_type': 'Language',
- 'id': '1000'
- }
- spanish = {
- 'xsi_type': 'Language',
- 'id': '1003'
- }
-
- # Create location groups. The IDs can be found in the documentation or
- # retrieved with the LocationCriterionService.
- florida_tier3 = {
- 'xsi_type': 'LocationGroups',
- 'matchingFunction': {
- 'operator': 'AND',
- 'lhsOperand': [{
- 'xsi_type': 'IncomeOperand',
- # Tiers are numbered 1-10, and represent 10% segments of earners.
- # For example, TIER_1 is the top 10%, TIER_2 is the 80-90%, etc.
- # Tiers 6 through 10 are grouped into TIER_6_TO_10.
- 'tier': 'TIER_3'
- }],
- 'rhsOperand': [{
- 'xsi_type': 'GeoTargetOperand',
- 'locations': [1015116] # Miami, FL
- }]
- },
- }
- florida_downtown = {
- 'xsi_type': 'LocationGroups',
- 'matchingFunction': {
- 'operator': 'AND',
- 'lhsOperand': [{
- 'xsi_type': 'PlacesOfInterestOperand',
- # Other valid options: AIRPORT, UNIVERSITY.
- 'category': 'DOWNTOWN',
- }],
- 'rhsOperand': [{
- 'xsi_type': 'GeoTargetOperand',
- 'locations': [1015116] # Miami, FL
- }]
- }
- }
- # Distance targeting. Area of 10 miles around targets above.
- distance_10_miles = {
- 'xsi_type': 'LocationGroups',
- 'matchingFunction': {
- 'operator': 'IDENTITY',
- 'lhsOperand': [{
- 'xsi_type': 'LocationExtensionOperand',
- 'radius': {
- 'xsi_type': 'ConstantOperand',
- 'type': 'DOUBLE',
- 'unit': 'MILES',
- 'doubleValue': 10
- }
-
- }]
- }
- }
- # Create a negative campaign criterion operation.
- negative_campaign_criterion_operand = {
- 'xsi_type': 'NegativeCampaignCriterion',
- 'campaignId': campaign_id,
- 'criterion': {
- 'xsi_type': 'Keyword',
- 'matchType': 'BROAD',
- 'text': 'jupiter cruise'
- }
- }
-
- # Create operations
- operations = []
- for criterion in [california, mexico, english, spanish, florida_tier3,
- florida_downtown, distance_10_miles]:
- operations.append({
- 'operator': 'ADD',
- 'operand': {
- 'campaignId': campaign_id,
- 'criterion': criterion
- }
- })
- # Add the negative campaign criterion.
- operations.append({
- 'operator': 'ADD',
- 'operand': negative_campaign_criterion_operand
- })
-
- # Make the mutate request.
- result = campaign_criterion_service.mutate(operations)
-
- # Display the resulting campaign criteria.
- for campaign_criterion in result['value']:
- print ('Campaign criterion with campaign id \'%s\', criterion id \'%s\', '
- 'and type \'%s\' was added.'
- % (campaign_criterion['campaignId'],
- campaign_criterion['criterion']['id'],
- campaign_criterion['criterion']['type']))
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201409/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201409/targeting/add_demographic_targeting_criteria.py
deleted file mode 100755
index 59fb8194..00000000
--- a/examples/adwords/v201409/targeting/add_demographic_targeting_criteria.py
+++ /dev/null
@@ -1,99 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds demographic criteria to an ad group.
-
-To get a list of ad groups, run get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupCriterionService.mutate
-"""
-
-__author__ = 'Joseph Dilallo'
-
-from googleads import adwords
-
-
-GENDER_MALE = '10'
-AGE_RANGE_UNDETERMINED = '503999'
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Initialize appropriate service.
- ad_group_criterion_service = client.GetService(
- 'AdGroupCriterionService', version='v201409')
-
- # Create the ad group criteria.
- ad_group_criteria = [
- # Targeting criterion.
- {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Gender',
- # Create gender criteria. The IDs can be found in the
- # documentation:
- # https://developers.google.com/adwords/api/docs/appendix/genders.
- 'id': GENDER_MALE
- }
- },
- # Exclusion criterion.
- {
- 'xsi_type': 'NegativeAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'AgeRange',
- # Create age range criteria. The IDs can be found in the
- # documentation:
- # https://developers.google.com/adwords/api/docs/appendix/ages.
- 'id': AGE_RANGE_UNDETERMINED
- }
- }
- ]
-
- # Create operations.
- operations = []
- for criterion in ad_group_criteria:
- operations.append({
- 'operator': 'ADD',
- 'operand': criterion
- })
-
- response = ad_group_criterion_service.mutate(operations)
-
- if response and response['value']:
- criteria = response['value']
- for ad_group_criterion in criteria:
- criterion = ad_group_criterion['criterion']
- print ('Ad group criterion with ad group ID %s, criterion ID %s and '
- 'type \'%s\' was added.' %
- (ad_group_criterion['adGroupId'], criterion['id'],
- criterion['type']))
- else:
- print 'No criteria were returned.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201409/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201409/targeting/get_campaign_targeting_criteria.py
deleted file mode 100755
index af886c92..00000000
--- a/examples/adwords/v201409/targeting/get_campaign_targeting_criteria.py
+++ /dev/null
@@ -1,89 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example illustrates how to retrieve all the campaign targets.
-
-To set campaign targets, run add_campaign_targeting_criteria.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignCriterionService.get
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-PAGE_SIZE = 500
-
-
-def main(client):
- # Initialize appropriate service.
- campaign_criterion_service = client.GetService(
- 'CampaignCriterionService', version='v201409')
-
- # Construct selector and get all campaign targets.
- offset = 0
- selector = {
- 'fields': ['CampaignId', 'Id', 'CriteriaType', 'PlatformName',
- 'LanguageName', 'LocationName', 'KeywordText'],
- 'predicates': [{
- 'field': 'CriteriaType',
- 'operator': 'IN',
- 'values': ['KEYWORD', 'LANGUAGE', 'LOCATION', 'PLATFORM']
- }],
- 'paging': {
- 'startIndex': str(offset),
- 'numberResults': str(PAGE_SIZE)
- }
- }
- more_pages = True
- while more_pages:
- page = campaign_criterion_service.get(selector)
-
- # Display results.
- if 'entries' in page:
- for campaign_criterion in page['entries']:
- negative = ''
- if (campaign_criterion['CampaignCriterion.Type']
- == 'NegativeCampaignCriterion'):
- negative = 'Negative '
- criterion = campaign_criterion['criterion']
- criteria = (criterion['text'] if 'text' in criterion else
- criterion['platformName'] if 'platformName' in criterion
- else criterion['name'] if 'name' in criterion else
- criterion['locationName'] if 'locationName' in criterion
- else None)
- print ('%sCampaign Criterion found for Campaign ID %s with type %s and '
- 'criteria "%s".' % (negative, campaign_criterion['campaignId'],
- criterion['type'], criteria))
- else:
- print 'No campaign targets were found.'
- offset += PAGE_SIZE
- selector['paging']['startIndex'] = str(offset)
- more_pages = offset < int(page['totalNumEntries'])
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201409/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201409/targeting/get_targetable_languages_and_carriers.py
deleted file mode 100755
index c0a83892..00000000
--- a/examples/adwords/v201409/targeting/get_targetable_languages_and_carriers.py
+++ /dev/null
@@ -1,60 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Retrieves all languages and carriers available for targeting.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ConstantDataService.getLanguageCriterion
-Tags: ConstantDataService.getCarrierCriterion
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-def main(client):
- # Initialize appropriate service.
- constant_data_service = client.GetService(
- 'ConstantDataService', version='v201409')
-
- # Get all languages.
- languages = constant_data_service.getLanguageCriterion()
-
- # Display results.
- for language in languages:
- print ('Language with name \'%s\' and ID \'%s\' was found.'
- % (language['name'], language['id']))
-
- # Get all carriers.
- carriers = constant_data_service.getCarrierCriterion()
-
- # Display results.
- for carrier in carriers:
- print ('Carrier with name \'%s\', ID \'%s\', and country code \'%s\' was '
- 'found.' % (carrier['name'], carrier['id'], carrier['countryCode']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201409/targeting/lookup_location.py b/examples/adwords/v201409/targeting/lookup_location.py
deleted file mode 100755
index 164901c9..00000000
--- a/examples/adwords/v201409/targeting/lookup_location.py
+++ /dev/null
@@ -1,86 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all LocationCriterion.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: LocationCriterionService.get
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-def GetLocationString(location):
- return '%s (%s)' % (location['locationName'], location['displayType']
- if 'displayType' in location else None)
-
-
-def main(client):
- # Initialize appropriate service.
- location_criterion_service = client.GetService(
- 'LocationCriterionService', version='v201409')
-
- location_names = ['Paris', 'Quebec', 'Spain', 'Deutchland']
-
- # Create the selector.
- selector = {
- 'fields': ['Id', 'LocationName', 'DisplayType', 'CanonicalName',
- 'ParentLocations', 'Reach', 'TargetingStatus'],
- 'predicates': [{
- 'field': 'LocationName',
- 'operator': 'IN',
- 'values': location_names
- }, {
- 'field': 'Locale',
- 'operator': 'EQUALS',
- 'values': ['en']
- }]
- }
-
- # Make the get request.
- location_criteria = location_criterion_service.get(selector)
-
- # Display the resulting location criteria.
- for location_criterion in location_criteria:
- parent_string = ''
- if ('parentLocations' in location_criterion['location']
- and location_criterion['location']['parentLocations']):
- parent_string = ', '.join([GetLocationString(parent)for parent in
- location_criterion['location']
- ['parentLocations']])
- print ('The search term \'%s\' returned the location \'%s\' of type \'%s\''
- ' with parent locations \'%s\', reach \'%s\' and id \'%s\' (%s)'
- % (location_criterion['searchTerm'],
- location_criterion['location']['locationName'],
- location_criterion['location']['displayType'], parent_string,
- location_criterion['reach']
- if 'reach' in location_criterion else None,
- location_criterion['location']['id'],
- location_criterion['location']['targetingStatus']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201502/__init__.py b/examples/adwords/v201502/__init__.py
deleted file mode 100644
index 41f5a52e..00000000
--- a/examples/adwords/v201502/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Examples for AdWords."""
diff --git a/examples/adwords/v201502/account_management/__init__.py b/examples/adwords/v201502/account_management/__init__.py
deleted file mode 100644
index fb8c03ea..00000000
--- a/examples/adwords/v201502/account_management/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Account management examples."""
diff --git a/examples/adwords/v201502/account_management/create_account.py b/examples/adwords/v201502/account_management/create_account.py
deleted file mode 100755
index 1427677c..00000000
--- a/examples/adwords/v201502/account_management/create_account.py
+++ /dev/null
@@ -1,67 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example illustrates how to create an account.
-
-Note by default this account will only be accessible via parent MCC.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreateAccountService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from datetime import datetime
-
-from googleads import adwords
-
-
-def main(client):
- # Initialize appropriate service.
- managed_customer_service = client.GetService(
- 'ManagedCustomerService', version='v201502')
-
- today = datetime.today().strftime('%Y%m%d %H:%M:%S')
- # Construct operations and add campaign.
- operations = [{
- 'operator': 'ADD',
- 'operand': {
- 'name': 'Account created with ManagedCustomerService on %s' % today,
- 'currencyCode': 'EUR',
- 'dateTimeZone': 'Europe/London',
- }
- }]
-
- # Create the account. It is possible to create multiple accounts with one
- # request by sending an array of operations.
- accounts = managed_customer_service.mutate(operations)
-
- # Display results.
- for account in accounts['value']:
- print ('Account with customer ID \'%s\' was successfully created.'
- % account['customerId'])
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
- main(adwords_client)
diff --git a/examples/adwords/v201502/account_management/get_account_changes.py b/examples/adwords/v201502/account_management/get_account_changes.py
deleted file mode 100755
index 7fa5ff80..00000000
--- a/examples/adwords/v201502/account_management/get_account_changes.py
+++ /dev/null
@@ -1,100 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets the changes in the account during the last 24 hours.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomerSyncService.get
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-import datetime
-
-from googleads import adwords
-
-
-def main(client):
- # Initialize appropriate service.
- customer_sync_service = client.GetService(
- 'CustomerSyncService', version='v201502')
- campaign_service = client.GetService('CampaignService', version='v201502')
-
- # Construct selector and get all campaigns.
- selector = {
- 'fields': ['Id', 'Name', 'Status']
- }
- campaigns = campaign_service.get(selector)
- campaign_ids = []
- if 'entries' in campaigns:
- for campaign in campaigns['entries']:
- campaign_ids.append(campaign['id'])
- else:
- print 'No campaigns were found.'
- return
-
- # Construct selector and get all changes.
- today = datetime.datetime.today()
- yesterday = today - datetime.timedelta(1)
- selector = {
- 'dateTimeRange': {
- 'min': yesterday.strftime('%Y%m%d %H%M%S'),
- 'max': today.strftime('%Y%m%d %H%M%S')
- },
- 'campaignIds': campaign_ids
- }
- account_changes = customer_sync_service.get(selector)
-
- # Display results.
- if account_changes:
- if 'lastChangeTimestamp' in account_changes:
- print 'Most recent changes: %s' % account_changes['lastChangeTimestamp']
- if account_changes['changedCampaigns']:
- for data in account_changes['changedCampaigns']:
- print ('Campaign with id \'%s\' has change status \'%s\'.'
- % (data['campaignId'], data['campaignChangeStatus']))
- if (data['campaignChangeStatus'] != 'NEW' and
- data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'):
- print ' Added ad extensions: %s' % data.get('addedAdExtensions')
- print ' Removed ad extensions: %s' % data.get('deletedAdExtensions')
- print (' Added campaign criteria: %s'
- % data.get('addedCampaignCriteria'))
- print (' Removed campaign criteria: %s'
- % data.get('deletedCampaignCriteria'))
- if data.get('changedAdGroups'):
- for ad_group_data in data['changedAdGroups']:
- print (' Ad group with id \'%s\' has change status \'%s\'.'
- % (ad_group_data['adGroupId'],
- ad_group_data['adGroupChangeStatus']))
- if ad_group_data['adGroupChangeStatus'] != 'NEW':
- print ' Changed ads: %s' % ad_group_data['changedAds']
- print (' Changed criteria: %s'
- % ad_group_data['changedCriteria'])
- print (' Removed criteria: %s'
- % ad_group_data['deletedCriteria'])
- else:
- print 'No changes were found.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
- main(adwords_client)
diff --git a/examples/adwords/v201502/account_management/get_account_hierarchy.py b/examples/adwords/v201502/account_management/get_account_hierarchy.py
deleted file mode 100755
index 78606269..00000000
--- a/examples/adwords/v201502/account_management/get_account_hierarchy.py
+++ /dev/null
@@ -1,97 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets the account hierarchy under the current account.
-
-Note: this code example won't work with test accounts. See
-https://developers.google.com/adwords/api/docs/test-accounts
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ServicedAccountService.get
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-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 = '-' * depth * 2
- print '%s%s, %s' % (prefix, account['customerId'], account['name'])
- if account['customerId'] in links:
- for child_link in links[account['customerId']]:
- child_account = accounts[child_link['clientCustomerId']]
- DisplayAccountTree(child_account, accounts, links, depth + 1)
-
-
-def main(client):
- # Initialize appropriate service.
- managed_customer_service = client.GetService(
- 'ManagedCustomerService', version='v201502')
-
- # Construct selector to get all accounts.
- selector = {
- 'fields': ['CustomerId', 'Name']
- }
- # Get serviced account graph.
- graph = managed_customer_service.get(selector)
- if 'entries' in graph and graph['entries']:
- # Create map from customerId to parent and child links.
- child_links = {}
- parent_links = {}
- if 'links' in graph:
- for link in graph['links']:
- if link['managerCustomerId'] not in child_links:
- child_links[link['managerCustomerId']] = []
- child_links[link['managerCustomerId']].append(link)
- if link['clientCustomerId'] not in parent_links:
- parent_links[link['clientCustomerId']] = []
- parent_links[link['clientCustomerId']].append(link)
- # Create map from customerID to account and find root account.
- accounts = {}
- root_account = None
- for account in graph['entries']:
- accounts[account['customerId']] = account
- if account['customerId'] not in parent_links:
- root_account = account
- # Display account tree.
- if root_account:
- print 'CustomerId, Name'
- DisplayAccountTree(root_account, accounts, child_links, 0)
- else:
- print 'Unable to determine a root account'
- else:
- print 'No serviced accounts were found'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
- main(adwords_client)
diff --git a/examples/adwords/v201502/advanced_operations/__init__.py b/examples/adwords/v201502/advanced_operations/__init__.py
deleted file mode 100644
index 7e57b8b3..00000000
--- a/examples/adwords/v201502/advanced_operations/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Advanced operations examples."""
diff --git a/examples/adwords/v201502/advanced_operations/add_ad_customizer.py b/examples/adwords/v201502/advanced_operations/add_ad_customizer.py
deleted file mode 100755
index 09282e58..00000000
--- a/examples/adwords/v201502/advanced_operations/add_ad_customizer.py
+++ /dev/null
@@ -1,251 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Adds an ad customizer feed.
-
-Associates the feed with customer and adds an ad that
-uses the feed to populate dynamic data.
-
-Tags: CustomerFeedService.mutate, FeedItemService.mutate
-Tags: FeedMappingService.mutate, FeedService.mutate
-Tags: AdGroupAdService.mutate
-"""
-
-__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)',
- 'yufeng.dev@gmail.com (Yufeng Guo)')
-
-# Import appropriate classes from the client library.
-from googleads import adwords
-
-# See the Placeholder reference page for a list of all the placeholder types
-# and fields:
-# https://developers.google.com/adwords/api/docs/appendix/placeholders
-PLACEHOLDER_AD_CUSTOMIZER = '10'
-PLACEHOLDER_FIELD_INTEGER = '1'
-PLACEHOLDER_FIELD_FLOAT = '2'
-PLACEHOLDER_FIELD_PRICE = '3'
-PLACEHOLDER_FIELD_DATE = '4'
-PLACEHOLDER_FIELD_STRING = '5'
-
-ADGROUPS = [
- 'INSERT_ADGROUP_ID_HERE',
- 'INSERT_ADGROUP_ID_HERE'
-]
-
-FEEDNAME = 'INSERT_FEED_NAME_HERE'
-
-
-def main(client, adgroups):
- # Initialize appropriate services.
- ad_group_ad_service = client.GetService('AdGroupAdService', version='v201502')
- customer_feed_service = client.GetService(
- 'CustomerFeedService', version='v201502')
- feed_item_service = client.GetService('FeedItemService', version='v201502')
- feed_mapping_service = client.GetService(
- 'FeedMappingService', version='v201502')
- feed_service = client.GetService('FeedService', version='v201502')
-
- # First, create a customizer feed. One feed per account can be used for all
- # ads.
- customizer_feed = {
- 'name': FEEDNAME,
- 'attributes': [
- {'type': 'STRING', 'name': 'Name'},
- {'type': 'STRING', 'name': 'Price'},
- {'type': 'DATE_TIME', 'name': 'Date'}
- ]
- }
-
- feed_service_operation = {
- 'operator': 'ADD',
- 'operand': customizer_feed
- }
-
- response = feed_service.mutate([feed_service_operation])
-
- if response and 'value' in response:
- feed = response['value'][0]
- feed_data = {
- 'feedId': feed['id'],
- 'nameId': feed['attributes'][0]['id'],
- 'priceId': feed['attributes'][1]['id'],
- 'dateId': feed['attributes'][2]['id']
- }
- print ('Feed with name \'%s\' and ID %s was added with:'
- '\tName attribute ID %s and price attribute ID %s and date attribute'
- 'ID %s') % (feed['name'], feed['id'], feed_data['nameId'],
- feed_data['priceId'], feed_data['dateId'])
- else:
- raise Exception('No feeds were added')
-
- # Creating feed mapping to map the fields with customizer IDs.
- feed_mapping = {
- 'placeholderType': PLACEHOLDER_AD_CUSTOMIZER,
- 'feedId': feed_data['feedId'],
- 'attributeFieldMappings': [
- {
- 'feedAttributeId': feed_data['nameId'],
- 'fieldId': PLACEHOLDER_FIELD_STRING
- },
- {
- 'feedAttributeId': feed_data['priceId'],
- 'fieldId': PLACEHOLDER_FIELD_PRICE
- },
- {
- 'feedAttributeId': feed_data['dateId'],
- 'fieldId': PLACEHOLDER_FIELD_DATE
- }
- ]
- }
-
- feed_mapping_operation = {
- 'operator': 'ADD',
- 'operand': feed_mapping
- }
-
- response = feed_mapping_service.mutate([feed_mapping_operation])
-
- if response and 'value' in response:
- feed_mapping = response['value'][0]
- print ('Feed mapping with ID %s and placeholder type %s was saved for feed'
- ' with ID %s.') % (feed_mapping['feedMappingId'],
- feed_mapping['placeholderType'],
- feed_mapping['feedId'])
- else:
- raise Exception('No feed mappings were added.')
-
- # Now adding feed items -- the values we'd like to place.
- items_data = [
- {
- 'name': 'Mars',
- 'price': '$1234.56',
- 'date': '20140601 000000',
- 'adGroupId': adgroups[0]
- },
- {
- 'name': 'Venus',
- 'price': '$1450.00',
- 'date': '20140615 120000',
- 'adGroupId': adgroups[1]
- }
- ]
-
- feed_items = [{'feedId': feed_data['feedId'],
- 'adGroupTargeting': {
- 'TargetingAdGroupId': item['adGroupId']
- },
- 'attributeValues': [
- {
- 'feedAttributeId': feed_data['nameId'],
- 'stringValue': item['name']
- },
- {
- 'feedAttributeId': feed_data['priceId'],
- 'stringValue': item['price']
- },
- {
- 'feedAttributeId': feed_data['dateId'],
- 'stringValue': item['date']
- }
- ]} for item in items_data]
-
- feed_item_operations = [{
- 'operator': 'ADD',
- 'operand': feed_item
- } for feed_item in feed_items]
-
- response = feed_item_service.mutate(feed_item_operations)
-
- if response and 'value' in response:
- for feed_item in response['value']:
- print 'Feed item with ID %s was added.' % feed_item['feedItemId']
- else:
- raise Exception('No feed items were added.')
-
- # Finally, creating a customer (account-level) feed with a matching function
- # that determines when to use this feed. For this case we use the "IDENTITY"
- # matching function that is always 'true' just to associate this feed with
- # the customer. The targeting is done within the feed items using the
- # :campaign_targeting, :ad_group_targeting, or :keyword_targeting attributes.
- matching_function = {
- 'operator': 'IDENTITY',
- 'lhsOperand': [
- {
- 'xsi_type': 'ConstantOperand',
- 'type': 'BOOLEAN',
- 'booleanValue': 'true'
- }
- ]
- }
-
- customer_feed = {
- 'feedId': feed_data['feedId'],
- 'matchingFunction': matching_function,
- 'placeholderTypes': [PLACEHOLDER_AD_CUSTOMIZER]
- }
-
- customer_feed_operation = {
- 'operator': 'ADD',
- 'operand': customer_feed
- }
-
- response = customer_feed_service.mutate([customer_feed_operation])
-
- if response and 'value' in response:
- feed = response['value'][0]
- print 'Customer feed with ID %s was added.' % feed['feedId']
- else:
- raise Exception('No customer feeds were added.')
-
- # All set! We can now create ads with customizations.
- text_ad = {
- 'xsi_type': 'TextAd',
- 'headline': 'Luxury Cruise to {=%s.Name}' % FEEDNAME,
- 'description1': 'Only {=%s.Price}' % FEEDNAME,
- 'description2': 'Offer ends in {=countdown(%s.Date)}!' % FEEDNAME,
- 'finalUrls': ['http://www.example.com'],
- 'displayUrl': 'www.example.com'
- }
-
- # We add the same ad to both ad groups. When they serve, they will show
- # different values, since they match different feed items.
- operations = [{
- 'operator': 'ADD',
- 'operand': {
- 'adGroupId': adgroup,
- 'ad': text_ad
- }
- } for adgroup in adgroups]
-
- print operations
-
- response = ad_group_ad_service.mutate(operations)
-
- print '===ad group ad service==='
- print response
-
- if response and 'value' in response:
- for ad in response['value']:
- print ('\tCreated an ad with ID \'%s\', type \'%s\', and status \'%s\'.'
- % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status']))
- else:
- raise Exception('No ads were added.')
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
- main(adwords_client, ADGROUPS)
diff --git a/examples/adwords/v201502/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201502/advanced_operations/add_ad_group_bid_modifier.py
deleted file mode 100755
index c1de6f8c..00000000
--- a/examples/adwords/v201502/advanced_operations/add_ad_group_bid_modifier.py
+++ /dev/null
@@ -1,78 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Adds an ad group level mobile bid modifier override for a campaign.
-
-To get your ad groups, run get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupBidModifierService.mutate
-"""
-
-__author__ = 'Joseph DiLallo'
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-BID_MODIFIER = 'INSERT_BID_MODIFIER_HERE'
-
-
-def main(client, ad_group_id, bid_modifier):
- # Initialize appropriate service.
- ad_group_bid_modifier_service = client.GetService(
- 'AdGroupBidModifierService', version='v201502')
-
- # Mobile criterion ID.
- criterion_id = '30001'
-
- # Prepare to add an ad group level override.
- operation = {
- # Use 'ADD' to add a new modifier and 'SET' to update an existing one. A
- # modifier can be removed with the 'REMOVE' operator.
- 'operator': 'ADD',
- 'operand': {
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Platform',
- 'id': criterion_id
- },
- 'bidModifier': bid_modifier
- }
- }
-
- # Add ad group level mobile bid modifier.
- response = ad_group_bid_modifier_service.mutate([operation])
- if response and response['value']:
- modifier = response['value'][0]
- value = modifier['bidModifier'] if 'bidModifier' in modifier else 'unset'
- print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s was updated with '
- 'ad group level modifier: %s' %
- (modifier['campaignId'], modifier['adGroupId'],
- modifier['criterion']['id'], value))
- else:
- print 'No modifiers were added.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID, BID_MODIFIER)
diff --git a/examples/adwords/v201502/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201502/advanced_operations/add_click_to_download_ad.py
deleted file mode 100755
index a9aaeffe..00000000
--- a/examples/adwords/v201502/advanced_operations/add_click_to_download_ad.py
+++ /dev/null
@@ -1,114 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates a click-to-download ad in a given ad group.
-
-This type of ad is also known as an app promotion ad. To list ad groups, run
-get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupAdService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = 'Joseph DiLallo'
-
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Initialize appropriate service.
- ad_group_ad_service = client.GetService('AdGroupAdService', version='v201502')
-
- # Create the template elements for the ad. You can refer to
- # https://developers.google.com/adwords/api/docs/appendix/templateads
- # for the list of available template fields.
- ad_data = {
- 'uniqueName': 'adData',
- 'fields': [
- {
- 'name': 'headline',
- 'fieldText': 'Enjoy your drive in Mars',
- 'type': 'TEXT'
- },
- {
- 'name': 'description1',
- 'fieldText': 'Realistic physics simulation',
- 'type': 'TEXT'
- },
- {
- 'name': 'description2',
- 'fieldText': 'Race against players online',
- 'type': 'TEXT'
- },
- {
- 'name': 'appId',
- 'fieldText': 'com.example.demogame',
- 'type': 'TEXT'
- },
- {
- 'name': 'appStore',
- 'fieldText': '2',
- 'type': 'ENUM'
- }
- ]
- }
-
- # Create click to download ad.
- click_to_download_app_ad = {
- 'xsi_type': 'TemplateAd',
- 'name': 'Ad for demo game',
- 'templateId': '353',
- 'finalUrls': [
- 'http://play.google.com/store/apps/details?id=com.example.demogame'
- ],
- 'displayUrl': 'play.google.com',
- 'templateElements': [ad_data]
- }
-
- # Create ad group ad.
- ad_group_ad = {
- 'adGroupId': ad_group_id,
- 'ad': click_to_download_app_ad,
- # Optional.
- 'status': 'PAUSED'
- }
-
- # Add ad.
- ads = ad_group_ad_service.mutate([
- {'operator': 'ADD', 'operand': ad_group_ad}
- ])
- # Display results.
- if 'value' in ads:
- for ad in ads['value']:
- print ('Added new click-to-download ad to ad group ID \'%s\' '
- 'with URL \'%s\'.' % (ad['ad']['id'], ad['ad']['finalUrls'][0]))
- else:
- print 'No ads were added.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201502/advanced_operations/add_text_ad_with_upgraded_urls.py b/examples/adwords/v201502/advanced_operations/add_text_ad_with_upgraded_urls.py
deleted file mode 100755
index a3032cb2..00000000
--- a/examples/adwords/v201502/advanced_operations/add_text_ad_with_upgraded_urls.py
+++ /dev/null
@@ -1,114 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds a text add that uses advanced features of upgraded URLS.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupAdService.mutate
-"""
-
-__author__ = 'Mark Saniscalchi'
-
-from googleads import adwords
-from googleads import errors
-
-
-ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE'
-
-
-def main(client, adgroup_id):
- # Initialize appropriate service.
- adgroup_ad_service = client.GetService('AdGroupAdService', version='v201502')
-
- # Create the text ad
- text_ad = {
- 'xsi_type': 'TextAd',
- 'headline': 'Luxury Cruise to Mars',
- 'description1': 'Visit the Red Planet in style.',
- 'description2': 'Low-gravity fun for everyone!',
- 'displayUrl': 'www.example.com',
- # Specify a tracking URL for 3rd party tracking provider. You may specify
- # one at customer, campaign, ad group, ad, criterion or feed item levels.
- 'trackingUrlTemplate': ('http://tracker.example.com/?season={_season}'
- '&promocode={_promocode}&u={lpurl}'),
- 'urlCustomParameters': {
- 'parameters': [
- # Since your tracking URL has two custom parameters, provide
- # their values too. This can be provided at campaign, ad group,
- # ad, criterion, or feed item levels.
- {
- 'key': 'season',
- 'value': 'christmas'
- },
- {
- 'key': 'promocode',
- 'value': 'NYC123'
- }
- ]
- },
- # Specify a list of final URLs. This field cannot be set if URL
- # field is set, or finalUrls is unset. This may be specified at ad,
- # criterion, and feed item levels.
- 'finalUrls': [
- 'http://www.example.com/cruise/space/',
- 'http://www.example.com/locations/mars/'
- ],
- # Specify a list of final mobile URLs. This field cannot be set if URL
- # field is set, or finalUrls is unset. This may be specified at ad,
- # criterion, and feed item levels.
- 'finalMobileUrls': [
- 'http://mobile.example.com/cruise/space/',
- 'http://mobile.example.com/locations/mars/'
- ]
- }
-
- text_adgroup_ad = {
- 'adGroupId': adgroup_id,
- 'ad': text_ad,
- # Optional: Set the status.
- 'status': 'PAUSED'
- }
-
- operations = [{
- 'operator': 'ADD',
- 'operand': text_adgroup_ad
- }]
-
- response = adgroup_ad_service.mutate(operations)
-
- if 'value' in response:
- for adgroup_ad in response['value']:
- print ('AdGroupAd with ID %s and display URL \'%s\'was added.'
- % (adgroup_ad['ad']['id'], adgroup_ad['ad']['displayUrl']))
- print 'Upgraded URL properties:'
- print 'Final Urls: %s' % adgroup_ad['ad']['finalUrls']
- print 'Final Mobile URLs: %s' % adgroup_ad['ad']['finalMobileUrls']
- print ('Tracking URL template: %s'
- % adgroup_ad['ad']['trackingUrlTemplate'])
- print 'Custom parameters: %s' % adgroup_ad['ad']['urlCustomParameters']
- else:
- raise errors.GoogleAdsError('Failed to create AdGroupAd.')
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, ADGROUP_ID)
diff --git a/examples/adwords/v201502/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201502/advanced_operations/find_and_remove_criteria_from_shared_set.py
deleted file mode 100755
index c4c46225..00000000
--- a/examples/adwords/v201502/advanced_operations/find_and_remove_criteria_from_shared_set.py
+++ /dev/null
@@ -1,158 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Demonstrates how to find and remove shared sets/shared set criterions.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignSharedSetService.get, SharedCriterionService.get,
- SharedCriterionService.mutate
-"""
-
-__author__ = 'Mark Saniscalchi'
-
-from googleads import adwords
-
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-PAGE_SIZE = 500
-
-
-def main(client, campaign_id):
- # Initialize appropriate services.
- shared_criterion_service = client.GetService('SharedCriterionService',
- version='v201502')
- campaign_shared_set_service = client.GetService('CampaignSharedSetService',
- version='v201502')
-
- shared_set_ids = []
- criterion_ids = []
-
- # First, retrieve all shared sets associated with the campaign.
-
- # Create selector for shared sets to:
- # - filter by campaign ID,
- # - filter by shared set type.
- selector = {
- 'fields': ['SharedSetId', 'CampaignId', 'SharedSetName', 'SharedSetType',
- 'Status'],
- 'predicates': [
- {
- 'field': 'CampaignId',
- 'operator': 'EQUALS',
- 'values': [campaign_id]
- },
- {
- 'field': 'SharedSetType',
- 'operator': 'IN',
- 'values': ['NEGATIVE_KEYWORDS', 'NEGATIVE_PLACEMENTS']
- }
- ],
- 'paging': {
- 'startIndex': 0,
- 'numberResults': PAGE_SIZE
- }
- }
-
- # Set initial values:
- offset = 0
- page = {'totalNumEntries': 1}
-
- while page['totalNumEntries'] > offset:
- page = campaign_shared_set_service.get(selector)
- if page['entries']:
- for shared_set in page['entries']:
- print 'Campaign shared set ID %d and name "%s"' % (
- shared_set['sharedSetId'], shared_set['sharedSetName']
- )
- shared_set_ids.append(shared_set['sharedSetId'])
- # Increment values to request the next page.
- offset += PAGE_SIZE
- selector['paging']['startIndex'] = offset
-
- # Next, retrieve criterion IDs for all found shared sets.
- selector = {
- 'fields': ['SharedSetId', 'Id', 'KeywordText', 'KeywordMatchType',
- 'PlacementUrl'],
- 'predicates': [
- {
- 'field': 'SharedSetId',
- 'operator': 'IN',
- 'values': shared_set_ids
- }
- ],
- 'paging': {
- 'startIndex': 0,
- 'numberResults': PAGE_SIZE
- }
- }
-
- # Set initial values:
- offset = 0
- page = {'totalNumEntries': 1}
-
- while page['totalNumEntries'] > offset:
- page = shared_criterion_service.get(selector)
- if page['entries']:
- for shared_criterion in page['entries']:
- if shared_criterion['criterion']['type'] == 'KEYWORD':
- print ('Shared negative keyword with ID %d and text "%s" was'
- 'found.' % (shared_criterion['criterion']['id'],
- shared_criterion['criterion']['text']))
- elif shared_criterion['criterion']['type'] == 'PLACEMENT':
- print ('Shared negative placement with ID %d and url "%s" was'
- 'found.' % (shared_criterion['criterion']['id'],
- shared_criterion['criterion']['url']))
- else:
- print 'Shared criterion with ID %d was found.' % (
- shared_criterion['criterion']['id'],
- )
- criterion_ids.append({
- 'sharedSetId': shared_criterion['sharedSetId'],
- 'criterionId': shared_criterion['criterion']['id']
- })
- # Increment values to request the next page.
- offset += PAGE_SIZE
- selector['paging']['startIndex'] = offset
-
- # Finally, remove the criteria.
- operations = [
- {
- 'operator': 'REMOVE',
- 'operand': {
- 'criterion': {'id': criterion['criterionId']},
- 'sharedSetId': criterion['sharedSetId']
- }
- } for criterion in criterion_ids
- ]
-
- response = shared_criterion_service.mutate(operations)
- if 'value' in response:
- for criterion in response['value']:
- print ('Criterion ID %d was successfully removed from shared set ID'
- '%d.' % (criterion['criterion']['id'], criterion['sharedSetId']))
- else:
- print 'No shared criteria were removed.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201502/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201502/advanced_operations/get_ad_group_bid_modifier.py
deleted file mode 100755
index 88b39a7a..00000000
--- a/examples/adwords/v201502/advanced_operations/get_ad_group_bid_modifier.py
+++ /dev/null
@@ -1,76 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Retrieves the ad group level bid modifiers for a campaign.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupBidModifierService.get
-"""
-
-__author__ = 'Joseph DiLallo'
-
-from googleads import adwords
-
-
-PAGE_SIZE = 500
-
-
-def main(client):
- # Initialize appropriate service.
- ad_group_bid_modifier_service = client.GetService(
- 'AdGroupBidModifierService', version='v201502')
-
- # Get all ad group bid modifiers for the campaign.
- selector = {
- 'fields': ['CampaignId', 'AdGroupId', 'BidModifier', 'Id'],
- 'paging': {
- 'startIndex': '0',
- 'numberResults': str(PAGE_SIZE)
- }
- }
-
- # Set initial values.
- offset, page = 0, {}
- more_results = True
-
- while more_results:
- page = ad_group_bid_modifier_service.get(selector)
- if page['entries']:
- for modifier in page['entries']:
- value = (modifier['bidModifier'] if 'bidModifier' in modifier
- else 'unset')
- print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s has ad group '
- 'level modifier: %s' %
- (modifier['campaignId'], modifier['adGroupId'],
- modifier['criterion']['id'], value))
-
- # Increment values to request the next page.
- offset += PAGE_SIZE
- selector['paging']['startIndex'] = str(offset)
- else:
- print 'No ad group bid modifiers returned.'
- more_results = int(page['totalNumEntries']) > offset
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201502/advanced_operations/upload_offline_conversions.py b/examples/adwords/v201502/advanced_operations/upload_offline_conversions.py
deleted file mode 100755
index fafbcca2..00000000
--- a/examples/adwords/v201502/advanced_operations/upload_offline_conversions.py
+++ /dev/null
@@ -1,101 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Imports offline conversion values for specific clicks into your account.
-
-To get the Google Click ID for a click, run a CLICK_PERFORMANCE_REPORT.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ConversionTrackerService.mutate, OfflineConversionFeedService.mutate
-"""
-
-__author__ = 'Joseph DiLallo'
-
-from googleads import adwords
-
-
-CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE'
-# Your click ID must be less than 30 days old.
-CLICK_ID = 'INSERT_GOOGLE_CLICK_ID_HERE'
-# The conversion time must be more recent than the time of the click.
-CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE'
-CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE'
-
-
-def main(client, conversion_name, click_id, conversion_time, conversion_value):
- # Initialize appropriate services.
- conversion_tracker_service = client.GetService('ConversionTrackerService',
- version='v201502')
-
- offline_conversion_feed_service = client.GetService(
- 'OfflineConversionFeedService', version='v201502')
-
- # Once created, this entry will be visible under
- # Tools and Analysis->Conversion and will have "Source = Import".
- upload_conversion = {
- 'xsi_type': 'UploadConversion',
- 'category': 'PAGE_VIEW',
- 'name': conversion_name,
- 'viewthroughLookbackWindow': '30',
- 'ctcLookbackWindow': '90'
- }
-
- upload_conversion_operation = {
- 'operator': 'ADD',
- 'operand': upload_conversion
- }
-
- response = conversion_tracker_service.mutate(
- [upload_conversion_operation])
- new_upload_conversion = response['value']
-
- print ('New upload conversion type with name \'%s\' and ID \'%s\' was '
- 'created.' % (new_upload_conversion['name'],
- new_upload_conversion['id']))
-
- # Associate offline conversions with the upload conversion we created.
- feed = {
- 'conversionName': conversion_name,
- 'conversionTime': conversion_time,
- 'conversionValue': conversion_value,
- 'googleClickId': click_id
- }
-
- offline_conversion_operation = {
- 'operator': 'ADD',
- 'operand': feed
- }
-
- offline_conversion_response = offline_conversion_feed_service.mutate(
- [offline_conversion_operation])
- new_feed = offline_conversion_response['value']
-
- print ('Uploaded offline conversion value of \'%s\' for Google Click ID '
- '\'%s\' to \'%s\'.' % (new_feed['conversionValue'],
- new_feed['googleClickId'],
- new_feed['conversionName']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CONVERSION_NAME, CLICK_ID, CONVERSION_TIME,
- CONVERSION_VALUE)
diff --git a/examples/adwords/v201502/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201502/advanced_operations/use_shared_bidding_strategy.py
deleted file mode 100755
index 8e0fd39b..00000000
--- a/examples/adwords/v201502/advanced_operations/use_shared_bidding_strategy.py
+++ /dev/null
@@ -1,176 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Adds a Shared Bidding Strategy and uses it to construct a campaign.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: BiddingStrategyService.mutate
-Tags: BudgetService.mutate, CampaignService.mutate
-"""
-
-__author__ = 'Joseph DiLallo'
-
-import uuid
-
-from googleads import adwords
-
-
-# Enter a shared budget ID to re-use an existing budget or leave as None to
-# create a new one.
-BUDGET_ID = None
-
-
-def main(client, budget_id):
- bidding_strategy = CreateBiddingStrategy(client)
-
- if budget_id is None:
- budget = CreateSharedBudget(client)
- budget_id = budget['budgetId']
-
- CreateCampaignWithBiddingStrategy(client, bidding_strategy['id'], budget_id)
-
-
-def CreateBiddingStrategy(client):
- """Creates a bidding strategy object.
-
- Args:
- client: AdWordsClient the client to run the example with.
-
- Returns:
- dict An object representing a bidding strategy.
- """
- # Initialize appropriate service.
- bidding_strategy_service = client.GetService(
- 'BiddingStrategyService', version='v201502')
-
- # Create a shared bidding strategy.
- shared_bidding_strategy = {
- 'name': 'Maximize Clicks %s' % uuid.uuid4(),
- 'biddingScheme': {
- 'xsi_type': 'TargetSpendBiddingScheme',
- # Optionally set additional bidding scheme parameters.
- 'bidCeiling': {
- 'microAmount': '2000000'
- }
- }
- }
-
- # Create operation.
- operation = {
- 'operator': 'ADD',
- 'operand': shared_bidding_strategy
- }
-
- response = bidding_strategy_service.mutate([operation])
- new_bidding_strategy = response['value'][0]
-
- print ('Shared bidding strategy with name \'%s\' and ID \'%s\' of type \'%s\''
- 'was created.' %
- (new_bidding_strategy['name'], new_bidding_strategy['id'],
- new_bidding_strategy['biddingScheme']['BiddingScheme.Type']))
-
- return new_bidding_strategy
-
-
-def CreateSharedBudget(client):
- """Creates an explicit budget to be used only to create the Campaign.
-
- Args:
- client: AdWordsClient the client to run the example with.
-
- Returns:
- dict An object representing a shared budget.
- """
- # Initialize appropriate service.
- budget_service = client.GetService('BudgetService', version='v201502')
-
- # Create a shared budget
- budget = {
- 'name': 'Shared Interplanetary Budget #%s' % uuid.uuid4(),
- 'period': 'DAILY',
- 'amount': {
- 'microAmount': '2000000'
- },
- 'deliveryMethod': 'STANDARD',
- 'isExplicitlyShared': 'true'
- }
-
- # Create operation.
- operation = {
- 'operator': 'ADD',
- 'operand': budget
- }
-
- response = budget_service.mutate([operation])
- return response['value'][0]
-
-
-def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id):
- """Create a Campaign with a Shared Bidding Strategy.
-
- Args:
- client: AdWordsClient the client to run the example with.
- bidding_strategy_id: string the bidding strategy ID to use.
- budget_id: string the shared budget ID to use.
-
- Returns:
- dict An object representing a campaign.
- """
- # Initialize appropriate service.
- campaign_service = client.GetService('CampaignService', version='v201502')
-
- # Create campaign.
- campaign = {
- 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(),
- 'budget': {
- 'budgetId': budget_id
- },
- 'biddingStrategyConfiguration': {
- 'biddingStrategyId': bidding_strategy_id
- },
- 'advertisingChannelType': 'SEARCH',
- 'networkSetting': {
- 'targetGoogleSearch': 'true',
- 'targetSearchNetwork': 'true',
- 'targetContentNetwork': 'true'
- }
- }
-
- # Create operation.
- operation = {
- 'operator': 'ADD',
- 'operand': campaign
- }
-
- response = campaign_service.mutate([operation])
- new_campaign = response['value'][0]
-
- print ('Campaign with name \'%s\', ID \'%s\' and bidding scheme ID \'%s\' '
- 'was created.' %
- (new_campaign['name'], new_campaign['id'],
- new_campaign['biddingStrategyConfiguration']['biddingStrategyId']))
-
- return new_campaign
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
- main(adwords_client, BUDGET_ID)
diff --git a/examples/adwords/v201502/basic_operations/__init__.py b/examples/adwords/v201502/basic_operations/__init__.py
deleted file mode 100644
index 80acbea9..00000000
--- a/examples/adwords/v201502/basic_operations/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Basic operations examples."""
diff --git a/examples/adwords/v201502/basic_operations/add_ad_groups.py b/examples/adwords/v201502/basic_operations/add_ad_groups.py
deleted file mode 100755
index b8eadc57..00000000
--- a/examples/adwords/v201502/basic_operations/add_ad_groups.py
+++ /dev/null
@@ -1,116 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds ad groups to a given campaign.
-
-To get ad groups, run get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README..
-
-Tags: AdGroupService.mutate
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-import uuid
-
-from googleads import adwords
-
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-
-
-def main(client, campaign_id):
- # Initialize appropriate service.
- ad_group_service = client.GetService('AdGroupService', version='v201502')
-
- # Construct operations and add ad groups.
- operations = [{
- 'operator': 'ADD',
- 'operand': {
- 'campaignId': campaign_id,
- 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(),
- 'status': 'ENABLED',
- 'biddingStrategyConfiguration': {
- 'bids': [
- {
- 'xsi_type': 'CpcBid',
- 'bid': {
- 'microAmount': '1000000'
- },
- }
- ]
- },
- 'settings': [
- {
- # Targeting restriction settings - these settings only affect
- # serving for the Display Network.
- 'xsi_type': 'TargetingSetting',
- 'details': [
- # Restricting to serve ads that match your ad group
- # placements. This is equivalent to choosing
- # "Target and bid" in the UI.
- {
- 'xsi_type': 'TargetingSettingDetail',
- 'criterionTypeGroup': 'PLACEMENT',
- 'targetAll': 'false',
- },
- # Using your ad group verticals only for bidding. This is
- # equivalent to choosing "Bid only" in the UI.
- {
- 'xsi_type': 'TargetingSettingDetail',
- 'criterionTypeGroup': 'VERTICAL',
- 'targetAll': 'true',
- },
- ]
- }
- ]
- }
- }, {
- 'operator': 'ADD',
- 'operand': {
- 'campaignId': campaign_id,
- 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(),
- 'status': 'ENABLED',
- 'biddingStrategyConfiguration': {
- 'bids': [
- {
- 'xsi_type': 'CpcBid',
- 'bid': {
- 'microAmount': '1000000'
- }
- }
- ]
- }
- }
- }]
- ad_groups = ad_group_service.mutate(operations)
-
- # Display results.
- for ad_group in ad_groups['value']:
- print ('Ad group with name \'%s\' and id \'%s\' was added.'
- % (ad_group['name'], ad_group['id']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201502/basic_operations/add_campaigns.py b/examples/adwords/v201502/basic_operations/add_campaigns.py
deleted file mode 100755
index c2c05c27..00000000
--- a/examples/adwords/v201502/basic_operations/add_campaigns.py
+++ /dev/null
@@ -1,131 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds campaigns.
-
-To get campaigns, run get_campaigns.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignService.mutate
-Tags: BudgetService.mutate
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-import datetime
-import uuid
-
-from googleads import adwords
-
-
-def main(client):
- # Initialize appropriate services.
- campaign_service = client.GetService('CampaignService', version='v201502')
- budget_service = client.GetService('BudgetService', version='v201502')
-
- # Create a budget, which can be shared by multiple campaigns.
- budget = {
- 'name': 'Interplanetary budget #%s' % uuid.uuid4(),
- 'amount': {
- 'microAmount': '50000000'
- },
- 'deliveryMethod': 'STANDARD',
- 'period': 'DAILY'
- }
-
- budget_operations = [{
- 'operator': 'ADD',
- 'operand': budget
- }]
-
- # Add the budget.
- budget_id = budget_service.mutate(budget_operations)['value'][0][
- 'budgetId']
-
- # Construct operations and add campaigns.
- operations = [{
- 'operator': 'ADD',
- 'operand': {
- 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(),
- 'status': 'PAUSED',
- 'advertisingChannelType': 'SEARCH',
- 'biddingStrategyConfiguration': {
- 'biddingStrategyType': 'MANUAL_CPC',
- },
- 'endDate': (datetime.datetime.now() +
- datetime.timedelta(365)).strftime('%Y%m%d'),
- # Note that only the budgetId is required
- 'budget': {
- 'budgetId': budget_id
- },
- 'networkSetting': {
- 'targetGoogleSearch': 'true',
- 'targetSearchNetwork': 'true',
- 'targetContentNetwork': 'false',
- 'targetPartnerSearchNetwork': 'false'
- },
- # Optional fields
- 'startDate': (datetime.datetime.now() +
- datetime.timedelta(1)).strftime('%Y%m%d'),
- 'adServingOptimizationStatus': 'ROTATE',
- 'frequencyCap': {
- 'impressions': '5',
- 'timeUnit': 'DAY',
- 'level': 'ADGROUP'
- },
- 'settings': [
- {
- 'xsi_type': 'GeoTargetTypeSetting',
- 'positiveGeoTargetType': 'DONT_CARE',
- 'negativeGeoTargetType': 'DONT_CARE'
- }
- ]
- }
- }, {
- 'operator': 'ADD',
- 'operand': {
- 'name': 'Interplanetary Cruise banner #%s' % uuid.uuid4(),
- 'status': 'PAUSED',
- 'biddingStrategyConfiguration': {
- 'biddingStrategyType': 'MANUAL_CPC'
- },
- 'endDate': (datetime.datetime.now() +
- datetime.timedelta(365)).strftime('%Y%m%d'),
- # Note that only the budgetId is required
- 'budget': {
- 'budgetId': budget_id
- },
- 'advertisingChannelType': 'DISPLAY'
- }
- }]
- campaigns = campaign_service.mutate(operations)
-
- # Display results.
- for campaign in campaigns['value']:
- print ('Campaign with name \'%s\' and id \'%s\' was added.'
- % (campaign['name'], campaign['id']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201502/basic_operations/add_keywords.py b/examples/adwords/v201502/basic_operations/add_keywords.py
deleted file mode 100755
index f87b2b52..00000000
--- a/examples/adwords/v201502/basic_operations/add_keywords.py
+++ /dev/null
@@ -1,97 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds ad group criteria to an ad group.
-
-To get ad groups, run get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupCriterionService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Initialize appropriate service.
- ad_group_criterion_service = client.GetService(
- 'AdGroupCriterionService', version='v201502')
-
- # Construct keyword ad group criterion object.
- keyword1 = {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Keyword',
- 'matchType': 'BROAD',
- 'text': 'mars'
- },
- # These fields are optional.
- 'userStatus': 'PAUSED',
- 'finalUrls': {
- 'urls': ['http://example.com/mars']
- }
- }
-
- keyword2 = {
- 'xsi_type': 'NegativeAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Keyword',
- 'matchType': 'EXACT',
- 'text': 'pluto'
- }
- }
-
- # Construct operations and add ad group criteria.
- operations = [
- {
- 'operator': 'ADD',
- 'operand': keyword1
- },
- {
- 'operator': 'ADD',
- 'operand': keyword2
- }
- ]
- ad_group_criteria = ad_group_criterion_service.mutate(
- operations)['value']
-
- # Display results.
- for criterion in ad_group_criteria:
- print ('Keyword ad group criterion with ad group id \'%s\', criterion id '
- '\'%s\', text \'%s\', and match type \'%s\' was added.'
- % (criterion['adGroupId'], criterion['criterion']['id'],
- criterion['criterion']['text'],
- criterion['criterion']['matchType']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201502/basic_operations/add_text_ads.py b/examples/adwords/v201502/basic_operations/add_text_ads.py
deleted file mode 100755
index 2f32332d..00000000
--- a/examples/adwords/v201502/basic_operations/add_text_ads.py
+++ /dev/null
@@ -1,98 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds several text ads to a given ad group.
-
-To get ad_group_id, run get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupAdService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Initialize appropriate service.
- ad_group_ad_service = client.GetService('AdGroupAdService', version='v201502')
-
- # Construct operations and add ads.
- # If needed, you could specify an exemption request here, e.g.:
- # 'exemptionRequests': [{
- # # This comes back in a PolicyViolationError.
- # 'key' {
- # 'policyName': '...',
- # 'violatingText': '...'
- # }
- # }]
- operations = [
- {
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'AdGroupAd',
- 'adGroupId': ad_group_id,
- 'ad': {
- 'xsi_type': 'TextAd',
- 'finalUrls': ['http://www.example.com'],
- 'displayUrl': 'example.com',
- 'description1': 'Visit the Red Planet in style.',
- 'description2': 'Low-gravity fun for everyone!',
- 'headline': 'Luxury Cruise to Mars'
- },
- # Optional fields.
- 'status': 'PAUSED'
- }
- },
- {
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'AdGroupAd',
- 'adGroupId': ad_group_id,
- 'ad': {
- 'xsi_type': 'TextAd',
- 'finalUrls': ['http://www.example.com'],
- 'displayUrl': 'example.com',
- 'description1': 'Enjoy your stay at Red Planet.',
- 'description2': 'Buy your tickets now!',
- 'headline': 'Luxury Cruise to Mars'
- }
- }
- }
- ]
- ads = ad_group_ad_service.mutate(operations)
-
- # Display results.
- for ad in ads['value']:
- print ('Ad with id \'%s\' and of type \'%s\' was added.'
- % (ad['ad']['id'], ad['ad']['Ad.Type']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201502/basic_operations/get_ad_groups.py b/examples/adwords/v201502/basic_operations/get_ad_groups.py
deleted file mode 100755
index 4cfc1add..00000000
--- a/examples/adwords/v201502/basic_operations/get_ad_groups.py
+++ /dev/null
@@ -1,80 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all ad groups for a given campaign.
-
-To add an ad group, run add_ad_group.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupService.get
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-PAGE_SIZE = 500
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-
-
-def main(client, campaign_id):
- # Initialize appropriate service.
- ad_group_service = client.GetService('AdGroupService', version='v201502')
-
- # Construct selector and get all ad groups.
- offset = 0
- selector = {
- 'fields': ['Id', 'Name', 'Status'],
- 'predicates': [
- {
- 'field': 'CampaignId',
- 'operator': 'EQUALS',
- 'values': [campaign_id]
- }
- ],
- 'paging': {
- 'startIndex': str(offset),
- 'numberResults': str(PAGE_SIZE)
- }
- }
- more_pages = True
- while more_pages:
- page = ad_group_service.get(selector)
-
- # Display results.
- if 'entries' in page:
- for ad_group in page['entries']:
- print ('Ad group with name \'%s\', id \'%s\' and status \'%s\' was '
- 'found.' % (ad_group['name'], ad_group['id'],
- ad_group['status']))
- else:
- print 'No ad groups were found.'
- offset += PAGE_SIZE
- selector['paging']['startIndex'] = str(offset)
- more_pages = offset < int(page['totalNumEntries'])
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201502/basic_operations/get_campaigns.py b/examples/adwords/v201502/basic_operations/get_campaigns.py
deleted file mode 100755
index 8631c5fe..00000000
--- a/examples/adwords/v201502/basic_operations/get_campaigns.py
+++ /dev/null
@@ -1,77 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all campaigns.
-
-To add a campaign, run add_campaign.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignService.get
-"""
-
-__author__ = 'Joseph DiLallo'
-
-import logging
-import time
-
-from googleads import adwords
-
-logging.basicConfig(level=logging.INFO)
-logging.getLogger('suds.transport').setLevel(logging.DEBUG)
-
-
-PAGE_SIZE = 100
-
-
-def main(client):
- # Initialize appropriate service.
- campaign_service = client.GetService('CampaignService', version='v201502')
-
- # Construct selector and get all campaigns.
- offset = 0
- selector = {
- 'fields': ['Id', 'Name', 'Status'],
- 'paging': {
- 'startIndex': str(offset),
- 'numberResults': str(PAGE_SIZE)
- }
- }
-
- more_pages = True
- while more_pages:
- page = campaign_service.get(selector)
-
- # Display results.
- if 'entries' in page:
- for campaign in page['entries']:
- print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was '
- 'found.' % (campaign['id'], campaign['name'],
- campaign['status']))
- else:
- print 'No campaigns were found.'
- offset += PAGE_SIZE
- selector['paging']['startIndex'] = str(offset)
- more_pages = offset < int(page['totalNumEntries'])
- time.sleep(1)
-
-
-if __name__ == '__main__':
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
- main(adwords_client)
diff --git a/examples/adwords/v201502/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201502/basic_operations/get_campaigns_with_awql.py
deleted file mode 100755
index 3d1f3c99..00000000
--- a/examples/adwords/v201502/basic_operations/get_campaigns_with_awql.py
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all campaigns with AWQL.
-
-To add a campaign, run add_campaign.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignService.query
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-import time
-
-from googleads import adwords
-
-
-PAGE_SIZE = 100
-
-
-def main(client):
- # Initialize appropriate service.
- campaign_service = client.GetService('CampaignService', version='v201502')
-
- # Construct query and get all campaigns.
- offset = 0
- query = 'SELECT Id, Name, Status ORDER BY Name'
-
- more_pages = True
- while more_pages:
- page = campaign_service.query(query + ' LIMIT %s, %s' % (offset, PAGE_SIZE))
-
- # Display results.
- if 'entries' in page:
- for campaign in page['entries']:
- print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was '
- 'found.' % (campaign['id'], campaign['name'],
- campaign['status']))
- else:
- print 'No campaigns were found.'
- offset += PAGE_SIZE
- more_pages = offset < int(page['totalNumEntries'])
- time.sleep(1)
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
- main(adwords_client)
diff --git a/examples/adwords/v201502/basic_operations/get_keywords.py b/examples/adwords/v201502/basic_operations/get_keywords.py
deleted file mode 100755
index 1d5214bb..00000000
--- a/examples/adwords/v201502/basic_operations/get_keywords.py
+++ /dev/null
@@ -1,81 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all ad group criteria in an account.
-
-To add keywords, run add_keywords.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupCriterionService.get
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-PAGE_SIZE = 500
-
-
-def main(client):
- # Initialize appropriate service.
- ad_group_criterion_service = client.GetService(
- 'AdGroupCriterionService', version='v201502')
-
- # Construct selector and get all ad group criteria.
- offset = 0
- selector = {
- 'fields': ['AdGroupId', 'Id', 'Text', 'KeywordMatchType', 'PlacementUrl'],
- 'predicates': [{
- 'field': 'CriteriaType',
- 'operator': 'EQUALS',
- 'values': ['KEYWORD']
- }],
- 'paging': {
- 'startIndex': str(offset),
- 'numberResults': str(PAGE_SIZE)
- }
- }
- more_pages = True
- while more_pages:
- page = ad_group_criterion_service.get(selector)
-
- # Display results.
- if 'entries' in page:
- for criterion in page['entries']:
- print ('Keyword ad group criterion with ad group id \'%s\', criterion '
- 'id \'%s\', text \'%s\', and match type \'%s\' was found.'
- % (criterion['adGroupId'], criterion['criterion']['id'],
- criterion['criterion']['text'],
- criterion['criterion']['matchType']))
- else:
- print 'No keywords were found.'
- offset += PAGE_SIZE
- selector['paging']['startIndex'] = str(offset)
- more_pages = offset < int(page['totalNumEntries'])
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201502/basic_operations/get_text_ads.py b/examples/adwords/v201502/basic_operations/get_text_ads.py
deleted file mode 100755
index a27ab6f8..00000000
--- a/examples/adwords/v201502/basic_operations/get_text_ads.py
+++ /dev/null
@@ -1,85 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all text ads for a given ad group.
-
-To add an ad, run add_text_ads.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupAdService.get
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-PAGE_SIZE = 500
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Initialize appropriate service.
- ad_group_ad_service = client.GetService('AdGroupAdService', version='v201502')
-
- # Construct selector and get all ads for a given ad group.
- offset = 0
- selector = {
- 'fields': ['Id', 'AdGroupId', 'Status'],
- 'predicates': [
- {
- 'field': 'AdGroupId',
- 'operator': 'EQUALS',
- 'values': [ad_group_id]
- },
- {
- 'field': 'AdType',
- 'operator': 'EQUALS',
- 'values': ['TEXT_AD']
- }
- ],
- 'paging': {
- 'startIndex': str(offset),
- 'numberResults': str(PAGE_SIZE)
- }
- }
- more_pages = True
- while more_pages:
- page = ad_group_ad_service.get(selector)
-
- # Display results.
- if 'entries' in page:
- for ad in page['entries']:
- print ('Ad with id \'%s\', status \'%s\', and of type \'%s\' was found.'
- % (ad['ad']['id'], ad['status'], ad['ad']['Ad.Type']))
- else:
- print 'No ads were found.'
- offset += PAGE_SIZE
- selector['paging']['startIndex'] = str(offset)
- more_pages = offset < int(page['totalNumEntries'])
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201502/basic_operations/pause_ad.py b/examples/adwords/v201502/basic_operations/pause_ad.py
deleted file mode 100755
index ae4dbcdc..00000000
--- a/examples/adwords/v201502/basic_operations/pause_ad.py
+++ /dev/null
@@ -1,65 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates status for a given ad.
-
-To get ads, run get_text_ads.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupAdService.mutate
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-AD_ID = 'INSERT_AD_ID_HERE'
-
-
-def main(client, ad_group_id, ad_id):
- # Initialize appropriate service.
- ad_group_ad_service = client.GetService('AdGroupAdService', version='v201502')
-
- # Construct operations and update an ad.
- operations = [{
- 'operator': 'SET',
- 'operand': {
- 'adGroupId': ad_group_id,
- 'ad': {
- 'id': ad_id,
- },
- 'status': 'PAUSED'
- }
- }]
- ads = ad_group_ad_service.mutate(operations)
-
- # Display results.
- for ad in ads['value']:
- print 'Ad with id \'%s\' was updated.'% ad['ad']['id']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID, AD_ID)
diff --git a/examples/adwords/v201502/basic_operations/remove_ad.py b/examples/adwords/v201502/basic_operations/remove_ad.py
deleted file mode 100755
index d12c147a..00000000
--- a/examples/adwords/v201502/basic_operations/remove_ad.py
+++ /dev/null
@@ -1,66 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example deletes an ad using the 'REMOVE' operator.
-
-To get ads, run get_text_ads.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupAdService.mutate
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-AD_ID = 'INSERT_AD_ID_HERE'
-
-
-def main(client, ad_group_id, ad_id):
- # Initialize appropriate service.
- ad_group_ad_service = client.GetService('AdGroupAdService', version='v201502')
-
- # Construct operations and delete ad.
- operations = [{
- 'operator': 'REMOVE',
- 'operand': {
- 'xsi_type': 'AdGroupAd',
- 'adGroupId': ad_group_id,
- 'ad': {
- 'id': ad_id
- }
- }
- }]
- result = ad_group_ad_service.mutate(operations)
-
- # Display results.
- for ad in result['value']:
- print ('Ad with id \'%s\' and type \'%s\' was deleted.'
- % (ad['ad']['id'], ad['ad']['Ad.Type']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID, AD_ID)
diff --git a/examples/adwords/v201502/basic_operations/remove_ad_group.py b/examples/adwords/v201502/basic_operations/remove_ad_group.py
deleted file mode 100755
index dacd3d1f..00000000
--- a/examples/adwords/v201502/basic_operations/remove_ad_group.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example deletes an ad group by setting the status to 'REMOVED'.
-
-To get ad groups, run get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupService.mutate
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Initialize appropriate service.
- ad_group_service = client.GetService('AdGroupService', version='v201502')
-
- # Construct operations and delete ad group.
- operations = [{
- 'operator': 'SET',
- 'operand': {
- 'id': ad_group_id,
- 'status': 'REMOVED'
- }
- }]
- result = ad_group_service.mutate(operations)
-
- # Display results.
- for ad_group in result['value']:
- print ('Ad group with name \'%s\' and id \'%s\' was deleted.'
- % (ad_group['name'], ad_group['id']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201502/basic_operations/remove_campaign.py b/examples/adwords/v201502/basic_operations/remove_campaign.py
deleted file mode 100755
index 4705f99e..00000000
--- a/examples/adwords/v201502/basic_operations/remove_campaign.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example deletes a campaign by setting the status to 'REMOVED'.
-
-To get campaigns, run get_campaigns.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignService.mutate
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-
-
-def main(client, campaign_id):
- # Initialize appropriate service.
- campaign_service = client.GetService('CampaignService', version='v201502')
-
- # Construct operations and delete campaign.
- operations = [{
- 'operator': 'SET',
- 'operand': {
- 'id': campaign_id,
- 'status': 'REMOVED'
- }
- }]
- result = campaign_service.mutate(operations)
-
- # Display results.
- for campaign in result['value']:
- print ('Campaign with name \'%s\' and id \'%s\' was deleted.'
- % (campaign['name'], campaign['id']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201502/basic_operations/remove_keyword.py b/examples/adwords/v201502/basic_operations/remove_keyword.py
deleted file mode 100755
index 9b8d85b5..00000000
--- a/examples/adwords/v201502/basic_operations/remove_keyword.py
+++ /dev/null
@@ -1,72 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example deletes an ad group criterion using the 'REMOVE' operator.
-
-To get ad group criteria, run get_keywords.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupCriterionService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-CRITERION_ID = 'INSERT_CRITERION_ID_HERE'
-
-
-def main(client, ad_group_id, criterion_id):
- # Initialize appropriate service.
- ad_group_criterion_service = client.GetService(
- 'AdGroupCriterionService', version='v201502')
-
- # Construct operations and delete ad group criteria.
- operations = [
- {
- 'operator': 'REMOVE',
- 'operand': {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'id': criterion_id
- }
- }
- }
- ]
- result = ad_group_criterion_service.mutate(operations)
-
- # Display results.
- for criterion in result['value']:
- print ('Ad group criterion with ad group id \'%s\', criterion id \'%s\', '
- 'and type \'%s\' was deleted.'
- % (criterion['adGroupId'], criterion['criterion']['id'],
- criterion['criterion']['Criterion.Type']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID, CRITERION_ID)
diff --git a/examples/adwords/v201502/basic_operations/update_ad_group.py b/examples/adwords/v201502/basic_operations/update_ad_group.py
deleted file mode 100755
index 25a8c8fd..00000000
--- a/examples/adwords/v201502/basic_operations/update_ad_group.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates status for a given ad group.
-
-To get ad groups, run get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupService.mutate
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Initialize appropriate service.
- ad_group_service = client.GetService('AdGroupService', version='v201502')
-
- # Construct operations and update an ad group.
- operations = [{
- 'operator': 'SET',
- 'operand': {
- 'id': ad_group_id,
- 'status': 'PAUSED'
- }
- }]
- ad_groups = ad_group_service.mutate(operations)
-
- # Display results.
- for ad_group in ad_groups['value']:
- print ('Ad group with name \'%s\' and id \'%s\' was updated.'
- % (ad_group['name'], ad_group['id']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201502/basic_operations/update_campaign.py b/examples/adwords/v201502/basic_operations/update_campaign.py
deleted file mode 100755
index f9625702..00000000
--- a/examples/adwords/v201502/basic_operations/update_campaign.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates a campaign by setting its status to PAUSED.
-
-To get campaigns, run get_campaigns.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignService.mutate
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-
-
-def main(client, campaign_id):
- # Initialize appropriate service.
- campaign_service = client.GetService('CampaignService', version='v201502')
-
- # Construct operations and update campaign.
- operations = [{
- 'operator': 'SET',
- 'operand': {
- 'id': campaign_id,
- 'status': 'PAUSED'
- }
- }]
- campaigns = campaign_service.mutate(operations)
-
- # Display results.
- for campaign in campaigns['value']:
- print ('Campaign with name \'%s\' and id \'%s\' was updated.'
- % (campaign['name'], campaign['id']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201502/basic_operations/update_keyword.py b/examples/adwords/v201502/basic_operations/update_keyword.py
deleted file mode 100755
index 9e8c7291..00000000
--- a/examples/adwords/v201502/basic_operations/update_keyword.py
+++ /dev/null
@@ -1,87 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates the bid of a keyword.
-
-To add a keyword, run add_keywords.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupCriterionService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE'
-
-
-def main(client, ad_group_id, criterion_id):
- # Initialize appropriate service.
- ad_group_criterion_service = client.GetService(
- 'AdGroupCriterionService', version='v201502')
-
- # Construct operations and update bids.
-
- operations = [{
- 'operator': 'SET',
- 'operand': {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'id': criterion_id,
- },
- 'biddingStrategyConfiguration': {
- 'bids': [
- {
- 'xsi_type': 'CpcBid',
- 'bid': {
- 'microAmount': '1000000'
- }
- }
- ]
- }
- }
- }]
- ad_group_criteria = ad_group_criterion_service.mutate(operations)
-
- # Display results.
- if 'value' in ad_group_criteria:
- for criterion in ad_group_criteria['value']:
- if criterion['criterion']['Criterion.Type'] == 'Keyword':
- print ('Ad group criterion with ad group id \'%s\' and criterion id '
- '\'%s\' currently has bids:'
- % (criterion['adGroupId'], criterion['criterion']['id']))
- for bid in criterion['biddingStrategyConfiguration']['bids']:
- print '\tType: \'%s\', value: %s' % (bid['Bids.Type'],
- bid['bid']['microAmount'])
- else:
- print 'No ad group criteria were updated.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID, CRITERION_ID)
diff --git a/examples/adwords/v201502/campaign_management/__init__.py b/examples/adwords/v201502/campaign_management/__init__.py
deleted file mode 100644
index db098bda..00000000
--- a/examples/adwords/v201502/campaign_management/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Campaign management examples."""
diff --git a/examples/adwords/v201502/campaign_management/add_campaign_labels.py b/examples/adwords/v201502/campaign_management/add_campaign_labels.py
deleted file mode 100755
index 0817e8d4..00000000
--- a/examples/adwords/v201502/campaign_management/add_campaign_labels.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds a label to multiple campaigns.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignService.mutateLabel
-"""
-
-__author__ = 'Mark Saniscalchi'
-
-from googleads import adwords
-
-
-CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE'
-CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE'
-LABEL_ID = 'INSERT_LABEL_ID_HERE'
-
-
-def main(client, campaign_id1, campaign_id2, label_id):
- # Initialize appropriate service.
- campaign_service = client.GetService('CampaignService', version='v201502')
-
- operations = [
- {
- 'operator': 'ADD',
- 'operand': {
- 'campaignId': campaign_id1,
- 'labelId': label_id,
- }
- },
- {
- 'operator': 'ADD',
- 'operand': {
- 'campaignId': campaign_id2,
- 'labelId': label_id,
- }
- }
- ]
-
- result = campaign_service.mutateLabel(operations)
-
- # Display results.
- for label in result['value']:
- print ('CampaignLabel with campaignId \'%s\' and labelId \'%s\' was added.'
- % (label['campaignId'], label['labelId']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2, LABEL_ID)
diff --git a/examples/adwords/v201502/campaign_management/add_experiment.py b/examples/adwords/v201502/campaign_management/add_experiment.py
deleted file mode 100755
index d7dadc35..00000000
--- a/examples/adwords/v201502/campaign_management/add_experiment.py
+++ /dev/null
@@ -1,132 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates an experiment.
-
-The created experiment is using a query percentage of 10, which defines what
-fraction of auctions should go to the control split (90%) vs. the experiment
-split (10%), then adds experimental bid changes for an ad group, and adds an
-experiment-only keyword. To get campaigns, run get_campaigns.py. To get ad
-groups, run get_ad_groups.py. To get keywords, run get_keywords.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ExperimentService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-import datetime
-import uuid
-
-from googleads import adwords
-
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, campaign_id, ad_group_id):
- # Initialize appropriate service.
- experiment_service = client.GetService('ExperimentService', version='v201502')
- ad_group_service = client.GetService('AdGroupService', version='v201502')
- ad_group_criterion_service = client.GetService(
- 'AdGroupCriterionService', version='v201502')
-
- # Construct operations and add experiment.
- tomorrow = datetime.datetime.now() + datetime.timedelta(1)
- thirty_days = datetime.datetime.now() + datetime.timedelta(30)
- operations = [{
- 'operator': 'ADD',
- 'operand': {
- 'campaignId': campaign_id,
- 'name': 'Interplanetary Experiment #%s' % uuid.uuid4(),
- 'queryPercentage': '10',
- 'startDateTime': tomorrow.strftime('%Y%m%d %H%M%S'),
- # Optional fields.
- 'status': 'ENABLED',
- 'endDateTime': thirty_days.strftime('%Y%m%d %H%M%S')
- }
- }]
- result = experiment_service.mutate(operations)
-
- # Display results.
- for experiment in result['value']:
- print ('Experiment with name \'%s\' and id \'%s\' was added.'
- % (experiment['name'], experiment['id']))
-
- # Construct operations and update ad group.
- operations = [{
- 'operator': 'SET',
- 'operand': {
- 'id': ad_group_id,
- 'experimentData': {
- 'xsi_type': 'AdGroupExperimentData',
- 'experimentId': experiment['id'],
- 'experimentDeltaStatus': 'MODIFIED',
- 'experimentBidMultipliers': {
- 'xsi_type': 'ManualCPCAdGroupExperimentBidMultipliers',
- 'maxCpcMultiplier': {
- 'multiplier': '0.5'
- }
- }
- }
- }
- }]
- result = ad_group_service.mutate(operations)
-
- # Display results.
- for ad_group in result['value']:
- print ('Ad group with name \'%s\' and id \'%s\' was updated in the '
- 'experiment.' % (ad_group['name'], ad_group['id']))
-
- # Construct operations and add ad group crierion.
- operations = [{
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group['id'],
- 'criterion': {
- 'xsi_type': 'Keyword',
- 'matchType': 'BROAD',
- 'text': 'mars cruise'
- },
- 'experimentData': {
- 'xsi_type': 'BiddableAdGroupCriterionExperimentData',
- 'experimentId': experiment['id'],
- 'experimentDeltaStatus': 'EXPERIMENT_ONLY'
- }
- }
- }]
- result = ad_group_criterion_service.mutate(operations)
-
- # Display results.
- for criterion in result['value']:
- print ('Ad group criterion with ad group id \'%s\' and criterion '
- 'id \'%s\' was added to the experiment.'
- % (criterion['adGroupId'], criterion['criterion']['id']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID, AD_GROUP_ID)
diff --git a/examples/adwords/v201502/campaign_management/add_keywords_in_bulk.py b/examples/adwords/v201502/campaign_management/add_keywords_in_bulk.py
deleted file mode 100755
index e346eb7a..00000000
--- a/examples/adwords/v201502/campaign_management/add_keywords_in_bulk.py
+++ /dev/null
@@ -1,141 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code sample illustrates how to perform asynchronous requests.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: MutateJobService.mutate
-Tags: MutateJobService.get
-Tags: MutateJobService.getResult
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-import random
-import re
-import time
-
-from googleads import adwords
-from googleads import errors
-
-
-RETRY_INTERVAL = 10
-RETRIES_COUNT = 30
-KEYWORD_NUMBER = 100
-INDEX_REGEX = r'operations\[(\d+)\].operand'
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Initialize appropriate service.
- mutate_job_service = client.GetService('MutateJobService', version='v201502')
-
- # Create list of all operations for the job.
- operations = []
-
- # Create AdGroupCriterionOperations to add keywords.
- for i in range(KEYWORD_NUMBER):
- keyword = 'mars%d' % i
- if random.randint(1, 10) == 1:
- keyword += '!!!'
- operations.append({
- 'xsi_type': 'AdGroupCriterionOperation',
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Keyword',
- 'matchType': 'BROAD',
- 'text': keyword
- }
- }
- })
-
- # You can specify up to 3 job IDs that must successfully complete before
- # this job can be processed.
- policy = {
- 'prerequisiteJobIds': []
- }
-
- # Call mutate to create a new job.
- response = mutate_job_service.mutate(operations, policy)
-
- if not response:
- raise errors.GoogleAdsError('Failed to submit a job; aborting.')
-
- job_id = response['id']
- print 'Job with ID %s was successfully created.' % job_id
-
- # Create selector to retrieve job status and wait for it to complete.
- selector = {
- 'xsi_type': 'BulkMutateJobSelector',
- 'jobIds': [job_id]
- }
-
- time.sleep(RETRY_INTERVAL)
- # Poll for job status until it's finished.
- print 'Retrieving job status...'
- for i in range(RETRIES_COUNT):
- job_status_response = mutate_job_service.get(selector)
- status = job_status_response[0]['status']
- if status in ('COMPLETED', 'FAILED'):
- break
- print ('[%d] Current status is \'%s\', waiting %d seconds to retry...' %
- (i, status, RETRY_INTERVAL))
- time.sleep(RETRY_INTERVAL)
-
- if status == 'FAILED':
- raise errors.GoogleAdsError('Job failed with reason: \'%s\'' %
- job_status_response[0]['failure_reason'])
- if status in ('PROCESSING', 'PENDING'):
- raise errors.GoogleAdsError('Job did not complete within %d seconds' %
- (RETRY_INTERVAL * (RETRIES_COUNT - 1)))
-
- # Status must be COMPLETED.
- # Get the job result. Here we re-use the same selector.
- result_response = mutate_job_service.getResult(selector)
-
- # Output results.
- index = 0
- for result in result_response['SimpleMutateResult']['results']:
- if 'PlaceHolder' in result:
- print 'Operation [%d] - FAILED' % index
- else:
- print 'Operation [%d] - SUCCEEDED' % index
- index += 1
-
- # Output errors
- for error in result_response['SimpleMutateResult']['errors']:
- index = int(re.search(INDEX_REGEX, error['fieldPath']).group(1))
- reason = error['reason']
- keyword = operations[index]['operand']['criterion']['text']
- print ('ERROR - keyword \'%s\' failed due to \'%s\'' %
- (keyword, reason))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201502/campaign_management/add_location_extension.py b/examples/adwords/v201502/campaign_management/add_location_extension.py
deleted file mode 100755
index f0e3e963..00000000
--- a/examples/adwords/v201502/campaign_management/add_location_extension.py
+++ /dev/null
@@ -1,114 +0,0 @@
-#!/usr/bin/python
-# -*- coding: UTF-8 -*-
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds a campaign ad extension to a given campaign.
-
-To get campaigns, run get_campaigns.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: GeoLocationService.get, CampaignAdExtensionService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-
-
-def main(client, campaign_id):
- # Initialize appropriate service.
- geo_location_service = client.GetService(
- 'GeoLocationService', version='v201502')
- campaign_ad_extension_service = client.GetService(
- 'CampaignAdExtensionService', version='v201502')
-
- # Construct selector and get geo location info for given addresses.
- selector = {
- 'addresses': [
- {
- 'streetAddress': '1600 Amphitheatre Parkway',
- 'cityName': 'Mountain View',
- 'provinceCode': 'US-CA',
- 'provinceName': 'California',
- 'postalCode': '94043',
- 'countryCode': 'US'
- },
- {
- 'streetAddress': u'38 avenue de l\'Opéra',
- 'cityName': 'Paris',
- 'postalCode': '75002',
- 'countryCode': 'FR'
- }
- ]
- }
- geo_locations = geo_location_service.get(selector)
-
- # Construct operations and add campaign ad extension.
- operations = [
- {
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'CampaignAdExtension',
- 'campaignId': campaign_id,
- 'adExtension': {
- 'xsi_type': 'LocationExtension',
- 'address': geo_locations[0]['address'],
- 'geoPoint': geo_locations[0]['geoPoint'],
- 'encodedLocation': geo_locations[0]['encodedLocation'],
- 'source': 'ADWORDS_FRONTEND',
- # Optional fields.
- 'companyName': 'ACME Inc.',
- 'phoneNumber': '(650) 253-0000'
- }
- }
- },
- {
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'CampaignAdExtension',
- 'campaignId': campaign_id,
- 'adExtension': {
- 'xsi_type': 'LocationExtension',
- 'address': geo_locations[1]['address'],
- 'geoPoint': geo_locations[1]['geoPoint'],
- 'encodedLocation': geo_locations[1]['encodedLocation'],
- 'source': 'ADWORDS_FRONTEND'
- }
- }
- }
- ]
- ad_extensions = campaign_ad_extension_service.mutate(operations)
-
- # Display results.
- for ad_extension in ad_extensions['value']:
- print ('Campaign ad extension with id \'%s\' and status \'%s\' was added.'
- % (ad_extension['adExtension']['id'], ad_extension['status']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201502/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201502/campaign_management/get_all_disapproved_ads.py
deleted file mode 100755
index ca22bf7d..00000000
--- a/examples/adwords/v201502/campaign_management/get_all_disapproved_ads.py
+++ /dev/null
@@ -1,78 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all disapproved ads for a given campaign.
-
-To add an ad, run add_ads.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupAdService.get
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-
-
-def main(client, campaign_id):
- # Initialize appropriate service.
- ad_group_ad_service = client.GetService('AdGroupAdService', version='v201502')
-
- # Construct selector and get all ads for a given ad group.
- selector = {
- 'fields': ['Id', 'AdGroupAdDisapprovalReasons'],
- 'predicates': [
- {
- 'field': 'CampaignId',
- 'operator': 'EQUALS',
- 'values': [campaign_id]
- },
- {
- 'field': 'AdGroupCreativeApprovalStatus',
- 'operator': 'IN',
- 'values': ['DISAPPROVED']
- }
- ]
- }
- ads = ad_group_ad_service.get(selector)
-
- # Display results.
- if 'entries' in ads:
- for ad in ads['entries']:
- print ('Ad with id \'%s\' was disapproved for the following reasons: '
- % (ad['ad']['id']))
- if ad['ad'].get('disapprovalReasons'):
- for reason in ad['ad']['disapprovalReasons']:
- print '\t%s' % reason
- else:
- print '\tReason not provided.'
- else:
- print 'No disapproved ads were found.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201502/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201502/campaign_management/get_all_disapproved_ads_with_awql.py
deleted file mode 100755
index 3a820077..00000000
--- a/examples/adwords/v201502/campaign_management/get_all_disapproved_ads_with_awql.py
+++ /dev/null
@@ -1,67 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all disapproved ads for a given campaign with AWQL.
-
-To add an ad, run add_ads.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupAdService.get
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-
-
-def main(client, campaign_id):
- # Initialize appropriate service.
- ad_group_ad_service = client.GetService('AdGroupAdService', version='v201502')
-
- # Construct query and get all ads for a given campaign.
- query = ('SELECT Id, AdGroupAdDisapprovalReasons '
- 'WHERE CampaignId = %s AND '
- 'AdGroupCreativeApprovalStatus = DISAPPROVED '
- 'ORDER BY Id' % campaign_id)
- ads = ad_group_ad_service.query(query)
-
- # Display results.
- if 'entries' in ads:
- for ad in ads['entries']:
- print ('Ad with id \'%s\' was disapproved for the following reasons: '
- % (ad['ad']['id']))
- if ad['ad'].get('disapprovalReasons'):
- for reason in ad['ad']['disapprovalReasons']:
- print '\t%s' % reason
- else:
- print '\tReason not provided.'
- else:
- print 'No disapproved ads were found.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201502/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201502/campaign_management/get_campaigns_by_label.py
deleted file mode 100755
index c18d8714..00000000
--- a/examples/adwords/v201502/campaign_management/get_campaigns_by_label.py
+++ /dev/null
@@ -1,88 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all campaigns with a specific label.
-
-To add a label to campaigns, run add_campaign_labels.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignService.get
-"""
-
-__author__ = 'Mark Saniscalchi'
-
-import time
-
-from googleads import adwords
-
-
-LABEL_ID = 'INSERT_LABEL_ID_HERE'
-PAGE_SIZE = 100
-
-
-def main(client, label_id):
- # Initialize appropriate service.
- campaign_service = client.GetService('CampaignService', version='v201502')
-
- offset = 0
- selector = {
- 'fields': ['Id', 'Name', 'Labels'],
- # Labels filtering is performed by ID. You can use CONTAINS_ANY to select
- # campaigns with any of the label IDs, CONTAINS_ALL to select campaigns
- # with all of the label IDs, or CONTAINS_NONE to select campaigns with
- # none of the label IDs.
- 'ordering': {
- 'field': 'Name',
- 'sortOrder': 'ASCENDING'
- },
- 'paging': {
- 'startIndex': str(offset),
- 'numberResults': str(PAGE_SIZE)
- },
- 'predicates': {
- 'field': 'Labels',
- 'operator': 'CONTAINS_ANY',
- 'values': [label_id]
- }
- }
-
- more_pages = True
- while more_pages:
- page = campaign_service.get(selector)
-
- # Display results.
- if 'entries' in page:
- for campaign in page['entries']:
- print ('Campaign found with Id \'%s\', name \'%s\', and labels: %s'
- % (campaign['id'], campaign['name'], campaign['labels']))
- else:
- print 'No campaigns were found.'
-
- offset += PAGE_SIZE
- selector['paging']['startIndex'] = str(offset)
- more_pages = offset < int(page['totalNumEntries'])
- time.sleep(1)
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, LABEL_ID)
diff --git a/examples/adwords/v201502/campaign_management/promote_experiment.py b/examples/adwords/v201502/campaign_management/promote_experiment.py
deleted file mode 100755
index 09e370a3..00000000
--- a/examples/adwords/v201502/campaign_management/promote_experiment.py
+++ /dev/null
@@ -1,65 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example promotes an experiment.
-
-Promoting an experiment permanently applies all the experimental changes made to
-its related ad groups, criteria and ads. To add an experiment, run
-add_experiment.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ExperimentService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-EXPERIMENT_ID = 'INSERT_EXPERIMENT_ID_HERE'
-
-
-def main(client, experiment_id):
- # Initialize appropriate service.
- experiment_service = client.GetService('ExperimentService', version='v201502')
-
- # Construct operations and promote experiment.
- operations = [{
- 'operator': 'SET',
- 'operand': {
- 'id': experiment_id,
- 'status': 'PROMOTED'
- }
- }]
- result = experiment_service.mutate(operations)
-
- # Display results.
- for experiment in result['value']:
- print ('Experiment with name \'%s\' and id \'%s\' was promoted.'
- % (experiment['name'], experiment['id']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, EXPERIMENT_ID)
diff --git a/examples/adwords/v201502/campaign_management/set_ad_parameters.py b/examples/adwords/v201502/campaign_management/set_ad_parameters.py
deleted file mode 100755
index e7f22a68..00000000
--- a/examples/adwords/v201502/campaign_management/set_ad_parameters.py
+++ /dev/null
@@ -1,107 +0,0 @@
-#!/usr/bin/python
-# -*- coding: utf-8 -*-
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds a text ad with ad parameters.
-
-To get ad groups, run get_ad_groups.py. To get keywords, run add_keywords.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupAdService.mutate, AdParamService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE'
-
-
-def main(client, ad_group_id, criterion_id):
- # Initialize appropriate service.
- ad_group_ad_service = client.GetService('AdGroupAdService', version='v201502')
- ad_param_service = client.GetService('AdParamService', version='v201502')
-
- # Construct operations for adding text ad object and add to an ad group.
- operations = [{
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'AdGroupAd',
- 'adGroupId': ad_group_id,
- 'ad': {
- 'xsi_type': 'TextAd',
- 'finalUrls': {
- 'urls': ['http://www.example.com']
- },
- 'displayUrl': 'example.com',
- 'description1': 'Low-gravity fun for {param1:cheap}.',
- 'description2': 'Only {param2:a few} seats left!',
- 'headline': 'Luxury Mars Cruises'
- },
- 'status': 'ENABLED'
- }
- }]
- ads = ad_group_ad_service.mutate(operations)['value']
-
- # Display results.
- for ad in ads:
- print ('Text ad with id \'%s\' was successfully added to an ad group with '
- 'id \'%s\'.' % (ad['adGroupId'], ad['ad']['id']))
-
- # Construct operations for setting ad parameters.
- operations = [
- {
- 'operator': 'SET',
- 'operand': {
- 'adGroupId': ad_group_id,
- 'criterionId': criterion_id,
- 'insertionText': u'£100',
- 'paramIndex': '1'
- }
- },
- {
- 'operator': 'SET',
- 'operand': {
- 'adGroupId': ad_group_id,
- 'criterionId': criterion_id,
- 'insertionText': '50',
- 'paramIndex': '2'
- }
- }
- ]
- ad_params = ad_param_service.mutate(operations)
-
- # Display results.
- for ad_param in ad_params:
- print ('Ad parameter with text \'%s\' was successfully set for criterion '
- 'with id \'%s\' and ad group id \'%s\'.'
- % (ad_param['insertionText'], ad_param['criterionId'],
- ad_param['adGroupId']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID, CRITERION_ID)
diff --git a/examples/adwords/v201502/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201502/campaign_management/set_criterion_bid_modifier.py
deleted file mode 100755
index 0b2e4a03..00000000
--- a/examples/adwords/v201502/campaign_management/set_criterion_bid_modifier.py
+++ /dev/null
@@ -1,82 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example sets a bid modifier for the mobile platform on given campaign.
-
-To get campaigns, run get_campaigns.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignCriterionService.mutate
-"""
-
-__author__ = ('api.dklimkin@gmail.com (Danial Klimkin)',
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-BID_MODIFIER = '1.5'
-
-
-def main(client, campaign_id, bid_modifier):
- # Initialize appropriate service.
- campaign_criterion_service = client.GetService(
- 'CampaignCriterionService', version='v201502')
-
- # Create mobile platform.The ID can be found in the documentation.
- # https://developers.google.com/adwords/api/docs/appendix/platforms
- mobile = {
- 'xsi_type': 'Platform',
- 'id': '30001'
- }
-
- # Create campaign criterion with modified bid.
- campaign_criterion = {
- 'campaignId': campaign_id,
- 'criterion': mobile,
- 'bidModifier': bid_modifier
- }
-
- # Create operations.
- operations = [
- {
- 'operator': 'SET',
- 'operand': campaign_criterion
- }
- ]
-
- # Make the mutate request.
- result = campaign_criterion_service.mutate(operations)
-
- # Display the resulting campaign criteria.
- for campaign_criterion in result['value']:
- print ('Campaign criterion with campaign id \'%s\' and criterion id \'%s\' '
- 'was updated with bid modifier \'%s\'.'
- % (campaign_criterion['campaignId'],
- campaign_criterion['criterion']['id'],
- campaign_criterion['bidModifier']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID, BID_MODIFIER)
diff --git a/examples/adwords/v201502/campaign_management/validate_text_ad.py b/examples/adwords/v201502/campaign_management/validate_text_ad.py
deleted file mode 100755
index 46cd4c3a..00000000
--- a/examples/adwords/v201502/campaign_management/validate_text_ad.py
+++ /dev/null
@@ -1,91 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example shows how to use validateOnly SOAP header.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-import suds
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Initialize appropriate service with validate only flag enabled.
- client.validate_only = True
- ad_group_ad_service = client.GetService('AdGroupAdService', version='v201502')
-
- # Construct operations to add a text ad.
- operations = [{
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'AdGroupAd',
- 'adGroupId': ad_group_id,
- 'ad': {
- 'xsi_type': 'TextAd',
- 'finalUrls': {
- 'urls': ['http://www.example.com']
- },
- 'displayUrl': 'example.com',
- 'description1': 'Visit the Red Planet in style.',
- 'description2': 'Low-gravity fun for everyone!',
- 'headline': 'Luxury Cruise to Mars'
- }
- }
- }]
- ad_group_ad_service.mutate(operations)
- # No error means the request is valid.
-
- # Now let's check an invalid ad using a very long line to trigger an error.
- operations = [{
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'AdGroupAd',
- 'adGroupId': ad_group_id,
- 'ad': {
- 'xsi_type': 'TextAd',
- 'url': 'http://www.example.com',
- 'displayUrl': 'example.com',
- 'description1': 'Visit the Red Planet in style.',
- 'description2': 'Low-gravity fun for all astronauts in orbit',
- 'headline': 'Luxury Cruise to Mars'
- }
- }
- }]
- try:
- ad_group_ad_service.mutate(operations)
- except suds.WebFault, e:
- print 'Validation correctly failed with \'%s\'.' % str(e)
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201502/error_handling/__init__.py b/examples/adwords/v201502/error_handling/__init__.py
deleted file mode 100644
index b5203c57..00000000
--- a/examples/adwords/v201502/error_handling/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Error handling examples."""
diff --git a/examples/adwords/v201502/error_handling/handle_partial_failures.py b/examples/adwords/v201502/error_handling/handle_partial_failures.py
deleted file mode 100755
index 644f22fe..00000000
--- a/examples/adwords/v201502/error_handling/handle_partial_failures.py
+++ /dev/null
@@ -1,124 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example demonstrates how to handle partial failures.
-
-To get ad groups, run get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupCriterionService.mutate
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-import re
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Enable partial failure.
- client.partial_failure = True
-
- # Initialize appropriate service.
- ad_group_criterion_service = client.GetService(
- 'AdGroupCriterionService', version='v201502')
-
- # Construct keyword ad group criteria objects.
- keywords = [
- {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Keyword',
- 'matchType': 'BROAD',
- 'text': 'mars cruise'
- }
- },
- {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Keyword',
- 'matchType': 'BROAD',
- 'text': r'inv\@lid cruise'
- }
- },
- {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Keyword',
- 'matchType': 'BROAD',
- 'text': 'venus cruise'
- }
- },
- {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Keyword',
- 'matchType': 'BROAD',
- 'text': r'b\(a\)d keyword cruise'
- }
- }
- ]
-
- # Construct operations and add ad group criteria.
- operations = []
- for keyword in keywords:
- operations.append(
- {
- 'operator': 'ADD',
- 'operand': keyword
- })
- result = ad_group_criterion_service.mutate(operations)
-
- # Display results.
- for criterion in result['value']:
- if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion':
- print ('Added keyword ad group criterion with ad group id \'%s\', '
- 'criterion id \'%s\', text \'%s\', and match type \'%s\' was '
- 'added.'
- % (criterion['adGroupId'], criterion['criterion']['id'],
- criterion['criterion']['text'],
- criterion['criterion']['matchType']))
-
- for error in result['partialFailureErrors']:
- index = re.findall(r'operations\[(.*)\]\.', error['fieldPath'])
- if index:
- print ('Keyword ad group criterion with ad group id \'%s\' and text '
- '\'%s\' triggered a failure for the following reason: \'%s\'.'
- % (keywords[int(index[0])]['adGroupId'],
- keywords[int(index[0])]['criterion']['text'],
- error['errorString']))
- else:
- print 'The following failure has occurred: \'%s\'.' % error['errorString']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201502/error_handling/handle_policy_violation_error.py b/examples/adwords/v201502/error_handling/handle_policy_violation_error.py
deleted file mode 100755
index 2a5a390d..00000000
--- a/examples/adwords/v201502/error_handling/handle_policy_violation_error.py
+++ /dev/null
@@ -1,117 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example demonstrates how to handle policy violation errors.
-
-To get ad groups, run get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupAdService.mutate
-"""
-
-__author__ = 'Joseph DiLallo'
-
-import re
-
-import suds
-
-from googleads import adwords
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- ad_group_ad_service = client.GetService('AdGroupAdService', 'v201502')
-
- # Create text ad.
- text_ad_operation = {
- 'operator': 'ADD',
- 'operand': {
- 'adGroupId': ad_group_id,
- 'ad': {
- # The 'xsi_type' field allows you to specify the xsi:type of the
- # object being created. It's only necessary when you must provide
- # an explicit type that the client library can't infer.
- 'xsi_type': 'TextAd',
- 'headline': 'Mars Cruise!!!',
- 'description1': 'Visit the Red Planet in style.',
- 'description2': 'Low-gravity fun for everyone!',
- 'finalUrls': ['http://www.example.com'],
- 'displayUrl': 'www.example.com',
- }
- }
- }
-
- operations = [text_ad_operation]
-
- # Validate the ad.
- try:
- # Enable "validate only" to check for errors.
- client.validate_only = True
- ad_group_ad_service.mutate(operations)
- print 'Validation successful, no errors returned.'
- except suds.WebFault, e:
- for error in e.fault.detail.ApiExceptionFault.errors:
- if error['ApiError.Type'] == 'PolicyViolationError':
- operation_index = re.findall(r'operations\[(.*)\]\.',
- error['fieldPath'])
- if operation_index:
- operation = operations[int(operation_index[0])]
- print ('Ad with headline \'%s\' violated %s policy \'%s\'.' %
- (operation['operand']['ad']['headline'],
- 'exemptable' if error['isExemptable'] else 'non-exemptable',
- error['externalPolicyName']))
- if error['isExemptable'].lower() == 'true':
- # Add exemption request to the operation.
- print ('Adding exemption request for policy name \'%s\' on text '
- '\'%s\'.' %
- (error['key']['policyName'], error['key']['violatingText']))
- if 'exemptionRequests' not in operation:
- operation['exemptionRequests'] = []
- operation['exemptionRequests'].append({
- 'key': error['key']
- })
- else:
- # Remove non-exemptable operation
- print 'Removing the operation from the request.'
- operations.delete(operation)
- else:
- # Non-policy error returned, re-throw exception.
- raise e
-
- # Add these ads. Disable "validate only" so the ads will get created.
- client.validate_only = False
- if operations:
- response = ad_group_ad_service.mutate(operations)
- if response and response['value']:
- ads = response['value']
- print 'Added %s ad(s) to ad group %s.' % (len(ads), ad_group_id)
- for ad in ads:
- print (' Ad id is %s, type is %s and status is \'%s\'.' %
- (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status']))
- else:
- print 'No ads were added.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201502/extensions/__init__.py b/examples/adwords/v201502/extensions/__init__.py
deleted file mode 100644
index b4d63e00..00000000
--- a/examples/adwords/v201502/extensions/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Extension examples."""
diff --git a/examples/adwords/v201502/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201502/extensions/add_google_my_business_location_extensions.py
deleted file mode 100755
index b723ca95..00000000
--- a/examples/adwords/v201502/extensions/add_google_my_business_location_extensions.py
+++ /dev/null
@@ -1,158 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-
-"""Adds a feed that syncs feed items from a Google My Business (GMB) account.
-
-This example associates the feed with a customer.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomerFeedService.mutate, FeedService.mutate
-"""
-
-__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)',
- 'Joseph DiLallo')
-
-import time
-import uuid
-
-# Import appropriate modules from the client library.
-import suds
-
-from googleads import adwords
-from googleads import errors
-
-GMB_EMAIL_ADDRESS = 'INSERT_GMB_EMAIL_ADDRESS_HERE'
-# To obtain an access token for your Places account, you can run the
-# generate_refresh_token.py example and manually replace the scope with
-# "https://www.google.com/local/add".
-GMB_ACCESS_TOKEN = 'INSERT_GMB_OAUTH_ACCESS_TOKEN_HERE'
-
-# If the gmb_email_address above is for a GMB manager instead of
-# the GMB account owner, then set business_account_identifier to the
-# +Page ID of a location for which the manager has access. See the
-# location extensions guide at
-# https://developers.google.com/adwords/api/docs/guides/feed-services-locations
-# for details.
-BUSINESS_ACCOUNT_IDENTIFIER = None
-
-# The placeholder type for location extensions.
-# See the Placeholder reference page for a list of all the placeholder types
-# and fields:
-# https://developers.google.com/adwords/api/docs/appendix/placeholders
-PLACEHOLDER_LOCATION = 7
-
-# The maximum number of CustomerFeed ADD operation attempts to make before
-# throwing an exception.
-MAX_CUSTOMER_FEED_ADD_ATTEMPTS = 10
-
-
-def main(client, gmb_email_address, gmb_access_token,
- business_account_identifier=None):
- # Create a feed that will sync to the Google Places account specified by
- # gmb_email_address. Do not add FeedAttributes to this object,
- # as AdWords will add them automatically because this will be a
- # system generated feed.
- feed = {
- 'name': 'GMB feed #%s' % uuid.uuid4(),
- 'systemFeedGenerationData': {
- 'xsi_type': 'PlacesLocationFeedData',
- 'oAuthInfo': {
- 'httpMethod': 'GET',
- 'httpRequestUrl': 'https://www.googleapis.com/auth/adwords',
- 'httpAuthorizationHeader': 'Bearer %s' % gmb_access_token
- },
- 'emailAddress': gmb_email_address,
- },
- # Since this feed's feed items will be managed by AdWords, you must set
- # its origin to ADWORDS.
- 'origin': 'ADWORDS'
- }
-
- # Only include the business_account_identifier if it's specified.
- if business_account_identifier:
- feed['systemFeedGenerationData']['businessAccountIdentifier'] = (
- business_account_identifier
- )
-
- # Create an operation to add the feed.
- gmb_operations = [{
- 'operator': 'ADD',
- 'operand': feed
- }]
-
- gmb_response = client.GetService('FeedService', version='v201502').mutate(
- gmb_operations)
- added_feed = gmb_response['value'][0]
- print 'Added GMB feed with ID: %d\n' % added_feed['id']
-
- # Add a CustomerFeed that associates the feed with this customer for the
- # LOCATION placeholder type.
- customer_feed = {
- 'feedId': added_feed['id'],
- 'placeholderTypes': [PLACEHOLDER_LOCATION],
- # Create a matching function that will always evaluate to True.
- 'matchingFunction': {
- 'operator': 'IDENTITY',
- 'lhsOperand': {
- 'xsi_type': 'ConstantOperand',
- 'type': 'BOOLEAN',
- 'booleanValue': True
- }
- }
- }
-
- customer_feed_operation = {
- 'xsi_type': 'CustomerFeedOperation',
- 'operator': 'ADD',
- 'operand': customer_feed
- }
-
- customer_feed_service = client.GetService(
- 'CustomerFeedService', version='v201502')
- added_customer_feed = None
-
- i = 0
- while i < MAX_CUSTOMER_FEED_ADD_ATTEMPTS and added_customer_feed is None:
- try:
- added_customer_feed = customer_feed_service.mutate([
- customer_feed_operation])['value'][0]
- except suds.WebFault:
- # Wait using exponential backoff policy
- sleep_seconds = 2 ** i
- print ('Attempt %d to add the CustomerFeed was not successful.'
- 'Waiting %d seconds before trying again.\n' % (i, sleep_seconds))
-
- time.sleep(sleep_seconds)
- i += 1
-
- if added_customer_feed is None:
- raise errors.GoogleAdsError(
- 'Could not create the CustomerFeed after %s attempts. Please retry the '
- 'CustomerFeed ADD operation later.' % MAX_CUSTOMER_FEED_ADD_ATTEMPTS)
-
- print ('Added CustomerFeed for feed ID %d and placeholder type %d\n'
- % (added_customer_feed['id'], added_customer_feed['placeholderTypes']))
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
- main(adwords_client, GMB_EMAIL_ADDRESS, GMB_ACCESS_TOKEN,
- BUSINESS_ACCOUNT_IDENTIFIER)
diff --git a/examples/adwords/v201502/extensions/add_site_links.py b/examples/adwords/v201502/extensions/add_site_links.py
deleted file mode 100755
index d7cf2989..00000000
--- a/examples/adwords/v201502/extensions/add_site_links.py
+++ /dev/null
@@ -1,128 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Adds sitelinks to a campaign using the CampaignExtensionSettingService.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignExtensionSettingService.mutate, CustomerService.get
-Api: AdWordsOnly
-"""
-
-__author__ = 'Mark Saniscalchi'
-
-from datetime import datetime
-
-
-from googleads import adwords
-from googleads import errors
-from pytz import timezone
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-
-
-def main(client, campaign_id):
- # Initialize appropriate services.
- campaign_extension_setting_service = client.GetService(
- 'CampaignExtensionSettingService', version='v201502')
- customer_service = client.GetService('CustomerService', version='v201502')
-
- customer_tz = timezone(customer_service.get()['dateTimeZone'])
- time_fmt = '%s %s' % ('%Y%m%d %H%M%S', customer_tz)
-
- # Create the sitelinks
- sitelink1 = {
- 'xsi_type': 'SitelinkFeedItem',
- 'sitelinkText': 'Store Hours',
- 'sitelinkUrl': 'http://www.example.com/storehours'
- }
-
- # Show the Thanksgiving specials link only from 20 - 27 Nov.
- sitelink2 = {
- 'xsi_type': 'SitelinkFeedItem',
- 'sitelinkText': 'Thanksgiving Specials',
- 'sitelinkUrl': 'http://www.example.com/thanksgiving',
- # The time zone of the start and end date/times must match the time zone
- # of the customer.
- 'startTime': datetime(datetime.now().year, 11, 20, 0, 0, 0, 0,
- customer_tz).strftime(time_fmt),
- 'endTime': datetime(datetime.now().year, 11, 27, 23, 59, 59, 59,
- customer_tz).strftime(time_fmt)
- }
-
- # Show the wifi details primarily for high end mobile users.
- sitelink3 = {
- 'xsi_type': 'SitelinkFeedItem',
- 'sitelinkText': 'Wifi Available',
- 'sitelinkUrl': 'http://www.example.com/mobile/wifi',
- # See https://developers.google.com/adwords/api/docs/appendix/platforms
- # for device criteria IDs.
- 'devicePreference': {'devicePreference': '30001'}
- }
-
- # Show the happy hours link only during Mon - Fri 6PM to 9PM.
- sitelink4 = {
- 'xsi_type': 'SitelinkFeedItem',
- 'sitelinkText': 'Happy hours',
- 'sitelinkUrl': 'http://www.example.com/happyhours',
- 'scheduling': {
- 'feedItemSchedules': [
- {
- 'dayOfWeek': day,
- 'startHour': '18',
- 'startMinute': 'ZERO',
- 'endHour': '21',
- 'endMinute': 'ZERO'
- } for day in ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY',
- 'FRIDAY']
- ]
- }
- }
-
- # Create your Campaign Extension Settings. This associates the sitelinks
- # to your campaign.
- campaign_extension_setting = {
- 'campaignId': campaign_id,
- 'extensionType': 'SITELINK',
- 'extensionSetting': {
- 'extensions': [sitelink1, sitelink2, sitelink3, sitelink4]
- }
- }
-
- operation = {
- 'operator': 'ADD',
- 'operand': campaign_extension_setting
- }
-
- # Add the extensions.
- response = campaign_extension_setting_service.mutate([operation])
-
- if 'value' in response:
- print ('Extension setting with type "%s" was added to campaignId "%d".' %
- (response['value'][0]['extensionType'],
- response['value'][0]['campaignId']))
- else:
- raise errors.GoogleAdsError('No extension settings were added.')
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201502/extensions/add_site_links_using_feeds.py b/examples/adwords/v201502/extensions/add_site_links_using_feeds.py
deleted file mode 100755
index 9dadf591..00000000
--- a/examples/adwords/v201502/extensions/add_site_links_using_feeds.py
+++ /dev/null
@@ -1,265 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds a sitelinks feed and associates it with a campaign.
-
-To add sitelinks using the simpler ExtensionSetting services, see:
-add_sitelinks.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignFeedService.mutate, FeedItemService.mutate
-Tags: FeedMappingService.mutate, FeedService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = 'Joseph DiLallo'
-
-import uuid
-
-from googleads import adwords
-from googleads import errors
-
-# See the Placeholder reference page for a list of all the placeholder types and
-# fields.
-# https://developers.google.com/adwords/api/docs/appendix/placeholders.html
-PLACEHOLDER_SITELINKS = '1'
-PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = '1'
-PLACEHOLDER_FIELD_SITELINK_FINAL_URL = '5'
-PLACEHOLDER_FIELD_LINE_1_TEXT = '3'
-PLACEHOLDER_FIELD_LINE_2_TEXT = '4'
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-
-
-def main(client, campaign_id):
- # Initialize appropriate service.
- feed_service = client.GetService('FeedService', version='v201502')
- feed_item_service = client.GetService('FeedItemService', version='v201502')
- feed_mapping_service = client.GetService(
- 'FeedMappingService', version='v201502')
- campaign_feed_service = client.GetService(
- 'CampaignFeedService', version='v201502')
-
- sitelinks_data = {}
-
- # Create site links feed first.
- site_links_feed = {
- 'name': 'Feed For Site Links #%s' % uuid.uuid4(),
- 'attributes': [
- {'type': 'STRING', 'name': 'Link Text'},
- {'type': 'URL_LIST', 'name': 'Link Final URLs'},
- {'type': 'STRING', 'name': 'Line 1 Description'},
- {'type': 'STRING', 'name': 'Line 2 Description'}
- ]
- }
-
- response = feed_service.mutate([
- {'operator': 'ADD', 'operand': site_links_feed}
- ])
-
- if 'value' in response:
- feed = response['value'][0]
- link_text_feed_attribute_id = feed['attributes'][0]['id']
- final_url_feed_attribute_id = feed['attributes'][1]['id']
- line_1_feed_attribute_id = feed['attributes'][2]['id']
- line_2_feed_attribute_id = feed['attributes'][3]['id']
- print ('Feed with name \'%s\' and ID \'%s\' was added with' %
- (feed['name'], feed['id']))
- print ('\tText attribute ID \'%s\' and Final URL attribute ID \'%s\'.' %
- (link_text_feed_attribute_id, final_url_feed_attribute_id))
- print ('\tLine 1 attribute ID \'%s\' and Line 2 attribute ID \'%s\'.' %
- (line_1_feed_attribute_id, line_2_feed_attribute_id))
- sitelinks_data['feedId'] = feed['id']
- sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id
- sitelinks_data['finalUrlFeedId'] = final_url_feed_attribute_id
- sitelinks_data['line1FeedId'] = line_1_feed_attribute_id
- sitelinks_data['line2FeedId'] = line_2_feed_attribute_id
- else:
- raise errors.GoogleAdsError('No feeds were added.')
-
- # Create site links feed items.
- items_data = [
- {'text': 'Home', 'url': 'http://www.example.com',
- 'line1': 'Home line 1', 'line2': 'Home line 2'},
- {'text': 'Stores', 'url': 'http://www.example.com/stores',
- 'line1': 'Stores line 1', 'line2': 'Stores line 2'},
- {'text': 'On Sale', 'url': 'http://www.example.com/sale',
- 'line1': 'On Sale line 1', 'line2': 'On Sale line 2'},
- {'text': 'Support', 'url': 'http://www.example.com/support',
- 'line1': 'Support line 1', 'line2': 'Support line 2'},
- {'text': 'Products', 'url': 'http://www.example.com/products',
- 'line1': 'Products line 1', 'line2': 'Products line 2'},
- {'text': 'About', 'url': 'http://www.example.com/about',
- 'line1': 'About line 1', 'line2': 'About line 2'}
- ]
-
- feed_items = []
- for item in items_data:
- feed_items.append({
- 'feedId': sitelinks_data['feedId'],
- 'attributeValues': [
- {
- 'feedAttributeId': sitelinks_data['linkTextFeedId'],
- 'stringValue': item['text']
- },
- {
- 'feedAttributeId': sitelinks_data['finalUrlFeedId'],
- 'stringValue': item['url']
- },
- {
- 'feedAttributeId': sitelinks_data['line1FeedId'],
- 'stringValue': item['line1']
- },
- {
- 'feedAttributeId': sitelinks_data['line2FeedId'],
- 'stringValue': item['line2']
- }
- ],
- # Optional: use the 'startTime' and 'endTime' keys to specify the time
- # period for the feed to deliver. The example below will make the feed
- # start now and stop in one month.
- # Make sure you specify the datetime in the customer's time zone. You
- # can retrieve this from customer['dateTimeZone'].
- #
- # ['startTime']: datetime.datetime.now().strftime('%Y%m%d %H%M%S')
- # ['endTime']: (datetime.datetime.now() +
- # relativedelta(months=1)).strftime('%Y%m%d %H%M%S')
-
- # Optional: use the 'scheduling' key to specify time and days of the
- # week for feed to deliver. This is a Beta feature.
- })
-
- feed_items_operations = [{'operator': 'ADD', 'operand': item} for item
- in feed_items]
-
- response = feed_item_service.mutate(feed_items_operations)
- if 'value' in response:
- sitelinks_data['feedItemIds'] = []
- for feed_item in response['value']:
- print 'Feed item with ID %s was added.' % feed_item['feedItemId']
- sitelinks_data['feedItemIds'].append(feed_item['feedItemId'])
- else:
- raise errors.GoogleAdsError('No feed items were added.')
-
- # Create site links feed mapping.
-
- feed_mapping = {
- 'placeholderType': PLACEHOLDER_SITELINKS,
- 'feedId': sitelinks_data['feedId'],
- 'attributeFieldMappings': [
- {
- 'feedAttributeId': sitelinks_data['linkTextFeedId'],
- 'fieldId': PLACEHOLDER_FIELD_SITELINK_LINK_TEXT
- },
- {
- 'feedAttributeId': sitelinks_data['finalUrlFeedId'],
- 'fieldId': PLACEHOLDER_FIELD_SITELINK_FINAL_URL
- },
- {
- 'feedAttributeId': sitelinks_data['line1FeedId'],
- 'fieldId': PLACEHOLDER_FIELD_LINE_1_TEXT
- },
- {
- 'feedAttributeId': sitelinks_data['line2FeedId'],
- 'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT
- }
- ]
- }
-
- response = feed_mapping_service.mutate([
- {'operator': 'ADD', 'operand': feed_mapping}
- ])
- if 'value' in response:
- feed_mapping = response['value'][0]
- print ('Feed mapping with ID %s and placeholder type %s was saved for feed'
- ' with ID %s.' %
- (feed_mapping['feedMappingId'], feed_mapping['placeholderType'],
- feed_mapping['feedId']))
- else:
- raise errors.GoogleAdsError('No feed mappings were added.')
-
- # Create site links campaign feed.
- operands = []
- for feed_item_id in sitelinks_data['feedItemIds']:
- operands.append({
- 'xsi_type': 'ConstantOperand',
- 'type': 'LONG',
- 'longValue': feed_item_id
- })
-
- feed_item_function = {
- 'operator': 'IN',
- 'lhsOperand': [
- {'xsi_type': 'RequestContextOperand', 'contextType': 'FEED_ITEM_ID'}
- ],
- 'rhsOperand': operands
- }
-
- # Optional: to target to a platform, define a function and 'AND' it with the
- # feed item ID link:
- platform_function = {
- 'operator': 'EQUALS',
- 'lhsOperand': [
- {
- 'xsi_type': 'RequestContextOperand',
- 'contextType': 'DEVICE_PLATFORM'
- }
- ],
- 'rhsOperand': [
- {
- 'xsi_type': 'ConstantOperand',
- 'type': 'STRING',
- 'stringValue': 'Mobile'
- }
- ]
- }
- combined_function = {
- 'operator': 'AND',
- 'lhsOperand': [
- {'xsi_type': 'FunctionOperand', 'value': feed_item_function},
- {'xsi_type': 'FunctionOperand', 'value': platform_function}
- ]
- }
-
- campaign_feed = {
- 'feedId': sitelinks_data['feedId'],
- 'campaignId': campaign_id,
- 'matchingFunction': combined_function,
- # Specifying placeholder types on the CampaignFeed allows the same feed
- # to be used for different placeholders in different Campaigns.
- 'placeholderTypes': [PLACEHOLDER_SITELINKS]
- }
-
- response = campaign_feed_service.mutate([
- {'operator': 'ADD', 'operand': campaign_feed}
- ])
- if 'value' in response:
- campaign_feed = response['value'][0]
- print ('Campaign with ID %s was associated with feed with ID %s.' %
- (campaign_feed['campaignId'], campaign_feed['feedId']))
- else:
- raise errors.GoogleAdsError('No campaign feeds were added.')
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201502/migration/__init__.py b/examples/adwords/v201502/migration/__init__.py
deleted file mode 100644
index 5de8ecca..00000000
--- a/examples/adwords/v201502/migration/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Migration examples."""
diff --git a/examples/adwords/v201502/migration/upgrade_ad_url.py b/examples/adwords/v201502/migration/upgrade_ad_url.py
deleted file mode 100755
index 3ccd8c63..00000000
--- a/examples/adwords/v201502/migration/upgrade_ad_url.py
+++ /dev/null
@@ -1,82 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example upgrades an ad to use upgraded URLs.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupAdService.get, AdGroupAdService.upgradeUrl
-"""
-
-__author__ = 'Mark Saniscalchi'
-
-from googleads import adwords
-from googleads import errors
-
-
-ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE'
-AD_ID = 'INSERT_AD_ID_HERE'
-
-
-def main(client, adgroup_id, ad_id):
- # Initialize appropriate service.
- adgroup_ad_service = client.GetService('AdGroupAdService', version='v201502')
-
- selector = {
- 'fields': ['Id', 'Url'],
- 'predicates': [
- {
- 'field': 'AdGroupId',
- 'operator': 'EQUALS',
- 'values': [adgroup_id]
- },
- {
- 'field': 'Id',
- 'operator': 'EQUALS',
- 'values': [ad_id]
- }
- ]
- }
-
- page = adgroup_ad_service.get(selector)
-
- adgroup_ad = page['entries'][0] if page['entries'] else None
-
- if not adgroup_ad:
- raise errors.GoogleAdsError('Ad not found.')
-
- ad_url_upgrade = {
- 'adId': adgroup_ad['ad']['id'],
- 'finalUrl': adgroup_ad['ad']['url']
- }
-
- adgroup_ad = adgroup_ad_service.upgradeUrl([ad_url_upgrade])[0]
-
- if adgroup_ad:
- print ('AdGroupAd with ID %s and destination URL \'%s\' was upgraded.'
- % (adgroup_ad['id'], adgroup_ad['finalUrls'][0]))
- else:
- raise errors.GoogleAdsError('Failed to create AdGroupAd.')
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, ADGROUP_ID, AD_ID)
diff --git a/examples/adwords/v201502/misc/__init__.py b/examples/adwords/v201502/misc/__init__.py
deleted file mode 100644
index 30d42e87..00000000
--- a/examples/adwords/v201502/misc/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Miscellaneous examples."""
diff --git a/examples/adwords/v201502/misc/get_all_images_and_videos.py b/examples/adwords/v201502/misc/get_all_images_and_videos.py
deleted file mode 100755
index 77bffc39..00000000
--- a/examples/adwords/v201502/misc/get_all_images_and_videos.py
+++ /dev/null
@@ -1,80 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all images and videos.
-
-To upload an image, run upload_image.py. To upload video, see:
-http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=39454.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: MediaService.get
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-PAGE_SIZE = 500
-
-
-def main(client):
- # Initialize appropriate service.
- media_service = client.GetService('MediaService', version='v201502')
-
- # Construct selector and get all images.
- offset = 0
- selector = {
- 'fields': ['MediaId', 'Type', 'Width', 'Height', 'MimeType'],
- 'predicates': [{
- 'field': 'Type',
- 'operator': 'IN',
- 'values': ['IMAGE', 'VIDEO']
- }],
- 'paging': {
- 'startIndex': str(offset),
- 'numberResults': str(PAGE_SIZE)
- }
- }
- more_pages = True
- while more_pages:
- page = media_service.get(selector)
-
- # Display results.
- if 'entries' in page:
- for image in page['entries']:
- dimensions = dict([(entry['key'], entry['value'])
- for entry in image['dimensions']])
- print ('Media with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\''
- ' was found.' % (image['mediaId'], dimensions['FULL']['height'],
- dimensions['FULL']['width'], image['mimeType']))
- else:
- print 'No images/videos were found.'
- offset += PAGE_SIZE
- selector['paging']['startIndex'] = str(offset)
- more_pages = offset < int(page['totalNumEntries'])
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201502/misc/upload_image.py b/examples/adwords/v201502/misc/upload_image.py
deleted file mode 100755
index 3d8d7478..00000000
--- a/examples/adwords/v201502/misc/upload_image.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example uploads an image.
-
-To get images, run get_all_images.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: MediaService.upload
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-import base64
-
-from googleads import adwords
-
-
-IMAGE_FILENAME = 'INSERT_IMAGE_PATH_HERE'
-
-
-def main(client, image_filename):
- # Initialize appropriate service.
- media_service = client.GetService('MediaService', version='v201502')
-
- with open(image_filename, 'r') as image_handle:
- image_data = base64.encodestring(image_handle.read())
-
- # Construct media and upload image.
- media = [{
- 'xsi_type': 'Image',
- 'data': image_data,
- 'type': 'IMAGE'
- }]
- media = media_service.upload(media)[0]
-
- # Display results.
- if media:
- dimensions = dict([(entry['key'], entry['value'])
- for entry in media['dimensions']])
- print ('Image with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\' was'
- ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'],
- dimensions['FULL']['width'], media['mimeType']))
- else:
- print 'No images were uploaded.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, IMAGE_FILENAME)
diff --git a/examples/adwords/v201502/optimization/__init__.py b/examples/adwords/v201502/optimization/__init__.py
deleted file mode 100644
index 2e0ca689..00000000
--- a/examples/adwords/v201502/optimization/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Optimization examples."""
diff --git a/examples/adwords/v201502/optimization/estimate_keyword_traffic.py b/examples/adwords/v201502/optimization/estimate_keyword_traffic.py
deleted file mode 100755
index 83387853..00000000
--- a/examples/adwords/v201502/optimization/estimate_keyword_traffic.py
+++ /dev/null
@@ -1,136 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example retrieves keyword traffic estimates.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: TrafficEstimatorService.get
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-def main(client):
- # Initialize appropriate service.
- traffic_estimator_service = client.GetService(
- 'TrafficEstimatorService', version='v201502')
-
- # Construct selector object and retrieve traffic estimates.
- keywords = [
- {'text': 'mars cruise', 'matchType': 'BROAD'},
- {'text': 'cheap cruise', 'matchType': 'PHRASE'},
- {'text': 'cruise', 'matchType': 'EXACT'}
- ]
- negative_keywords = [
- {'text': 'moon walk', 'matchType': 'BROAD'}
- ]
- keyword_estimate_requests = []
- for keyword in keywords:
- keyword_estimate_requests.append({
- 'keyword': {
- 'xsi_type': 'Keyword',
- 'matchType': keyword['matchType'],
- 'text': keyword['text']
- }
- })
-
- for keyword in negative_keywords:
- keyword_estimate_requests.append({
- 'keyword': {
- 'xsi_type': 'Keyword',
- 'matchType': keyword['matchType'],
- 'text': keyword['text']
- },
- 'isNegative': 'true'
- })
-
- selector = {
- 'campaignEstimateRequests': [{
- 'adGroupEstimateRequests': [{
- 'keywordEstimateRequests': keyword_estimate_requests,
- 'maxCpc': {
- 'xsi_type': 'Money',
- 'microAmount': '1000000'
- }
- }],
- 'criteria': [
- {
- 'xsi_type': 'Location',
- 'id': '2840' # United States.
- },
- {
- 'xsi_type': 'Language',
- 'id': '1000' # English.
- }
- ]
- }]
- }
- estimates = traffic_estimator_service.get(selector)
-
- # Display results.
- ad_group_estimate = estimates['campaignEstimates'][0]['adGroupEstimates'][0]
- keyword_estimates = ad_group_estimate['keywordEstimates']
- for index in xrange(len(keyword_estimates)):
- keyword = keyword_estimate_requests[index]['keyword']
- estimate = keyword_estimates[index]
- if keyword_estimate_requests[index].get('isNegative', False):
- continue
-
- # Find the mean of the min and max values.
- mean_avg_cpc = calc_mean(estimate['min']['averageCpc']['microAmount'],
- estimate['max']['averageCpc']['microAmount'])
- mean_avg_pos = calc_mean(estimate['min']['averagePosition'],
- estimate['max']['averagePosition'])
- mean_clicks = calc_mean(estimate['min']['clicksPerDay'],
- estimate['max']['clicksPerDay'])
- mean_total_cost = calc_mean(estimate['min']['totalCost']['microAmount'],
- estimate['max']['totalCost']['microAmount'])
-
- print ('Results for the keyword with text \'%s\' and match type \'%s\':'
- % (keyword['text'], keyword['matchType']))
- print ' Estimated average CPC: %s' % mean_avg_cpc
- print ' Estimated ad position: %s' % mean_avg_pos
- print ' Estimated daily clicks: %s' % mean_clicks
- print ' Estimated daily cost: %s' % mean_total_cost
-
-
-def fmt_mean(mean):
- if mean:
- return '%.2f' % mean
- else:
- return None
-
-
-def calc_mean(min_est, max_est):
- if min_est and max_est:
- return (float(min_est) + float(max_est)) / 2.0
- else:
- return None
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201502/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201502/optimization/get_keyword_bid_simulations.py
deleted file mode 100755
index cfee2131..00000000
--- a/examples/adwords/v201502/optimization/get_keyword_bid_simulations.py
+++ /dev/null
@@ -1,86 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets a bid landscape for an ad group and a criterion.
-
-To get ad groups, run get_ad_groups.py. To get criteria, run get_keywords.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: BidLandscapeService.getBidLandscape
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-CRITERION_ID = 'INSERT_CRITERION_ID_HERE'
-
-
-def main(client, ad_group_id, criterion_id):
- # Initialize appropriate service.
- data_service = client.GetService('DataService', version='v201502')
-
- # Construct bid landscape selector object and retrieve bid landscape.
- selector = {
- 'fields': ['AdGroupId', 'CriterionId', 'StartDate', 'EndDate', 'Bid',
- 'LocalClicks', 'LocalCost', 'LocalImpressions'],
- 'predicates': [
- {
- 'field': 'AdGroupId',
- 'operator': 'EQUALS',
- 'values': [ad_group_id]
- },
- {
- 'field': 'CriterionId',
- 'operator': 'EQUALS',
- 'values': [criterion_id]
- }
- ]
- }
- bid_landscapes = data_service.getCriterionBidLandscape(selector)
-
- # Display results.
- if 'entries' in bid_landscapes:
- for bid_landscape in bid_landscapes['entries']:
- if bid_landscape['BidLandscape.Type'] == 'CriterionBidLandscape':
- print ('Criterion bid landscape with ad group id \'%s\', criterion id '
- '\'%s\', start date \'%s\', end date \'%s\', with landscape '
- 'points was found:'
- % (bid_landscape['adGroupId'], bid_landscape['criterionId'],
- bid_landscape['startDate'], bid_landscape['endDate']))
- for bid_landscape_point in bid_landscape['landscapePoints']:
- print (' bid: %s => clicks: %s, cost: %s, impressions: %s'
- % (bid_landscape_point['bid']['microAmount'],
- bid_landscape_point['clicks'],
- bid_landscape_point['cost']['microAmount'],
- bid_landscape_point['impressions']))
- else:
- print 'No bid landscapes found.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID, CRITERION_ID)
diff --git a/examples/adwords/v201502/optimization/get_keyword_ideas.py b/examples/adwords/v201502/optimization/get_keyword_ideas.py
deleted file mode 100755
index abbe0e3b..00000000
--- a/examples/adwords/v201502/optimization/get_keyword_ideas.py
+++ /dev/null
@@ -1,95 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example retrieves keywords that are related to a given keyword.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: TargetingIdeaService.get
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-PAGE_SIZE = 100
-
-
-def main(client):
- # Initialize appropriate service.
- targeting_idea_service = client.GetService(
- 'TargetingIdeaService', version='v201502')
-
- # Construct selector object and retrieve related keywords.
- offset = 0
- selector = {
- 'searchParameters': [
- {
- 'xsi_type': 'RelatedToQuerySearchParameter',
- 'queries': ['space cruise']
- },
- {
- # Language setting (optional).
- # The ID can be found in the documentation:
- # https://developers.google.com/adwords/api/docs/appendix/languagecodes
- 'xsi_type': 'LanguageSearchParameter',
- 'languages': [{'id': '1000'}]
- }
- ],
- 'ideaType': 'KEYWORD',
- 'requestType': 'IDEAS',
- 'requestedAttributeTypes': ['KEYWORD_TEXT', 'SEARCH_VOLUME',
- 'CATEGORY_PRODUCTS_AND_SERVICES'],
- 'paging': {
- 'startIndex': str(offset),
- 'numberResults': str(PAGE_SIZE)
- }
- }
- more_pages = True
- while more_pages:
- page = targeting_idea_service.get(selector)
-
- # Display results.
- if 'entries' in page:
- for result in page['entries']:
- attributes = {}
- for attribute in result['data']:
- attributes[attribute['key']] = getattr(attribute['value'], 'value',
- '0')
- print ('Keyword with \'%s\' text and average monthly search volume '
- '\'%s\' was found with Products and Services categories: %s.'
- % (attributes['KEYWORD_TEXT'],
- attributes['SEARCH_VOLUME'],
- attributes['CATEGORY_PRODUCTS_AND_SERVICES']))
- print
- else:
- print 'No related keywords were found.'
- offset += PAGE_SIZE
- selector['paging']['startIndex'] = str(offset)
- more_pages = offset < int(page['totalNumEntries'])
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201502/remarketing/__init__.py b/examples/adwords/v201502/remarketing/__init__.py
deleted file mode 100644
index b39776a8..00000000
--- a/examples/adwords/v201502/remarketing/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Remarketing examples."""
diff --git a/examples/adwords/v201502/remarketing/add_audience.py b/examples/adwords/v201502/remarketing/add_audience.py
deleted file mode 100755
index a8cff444..00000000
--- a/examples/adwords/v201502/remarketing/add_audience.py
+++ /dev/null
@@ -1,107 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds a remarketing user list (a.k.a. audience).
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: UserListService.mutate
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-import uuid
-
-from googleads import adwords
-
-
-def main(client):
- # Initialize appropriate service.
- user_list_service = client.GetService(
- 'AdwordsUserListService', version='v201502')
- conversion_tracker_service = client.GetService(
- 'ConversionTrackerService', version='v201502')
-
- # Construct operations and add a user list.
- operations = [
- {
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'BasicUserList',
- 'name': 'Mars cruise customers #%s' % uuid.uuid4(),
- 'description': 'A list of mars cruise customers in the last year',
- 'membershipLifeSpan': '365',
- 'conversionTypes': [
- {
- 'name': ('Mars cruise customers #%s'
- % uuid.uuid4())
- }
- ],
- # Optional field.
- 'status': 'OPEN',
- }
- }
- ]
- result = user_list_service.mutate(operations)
-
- # Display results.
- if 'value' in result:
- conversion_ids = []
- for user_list in result['value']:
- if user_list['conversionTypes']:
- for conversion_type in user_list['conversionTypes']:
- conversion_ids.append(conversion_type['id'])
-
- selector = {
- 'fields': ['Name', 'Status', 'Category'],
- 'predicates': [{
- 'field': 'Id',
- 'operator': 'IN',
- 'values': conversion_ids
- }],
- 'ordering': [{
- 'field': 'Name',
- 'sortOrder': 'ASCENDING'
- }]
- }
-
- pages = conversion_tracker_service.get(selector)
- conversions_map = {}
- if pages['entries']:
- for conversion_tracker in pages['entries']:
- conversions_map[conversion_tracker['id']] = conversion_tracker
-
- for user_list in result['value']:
- print ('User list with name \'%s\' and ID \'%s\' was added.'
- % (user_list['name'], user_list['id']))
- if user_list['conversionTypes']:
- for conversion_type in user_list['conversionTypes']:
- conversion_tracker = conversions_map[conversion_type['id']]
- print ('Conversion type code snippet associated to the list:\n%s\n'
- % conversion_tracker['snippet'])
- else:
- print 'No user lists were added.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201502/remarketing/add_conversion_tracker.py b/examples/adwords/v201502/remarketing/add_conversion_tracker.py
deleted file mode 100755
index 4b65b9ba..00000000
--- a/examples/adwords/v201502/remarketing/add_conversion_tracker.py
+++ /dev/null
@@ -1,77 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the 'License');
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an 'AS IS' BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds an AdWords conversion.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ConversionTrackerService.mutate
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-import uuid
-
-from googleads import adwords
-
-
-def main(client):
- # Initialize appropriate service.
- conversion_tracker_service = client.GetService(
- 'ConversionTrackerService', version='v201502')
-
- # Construct operations and add conversion_tracker.
- operations = [
- {
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'AdWordsConversionTracker',
- 'name': 'Mars cruise customers #%s' % uuid.uuid4(),
- 'category': 'DEFAULT',
- 'markupLanguage': 'HTML',
- 'textFormat': 'HIDDEN',
- # Optional fields.
- 'status': 'ENABLED',
- 'viewthroughLookbackWindow': '15',
- 'isProductAdsChargeable': 'true',
- 'productAdsChargeableConversionWindow': '15',
- 'conversionPageLanguage': 'en',
- 'backgroundColor': '#0000FF',
- 'defaultRevenueValue': '23.41',
- 'alwaysUseDefaultRevenueValue': 'true'
- }
- }
- ]
- conversion_trackers = conversion_tracker_service.mutate(operations)
-
- # Display results.
- for conversion_tracker in conversion_trackers['value']:
- print ('Conversion tracker with id \'%s\', name \'%s\', status \'%s\' '
- 'and category \'%s\' and snippet \n\'%s\'\n was added.\n' %
- (conversion_tracker['id'], conversion_tracker['name'],
- conversion_tracker['status'], conversion_tracker['category'],
- conversion_tracker['snippet']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201502/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201502/remarketing/add_rule_based_user_lists.py
deleted file mode 100755
index bfa1ef50..00000000
--- a/examples/adwords/v201502/remarketing/add_rule_based_user_lists.py
+++ /dev/null
@@ -1,186 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the 'License');
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an 'AS IS' BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds two rule-based remarketing user lists.
-
-Adds two rule-based remarketing user lists; one with no site visit date
-restrictions and another that will only include users who visit your site in
-the next six months.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdwordsUserListService.mutate
-"""
-
-__author__ = 'Mark Saniscalchi'
-
-import calendar
-from datetime import date
-from datetime import datetime
-from datetime import timedelta
-
-from googleads import adwords
-
-
-def main(client):
- # Initialize appropriate service.
- adwords_user_list_service = client.GetService(
- 'AdwordsUserListService', version='v201502')
-
- # First rule item group - users who visited the checkout page and had more
- # than one item in their shopping cart.
- checkout_rule_item = {
- 'StringRuleItem': {
- 'key': {
- 'name': 'ecomm_pagetype'
- },
- 'op': 'EQUALS',
- 'value': 'checkout'
- }
- }
-
- cart_size_rule_item = {
- 'NumberRuleItem': {
- 'key': {
- 'name': 'cartsize'
- },
- 'op': 'GREATER_THAN',
- 'value': '1.0'
- }
- }
-
- # Combine the two rule items into a RuleItemGroup so AdWords will logically
- # AND the rules together.
- checkout_multiple_item_group = {
- 'items': [checkout_rule_item, cart_size_rule_item]
- }
-
- # Second rule item group - users who checked out within the next 3 months.
- today = date.today()
- start_date_rule_item = {
- 'DateRuleItem': {
- 'key': {
- 'name': 'checkoutdate'
- },
- 'op': 'AFTER',
- 'value': today.strftime('%Y%m%d')
- }
- }
-
- three_months_later = AddMonths(today, 3)
-
- three_months_later_rule_item = {
- 'DateRuleItem': {
- 'key': {
- 'name': 'checkoutdate'
- },
- 'op': 'BEFORE',
- 'value': three_months_later.strftime('%Y%m%d')
- }
- }
-
- # Combine the date rule items into a RuleItemGroup
- checked_out_date_range_item_group = {
- 'items': [start_date_rule_item, three_months_later_rule_item]
- }
-
- # Combine the rule item groups into a Rule so AdWords will logically OR the
- # groups together.
- rule = {
- 'groups': [
- checkout_multiple_item_group,
- checked_out_date_range_item_group
- ]
- }
-
- # Create the user list with no restrictions on site visit date.
- expression_user_list = {
- 'xsi_type': 'ExpressionRuleUserList',
- 'name': 'Expression-based user list created at %s'
- % datetime.today().strftime('%Y%m%d %H:%M:%S'),
- 'description': 'Users who checked out in three month window OR visited'
- ' the checkout page with more than one item in their'
- ' cart.',
- 'rule': rule
- }
-
- # Create the user list restricted to users who visit your site within the next
- # six months.
- end_date = AddMonths(today, 6)
-
- date_user_list = {
- 'xsi_type': 'DateSpecificRuleUserList',
- 'name': 'Date rule user list created at %s'
- % datetime.today().strftime('%Y%m%d %H:%M:%S'),
- 'description': 'Users who visited the site between %s and %s and checked'
- ' out in three month window OR visited the checkout page'
- ' with more than one item in their cart.'
- % (today.strftime('%Y%m%d'), end_date.strftime('%Y%m%d')),
- 'rule': rule,
- 'startDate': today.strftime('%Y%m%d'),
- 'endDate': end_date.strftime('%Y%m%d')
- }
-
- # Create operations to add the user lists.
- operations = [
- {
- 'operand': user_list,
- 'operator': 'ADD',
- } for user_list in [expression_user_list, date_user_list]
- ]
-
- # Submit the operations.
- user_lists = adwords_user_list_service.mutate(operations)
-
- # Display results.
- for user_list in user_lists['value']:
- print (('User list added with ID %d, name "%s", status "%s", list type'
- ' "%s", accountUserListStatus "%s", description "%s".') %
- (user_list['id'], user_list['name'],
- user_list['status'], user_list['listType'],
- user_list['accountUserListStatus'], user_list['description']))
-
-
-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 number of months to add.
-
- Returns:
- A date equal to the start date incremented by the given number of months.
- """
- current_date = start_date
- i = 0
- while i < months:
- month_days = calendar.monthrange(current_date.year, current_date.month)[1]
- current_date += timedelta(days=month_days)
- i += 1
- return current_date
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201502/reporting/__init__.py b/examples/adwords/v201502/reporting/__init__.py
deleted file mode 100644
index 85eee62f..00000000
--- a/examples/adwords/v201502/reporting/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Reporting examples."""
diff --git a/examples/adwords/v201502/reporting/download_criteria_report.py b/examples/adwords/v201502/reporting/download_criteria_report.py
deleted file mode 100755
index cd2dd747..00000000
--- a/examples/adwords/v201502/reporting/download_criteria_report.py
+++ /dev/null
@@ -1,65 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example downloads a criteria performance report.
-
-To get report fields, run get_report_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ReportDefinitionService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = 'Mark Saniscalchi'
-
-import logging
-import sys
-
-from googleads import adwords
-
-logging.basicConfig(level=logging.INFO)
-logging.getLogger('suds.transport').setLevel(logging.DEBUG)
-
-
-def main(client):
- report_downloader = client.GetReportDownloader(version='v201502')
-
- # Create report definition.
- report = {
- 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT',
- 'dateRangeType': 'LAST_7_DAYS',
- 'reportType': 'CRITERIA_PERFORMANCE_REPORT',
- 'downloadFormat': 'CSV',
- 'selector': {
- 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType',
- 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost']
- },
- # Enable to get rows with zero impressions.
- 'includeZeroImpressions': 'false'
- }
-
- # You can provide a file object to write the output to. For this demonstration
- # we use sys.stdout to write the report to the screen.
- report_downloader.DownloadReport(report, sys.stdout)
-
-
-if __name__ == '__main__':
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
- main(adwords_client)
diff --git a/examples/adwords/v201502/reporting/download_criteria_report_as_stream.py b/examples/adwords/v201502/reporting/download_criteria_report_as_stream.py
deleted file mode 100755
index 964b6e38..00000000
--- a/examples/adwords/v201502/reporting/download_criteria_report_as_stream.py
+++ /dev/null
@@ -1,78 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example retrieves the report download stream.
-
-To get report fields, run get_report_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ReportDefinitionService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = 'Mark Saniscalchi'
-
-import logging
-import StringIO
-import sys
-
-from googleads import adwords
-
-
-logging.basicConfig(level=logging.INFO)
-logging.getLogger('suds.transport').setLevel(logging.DEBUG)
-
-
-def main(client):
- report_downloader = client.GetReportDownloader(version='v201502')
-
- # Create report definition.
- report = {
- 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT',
- 'dateRangeType': 'LAST_7_DAYS',
- 'reportType': 'CRITERIA_PERFORMANCE_REPORT',
- 'downloadFormat': 'CSV',
- 'selector': {
- 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType',
- 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost']
- },
- # Enable to get rows with zero impressions.
- 'includeZeroImpressions': 'false'
- }
-
- # Retrieve the report stream and print it out
- report_data = StringIO.StringIO()
- stream_data = report_downloader.DownloadReportAsStream(report)
-
- try:
- while True:
- chunk = stream_data.read(adwords.CHUNK_SIZE)
- if not chunk: break
- report_data.write(chunk.decode() if sys.version_info[0] == 3
- and getattr(report_data, 'mode', 'w') == 'w' else chunk)
- print report_data.getvalue()
- finally:
- report_data.close()
- stream_data.close()
-
-
-if __name__ == '__main__':
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
- main(adwords_client)
diff --git a/examples/adwords/v201502/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201502/reporting/download_criteria_report_as_stream_with_awql.py
deleted file mode 100755
index 960740aa..00000000
--- a/examples/adwords/v201502/reporting/download_criteria_report_as_stream_with_awql.py
+++ /dev/null
@@ -1,82 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example downloads a criteria performance report as a string with AWQL.
-
-To get report fields, run get_report_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ReportDefinitionService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-import logging
-import StringIO
-import sys
-
-
-from googleads import adwords
-
-
-logging.basicConfig(level=logging.INFO)
-logging.getLogger('suds.transport').setLevel(logging.DEBUG)
-
-# Specify where to download the file here.
-PATH = '/tmp/report_download.csv'
-
-
-def main(client):
- # Initialize appropriate service.
- report_downloader = client.GetReportDownloader(version='v201502')
-
- # Create report query.
- report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, '
- 'FinalUrls, Impressions, Clicks, Cost '
- 'FROM CRITERIA_PERFORMANCE_REPORT '
- 'WHERE Status IN [ENABLED, PAUSED] '
- 'DURING LAST_7_DAYS')
-
- print report_downloader.DownloadReportAsStringWithAwql(report_query, 'CSV')
-
- # Retrieve the report stream and print it out
- report_data = StringIO.StringIO()
- stream_data = report_downloader.DownloadReportAsStreamWithAwql(report_query,
- 'CSV')
-
- try:
- while True:
- chunk = stream_data.read(adwords.CHUNK_SIZE)
- if not chunk: break
- report_data.write(chunk.decode() if sys.version_info[0] == 3
- and getattr(report_data, 'mode', 'w') == 'w' else chunk)
- print report_data.getvalue()
- finally:
- report_data.close()
- stream_data.close()
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201502/reporting/download_criteria_report_as_string.py b/examples/adwords/v201502/reporting/download_criteria_report_as_string.py
deleted file mode 100755
index c667b24c..00000000
--- a/examples/adwords/v201502/reporting/download_criteria_report_as_string.py
+++ /dev/null
@@ -1,63 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example downloads a criteria performance report as a string.
-
-To get report fields, run get_report_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ReportDefinitionService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = 'Mark Saniscalchi'
-
-import logging
-
-from googleads import adwords
-
-logging.basicConfig(level=logging.INFO)
-logging.getLogger('suds.transport').setLevel(logging.DEBUG)
-
-
-def main(client):
- report_downloader = client.GetReportDownloader(version='v201502')
-
- # Create report definition.
- report = {
- 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT',
- 'dateRangeType': 'LAST_7_DAYS',
- 'reportType': 'CRITERIA_PERFORMANCE_REPORT',
- 'downloadFormat': 'CSV',
- 'selector': {
- 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType',
- 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost']
- },
- # Enable to get rows with zero impressions.
- 'includeZeroImpressions': 'false'
- }
-
- # Print out the report as a string
- print report_downloader.DownloadReportAsString(report)
-
-
-if __name__ == '__main__':
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
- main(adwords_client)
diff --git a/examples/adwords/v201502/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201502/reporting/download_criteria_report_as_string_with_awql.py
deleted file mode 100755
index cc5c90e8..00000000
--- a/examples/adwords/v201502/reporting/download_criteria_report_as_string_with_awql.py
+++ /dev/null
@@ -1,58 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example downloads a criteria performance report as a string with AWQL.
-
-To get report fields, run get_report_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ReportDefinitionService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-# Specify where to download the file here.
-PATH = '/tmp/report_download.csv'
-
-
-def main(client):
- # Initialize appropriate service.
- report_downloader = client.GetReportDownloader(version='v201502')
-
- # Create report query.
- report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, '
- 'FinalUrls, Impressions, Clicks, Cost '
- 'FROM CRITERIA_PERFORMANCE_REPORT '
- 'WHERE Status IN [ENABLED, PAUSED] '
- 'DURING LAST_7_DAYS')
-
- print report_downloader.DownloadReportAsStringWithAwql(report_query, 'CSV')
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201502/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201502/reporting/download_criteria_report_with_awql.py
deleted file mode 100755
index 75cb3451..00000000
--- a/examples/adwords/v201502/reporting/download_criteria_report_with_awql.py
+++ /dev/null
@@ -1,61 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example downloads a criteria performance report with AWQL.
-
-To get report fields, run get_report_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ReportDefinitionService.mutate
-Api: AdWordsOnly
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-# Specify where to download the file here.
-PATH = '/tmp/report_download.csv'
-
-
-def main(client, path):
- # Initialize appropriate service.
- report_downloader = client.GetReportDownloader(version='v201502')
-
- # Create report query.
- report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, '
- 'FinalUrls, Impressions, Clicks, Cost '
- 'FROM CRITERIA_PERFORMANCE_REPORT '
- 'WHERE Status IN [ENABLED, PAUSED] '
- 'DURING LAST_7_DAYS')
-
- with open(path, 'w') as output_file:
- report_downloader.DownloadReportWithAwql(report_query, 'CSV', output_file)
-
- print 'Report was downloaded to \'%s\'.' % path
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, PATH)
diff --git a/examples/adwords/v201502/reporting/get_report_fields.py b/examples/adwords/v201502/reporting/get_report_fields.py
deleted file mode 100755
index 408d4926..00000000
--- a/examples/adwords/v201502/reporting/get_report_fields.py
+++ /dev/null
@@ -1,56 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets report fields.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ReportDefinitionService.getReportFields
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-REPORT_TYPE = 'INSERT_REPORT_TYPE_HERE'
-
-
-def main(client, report_type):
- # Initialize appropriate service.
- report_definition_service = client.GetService(
- 'ReportDefinitionService', version='v201502')
-
- # Get report fields.
- fields = report_definition_service.getReportFields(report_type)
-
- # Display results.
- print 'Report type \'%s\' contains the following fields:' % report_type
- for field in fields:
- print ' - %s (%s)' % (field['fieldName'], field['fieldType'])
- if 'enumValues' in field:
- print ' := [%s]' % ', '.join(field['enumValues'])
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, REPORT_TYPE)
diff --git a/examples/adwords/v201502/shopping/__init__.py b/examples/adwords/v201502/shopping/__init__.py
deleted file mode 100644
index 96422728..00000000
--- a/examples/adwords/v201502/shopping/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Shopping examples."""
diff --git a/examples/adwords/v201502/shopping/add_product_partition_tree.py b/examples/adwords/v201502/shopping/add_product_partition_tree.py
deleted file mode 100755
index 56d7a02c..00000000
--- a/examples/adwords/v201502/shopping/add_product_partition_tree.py
+++ /dev/null
@@ -1,285 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates a ProductPartition tree.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupCriterionService.mutate
-"""
-
-__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import adwords
-
-ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-class ProductPartitionHelper(object):
- """A helper for creating ProductPartition trees."""
-
- # The next temporary criterion ID to be used.
- # When creating our tree we need to specify the parent-child relationships
- # between nodes. However, until a criterion has been created on the server we
- # do not have a criterion ID with which to refer to it.
- # Instead we can specify temporary IDs that are specific to a single mutate
- # request. Once the criteria have been created they are assigned an ID as
- # normal and the temporary ID will no longer refer to it.
- # A valid temporary ID is any negative integer.
- next_id = -1
-
- # The set of mutate operations needed to create the current tree.
- operations = []
-
- def __init__(self, adgroup_id):
- """Initializer.
-
- Args:
- adgroup_id: The ID of the AdGroup that we wish to attach the partition
- tree to.
- """
- self.adgroup_id = adgroup_id
-
- 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',
- 'partitionType': 'SUBDIVISION',
- 'id': str(self.next_id)
- }
-
- # The root has neither a parent nor a value.
- if parent is not None:
- division['parentCriterionId'] = parent['id']
- division['caseValue'] = value
-
- adgroup_criterion = {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': self.adgroup_id,
- 'criterion': division
- }
-
- self.CreateAddOperation(adgroup_criterion)
- self.next_id -= 1
-
- return division
-
- 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.
- """
- unit = {
- 'xsi_type': 'ProductPartition',
- 'partitionType': 'UNIT'
- }
-
- # The root node has neither a parent nor a value.
- if parent is not None:
- unit['parentCriterionId'] = parent['id']
- unit['caseValue'] = value
-
- if bid_amount is not None and bid_amount > 0:
- bidding_strategy_configuration = {
- 'bids': [{
- 'xsi_type': 'CpcBid',
- 'bid': {
- 'xsi_type': 'Money',
- 'microAmount': str(bid_amount)
- }
- }]
- }
-
- adgroup_criterion = {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'biddingStrategyConfiguration': bidding_strategy_configuration
- }
- else:
- adgroup_criterion = {
- 'xsi_type': 'NegativeAdGroupCriterion'
- }
-
- adgroup_criterion['adGroupId'] = self.adgroup_id
- adgroup_criterion['criterion'] = unit
-
- self.CreateAddOperation(adgroup_criterion)
-
- return unit
-
- def GetOperations(self):
- """Returns the set of mutate operations needed to create the current tree.
-
- Returns:
- The set of operations
- """
- return self.operations
-
- def CreateAddOperation(self, criterion):
- """Creates an AdGroupCriterionOperation for the given criterion.
-
- Args:
- criterion: The criterion we want to add.
- """
- operation = {
- 'operator': 'ADD',
- 'operand': criterion
- }
-
- self.operations.append(operation)
-
-
-def main(client, adgroup_id):
- """Runs the example."""
- adgroup_criterion_service = client.GetService(
- 'AdGroupCriterionService', version='v201502')
-
- helper = ProductPartitionHelper(adgroup_id)
-
- # The most trivial partition tree has only a unit node as the root, e.g.:
- # helper.CreateUnit(bid_amount=100000)
-
- root = helper.CreateSubdivision()
-
- new_product_canonical_condition = {
- 'xsi_type': 'ProductCanonicalCondition',
- 'condition': 'NEW'
- }
-
- used_product_canonical_condition = {
- 'xsi_type': 'ProductCanonicalCondition',
- 'condition': 'USED'
- }
-
- other_product_canonical_condition = {
- 'xsi_type': 'ProductCanonicalCondition',
- }
-
- helper.CreateUnit(root, new_product_canonical_condition, 200000)
- helper.CreateUnit(root, used_product_canonical_condition, 100000)
- other_condition = helper.CreateSubdivision(
- root, other_product_canonical_condition)
-
- cool_product_brand = {
- 'xsi_type': 'ProductBrand',
- 'value': 'CoolBrand'
- }
-
- cheap_product_brand = {
- 'xsi_type': 'ProductBrand',
- 'value': 'CheapBrand'
- }
-
- other_product_brand = {
- 'xsi_type': 'ProductBrand',
- }
-
- helper.CreateUnit(other_condition, cool_product_brand, 900000)
- helper.CreateUnit(other_condition, cheap_product_brand, 10000)
- other_brand = helper.CreateSubdivision(other_condition, other_product_brand)
-
- # The value for the bidding category is a fixed ID for the 'Luggage & Bags'
- # category. You can retrieve IDs for categories from the ConstantDataService.
- # See the 'GetProductTaxonomy' example for more details.
- luggage_category = {
- 'xsi_type': 'ProductBiddingCategory',
- 'type': 'BIDDING_CATEGORY_L1',
- 'value': '-5914235892932915235'
- }
-
- generic_category = {
- 'xsi_type': 'ProductBiddingCategory',
- 'type': 'BIDDING_CATEGORY_L1',
- }
-
- helper.CreateUnit(other_brand, luggage_category, 750000)
- helper.CreateUnit(other_brand, generic_category, 110000)
-
- # Make the mutate request
- result = adgroup_criterion_service.mutate(helper.GetOperations())
-
- children = {}
-
- root_node = None
-
- # For each criterion, make an array containing each of its children.
- # We always create the parent before the child, so we can rely on that here.
- for adgroup_criterion in result['value']:
- children[adgroup_criterion['criterion']['id']] = []
-
- if 'parentCriterionId' in adgroup_criterion['criterion']:
- children[adgroup_criterion['criterion']['parentCriterionId']].append(
- adgroup_criterion['criterion'])
- else:
- root_node = adgroup_criterion['criterion']
-
- # Show the tree
- DisplayTree(root_node, 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_value = node['caseValue']
- node_type = case_value['ProductDimension.Type']
-
- if node_type == 'ProductCanonicalCondition':
- value = (case_value['condition'] if 'condition' in case_value
- else 'OTHER')
- elif node_type == 'ProductBiddingCategory':
- value = '%s(%s)' % (case_value['type'], case_value['value']
- if 'value' in case_value else 'OTHER')
- else:
- value = (case_value['value'] if 'value' in case_value else 'OTHER')
-
- print ('%sid: %s, node_type: %s, value: %s\n'
- % (' ' * level, node['id'], node_type, value))
-
- for child_node in children[node['id']]:
- DisplayTree(child_node, children, level + 1)
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, ADGROUP_ID)
-
diff --git a/examples/adwords/v201502/shopping/add_product_scope.py b/examples/adwords/v201502/shopping/add_product_scope.py
deleted file mode 100755
index 9ac3d667..00000000
--- a/examples/adwords/v201502/shopping/add_product_scope.py
+++ /dev/null
@@ -1,107 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Restricts products that will be included in a campaign with a ProductScope.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignCriterionService.mutate
-"""
-
-__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import adwords
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-
-
-def main(client, campaign_id):
- campaign_criterion_service = client.GetService(
- 'CampaignCriterionService', version='v201502')
-
- product_scope = {
- 'xsi_type': 'ProductScope',
- # This set of dimensions is for demonstration purposes only. It would be
- # extremely unlikely that you want to include so many dimensions in your
- # product scope.
- 'dimensions': [
- {
- 'xsi_type': 'ProductBrand',
- 'value': 'Nexus'
- },
- {
- 'xsi_type': 'ProductCanonicalCondition',
- 'condition': 'NEW'
- },
- {
- 'xsi_type': 'ProductCustomAttribute',
- 'type': 'CUSTOM_ATTRIBUTE_0',
- 'value': 'my attribute value'
- },
- {
- 'xsi_type': 'ProductOfferId',
- 'value': 'book1'
- },
- {
- 'xsi_type': 'ProductType',
- 'type': 'PRODUCT_TYPE_L1',
- 'value': 'Media'
- },
- {
- 'xsi_type': 'ProductType',
- 'type': 'PRODUCT_TYPE_L2',
- 'value': 'Books'
- },
- # The value for the bidding category is a fixed ID for the "Luggage
- # & Bags" category. You can retrieve IDs for categories from the
- # ConstantDataService. See the "GetProductCategoryTaxonomy" example
- # for more details.
- {
- 'xsi_type': 'ProductBiddingCategory',
- 'type': 'BIDDING_CATEGORY_L1',
- 'value': '-5914235892932915235'
- }
- ]
- }
-
- campaign_criterion = {
- 'campaignId': campaign_id,
- 'criterion': product_scope
- }
-
- operations = [{
- 'operator': 'ADD',
- 'operand': campaign_criterion
- }]
-
- # Make the request
- result = campaign_criterion_service.mutate(operations)
-
- for criterion in result['value']:
- print ('Created a ProductScope criterion with Id: %s'
- % criterion['criterion']['id'])
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201502/shopping/add_shopping_campaign.py b/examples/adwords/v201502/shopping/add_shopping_campaign.py
deleted file mode 100755
index 3cbe4da8..00000000
--- a/examples/adwords/v201502/shopping/add_shopping_campaign.py
+++ /dev/null
@@ -1,124 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds a Shopping campaign.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignService.mutate, AdGroupService.mutate, AdGroupAdService.mutate
-"""
-
-__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import adwords
-
-BUDGET_ID = 'INSERT_BUDGET_ID_HERE'
-MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE'
-
-
-def main(client, budget_id, merchant_id):
- campaign_service = client.GetService('CampaignService', version='v201502')
- ad_group_service = client.GetService('AdGroupService', version='v201502')
- ad_group_ad_service = client.GetService('AdGroupAdService', version='v201502')
-
- # Create campaign
- campaign = {
- 'name': 'Shopping campaign #%s' % uuid.uuid4(),
- # The advertisingChannelType is what makes this a shopping campaign
- 'advertisingChannelType': 'SHOPPING',
- # Set shared budget (required)
- 'budget': {
- 'budgetId': budget_id
- },
- 'biddingStrategyConfiguration': {
- 'biddingStrategyType': 'MANUAL_CPC'
- },
- 'settings': [
- # All shopping campaigns need a ShoppingSetting
- {
- 'xsi_type': 'ShoppingSetting',
- 'salesCountry': 'US',
- 'campaignPriority': '0',
- 'merchantId': merchant_id,
- # Set to "True" to enable Local Inventory Ads in your campaign.
- 'enableLocal': True
- }
- ]
- }
-
- campaign_operations = [{
- 'operator': 'ADD',
- 'operand': campaign
- }]
-
- result = campaign_service.mutate(campaign_operations)
-
- for campaign in result['value']:
- print ('Campaign with name \'%s\' and ID \'%s\' was added.'
- % (campaign['name'], campaign['id']))
-
- # Create the AdGroup
- adgroup = {
- 'campaignId': campaign['id'],
- 'name': 'AdGroup #%s' % uuid.uuid4()
- }
-
- adgroup_operations = {
- 'operator': 'ADD',
- 'operand': adgroup
- }
-
- # Make the mutate request to add the AdGroup to the Shopping Campaign
- ad_group_result = ad_group_service.mutate(adgroup_operations)
-
- for adgroup in ad_group_result['value']:
- print ('AdGroup with name \'%s\' and ID \'%s\' was added.'
- % (adgroup['name'], adgroup['id']))
-
- # Create an AdGroup Ad
- adgroup_ad = {
- 'adGroupId': adgroup['id'],
- # Create ProductAd
- 'ad': {
- 'xsi_type': 'ProductAd',
- 'Ad.Type': 'ProductAd'
- }
- }
-
- ad_operation = {
- 'operator': 'ADD',
- 'operand': adgroup_ad
- }
-
- # Make the mutate request to add the ProductAd to the AdGroup
- ad_result = ad_group_ad_service.mutate([ad_operation])
-
- for adgroup_ad in ad_result['value']:
- print 'ProductAd with ID \'%s\' was added.' % adgroup_ad['ad']['id']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, BUDGET_ID, MERCHANT_ID)
diff --git a/examples/adwords/v201502/shopping/get_product_category_taxonomy.py b/examples/adwords/v201502/shopping/get_product_category_taxonomy.py
deleted file mode 100755
index ac82093d..00000000
--- a/examples/adwords/v201502/shopping/get_product_category_taxonomy.py
+++ /dev/null
@@ -1,99 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example fetches the set of valid ProductBiddingCategories.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ConstantDataService.getProductBiddingCategoryData
-"""
-
-__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import adwords
-
-
-def main(client):
- service = client.GetService('ConstantDataService', version='v201502')
-
- selector = {
- 'predicates': [
- {
- 'field': 'Country',
- 'operator': 'IN',
- 'values': ['US']
- }
- ]
- }
-
- result = service.getProductBiddingCategoryData(selector)
-
- bidding_categories = {}
- root_categories = []
-
- for product_bidding_category in result:
- category_id = product_bidding_category['dimensionValue']['value']
- parent_id = None
- name = product_bidding_category['displayValue'][0]['value']
-
- # Note: There may be cases where there isn't a value.
- if ('parentDimensionValue' in product_bidding_category and
- 'value' in product_bidding_category['parentDimensionValue']):
- parent_id = product_bidding_category['parentDimensionValue']['value']
-
- if category_id not in bidding_categories:
- bidding_categories[category_id] = {}
-
- category = bidding_categories[category_id]
-
- if parent_id is not None:
- if parent_id not in bidding_categories:
- bidding_categories[parent_id] = {}
-
- parent = bidding_categories[parent_id]
-
- if 'children' not in parent:
- parent['children'] = []
-
- parent['children'].append(category)
- else:
- root_categories.append(category)
-
- category['id'] = category_id
- category['name'] = name
-
- DisplayCategories(root_categories)
-
-
-def DisplayCategories(categories, prefix=''):
- for category in categories:
- print '%s%s [%s]' % (prefix, category['name'], category['id'])
-
- if 'children' in category:
- DisplayCategories(category['children'], '%s%s > ' % (prefix,
- category['name']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201502/targeting/__init__.py b/examples/adwords/v201502/targeting/__init__.py
deleted file mode 100644
index 2c027ccc..00000000
--- a/examples/adwords/v201502/targeting/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Targeting examples."""
diff --git a/examples/adwords/v201502/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201502/targeting/add_campaign_targeting_criteria.py
deleted file mode 100755
index cdbddd74..00000000
--- a/examples/adwords/v201502/targeting/add_campaign_targeting_criteria.py
+++ /dev/null
@@ -1,159 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds various types of targeting criteria to a given campaign.
-
-To get campaigns, run get_campaigns.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignCriterionService.mutate
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-
-
-def main(client, campaign_id):
- # Initialize appropriate service.
- campaign_criterion_service = client.GetService(
- 'CampaignCriterionService', version='v201502')
-
- # Create locations. The IDs can be found in the documentation or retrieved
- # with the LocationCriterionService.
- california = {
- 'xsi_type': 'Location',
- 'id': '21137'
- }
- mexico = {
- 'xsi_type': 'Location',
- 'id': '2484'
- }
-
- # Create languages. The IDs can be found in the documentation or retrieved
- # with the ConstantDataService.
- english = {
- 'xsi_type': 'Language',
- 'id': '1000'
- }
- spanish = {
- 'xsi_type': 'Language',
- 'id': '1003'
- }
-
- # Create location groups. The IDs can be found in the documentation or
- # retrieved with the LocationCriterionService.
- florida_tier3 = {
- 'xsi_type': 'LocationGroups',
- 'matchingFunction': {
- 'operator': 'AND',
- 'lhsOperand': [{
- 'xsi_type': 'IncomeOperand',
- # Tiers are numbered 1-10, and represent 10% segments of earners.
- # For example, TIER_1 is the top 10%, TIER_2 is the 80-90%, etc.
- # Tiers 6 through 10 are grouped into TIER_6_TO_10.
- 'tier': 'TIER_3'
- }],
- 'rhsOperand': [{
- 'xsi_type': 'GeoTargetOperand',
- 'locations': [1015116] # Miami, FL
- }]
- },
- }
- florida_downtown = {
- 'xsi_type': 'LocationGroups',
- 'matchingFunction': {
- 'operator': 'AND',
- 'lhsOperand': [{
- 'xsi_type': 'PlacesOfInterestOperand',
- # Other valid options: AIRPORT, UNIVERSITY.
- 'category': 'DOWNTOWN',
- }],
- 'rhsOperand': [{
- 'xsi_type': 'GeoTargetOperand',
- 'locations': [1015116] # Miami, FL
- }]
- }
- }
- # Distance targeting. Area of 10 miles around targets above.
- distance_10_miles = {
- 'xsi_type': 'LocationGroups',
- 'matchingFunction': {
- 'operator': 'IDENTITY',
- 'lhsOperand': [{
- 'xsi_type': 'LocationExtensionOperand',
- 'radius': {
- 'xsi_type': 'ConstantOperand',
- 'type': 'DOUBLE',
- 'unit': 'MILES',
- 'doubleValue': 10
- }
-
- }]
- }
- }
- # Create a negative campaign criterion operation.
- negative_campaign_criterion_operand = {
- 'xsi_type': 'NegativeCampaignCriterion',
- 'campaignId': campaign_id,
- 'criterion': {
- 'xsi_type': 'Keyword',
- 'matchType': 'BROAD',
- 'text': 'jupiter cruise'
- }
- }
-
- # Create operations
- operations = []
- for criterion in [california, mexico, english, spanish, florida_tier3,
- florida_downtown, distance_10_miles]:
- operations.append({
- 'operator': 'ADD',
- 'operand': {
- 'campaignId': campaign_id,
- 'criterion': criterion
- }
- })
- # Add the negative campaign criterion.
- operations.append({
- 'operator': 'ADD',
- 'operand': negative_campaign_criterion_operand
- })
-
- # Make the mutate request.
- result = campaign_criterion_service.mutate(operations)
-
- # Display the resulting campaign criteria.
- for campaign_criterion in result['value']:
- print ('Campaign criterion with campaign id \'%s\', criterion id \'%s\', '
- 'and type \'%s\' was added.'
- % (campaign_criterion['campaignId'],
- campaign_criterion['criterion']['id'],
- campaign_criterion['criterion']['type']))
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201502/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201502/targeting/add_demographic_targeting_criteria.py
deleted file mode 100755
index 8e0a8c63..00000000
--- a/examples/adwords/v201502/targeting/add_demographic_targeting_criteria.py
+++ /dev/null
@@ -1,99 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds demographic criteria to an ad group.
-
-To get a list of ad groups, run get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupCriterionService.mutate
-"""
-
-__author__ = 'Joseph Dilallo'
-
-from googleads import adwords
-
-
-GENDER_MALE = '10'
-AGE_RANGE_UNDETERMINED = '503999'
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Initialize appropriate service.
- ad_group_criterion_service = client.GetService(
- 'AdGroupCriterionService', version='v201502')
-
- # Create the ad group criteria.
- ad_group_criteria = [
- # Targeting criterion.
- {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Gender',
- # Create gender criteria. The IDs can be found in the
- # documentation:
- # https://developers.google.com/adwords/api/docs/appendix/genders.
- 'id': GENDER_MALE
- }
- },
- # Exclusion criterion.
- {
- 'xsi_type': 'NegativeAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'AgeRange',
- # Create age range criteria. The IDs can be found in the
- # documentation:
- # https://developers.google.com/adwords/api/docs/appendix/ages.
- 'id': AGE_RANGE_UNDETERMINED
- }
- }
- ]
-
- # Create operations.
- operations = []
- for criterion in ad_group_criteria:
- operations.append({
- 'operator': 'ADD',
- 'operand': criterion
- })
-
- response = ad_group_criterion_service.mutate(operations)
-
- if response and response['value']:
- criteria = response['value']
- for ad_group_criterion in criteria:
- criterion = ad_group_criterion['criterion']
- print ('Ad group criterion with ad group ID %s, criterion ID %s and '
- 'type \'%s\' was added.' %
- (ad_group_criterion['adGroupId'], criterion['id'],
- criterion['type']))
- else:
- print 'No criteria were returned.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201502/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201502/targeting/get_campaign_targeting_criteria.py
deleted file mode 100755
index c1868d72..00000000
--- a/examples/adwords/v201502/targeting/get_campaign_targeting_criteria.py
+++ /dev/null
@@ -1,89 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example illustrates how to retrieve all the campaign targets.
-
-To set campaign targets, run add_campaign_targeting_criteria.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignCriterionService.get
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-PAGE_SIZE = 500
-
-
-def main(client):
- # Initialize appropriate service.
- campaign_criterion_service = client.GetService(
- 'CampaignCriterionService', version='v201502')
-
- # Construct selector and get all campaign targets.
- offset = 0
- selector = {
- 'fields': ['CampaignId', 'Id', 'CriteriaType', 'PlatformName',
- 'LanguageName', 'LocationName', 'KeywordText'],
- 'predicates': [{
- 'field': 'CriteriaType',
- 'operator': 'IN',
- 'values': ['KEYWORD', 'LANGUAGE', 'LOCATION', 'PLATFORM']
- }],
- 'paging': {
- 'startIndex': str(offset),
- 'numberResults': str(PAGE_SIZE)
- }
- }
- more_pages = True
- while more_pages:
- page = campaign_criterion_service.get(selector)
-
- # Display results.
- if 'entries' in page:
- for campaign_criterion in page['entries']:
- negative = ''
- if (campaign_criterion['CampaignCriterion.Type']
- == 'NegativeCampaignCriterion'):
- negative = 'Negative '
- criterion = campaign_criterion['criterion']
- criteria = (criterion['text'] if 'text' in criterion else
- criterion['platformName'] if 'platformName' in criterion
- else criterion['name'] if 'name' in criterion else
- criterion['locationName'] if 'locationName' in criterion
- else None)
- print ('%sCampaign Criterion found for Campaign ID %s with type %s and '
- 'criteria "%s".' % (negative, campaign_criterion['campaignId'],
- criterion['type'], criteria))
- else:
- print 'No campaign targets were found.'
- offset += PAGE_SIZE
- selector['paging']['startIndex'] = str(offset)
- more_pages = offset < int(page['totalNumEntries'])
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201502/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201502/targeting/get_targetable_languages_and_carriers.py
deleted file mode 100755
index 61a6f2a2..00000000
--- a/examples/adwords/v201502/targeting/get_targetable_languages_and_carriers.py
+++ /dev/null
@@ -1,60 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Retrieves all languages and carriers available for targeting.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ConstantDataService.getLanguageCriterion
-Tags: ConstantDataService.getCarrierCriterion
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-def main(client):
- # Initialize appropriate service.
- constant_data_service = client.GetService(
- 'ConstantDataService', version='v201502')
-
- # Get all languages.
- languages = constant_data_service.getLanguageCriterion()
-
- # Display results.
- for language in languages:
- print ('Language with name \'%s\' and ID \'%s\' was found.'
- % (language['name'], language['id']))
-
- # Get all carriers.
- carriers = constant_data_service.getCarrierCriterion()
-
- # Display results.
- for carrier in carriers:
- print ('Carrier with name \'%s\', ID \'%s\', and country code \'%s\' was '
- 'found.' % (carrier['name'], carrier['id'], carrier['countryCode']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201502/targeting/lookup_location.py b/examples/adwords/v201502/targeting/lookup_location.py
deleted file mode 100755
index 761ddb1e..00000000
--- a/examples/adwords/v201502/targeting/lookup_location.py
+++ /dev/null
@@ -1,86 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all LocationCriterion.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: LocationCriterionService.get
-"""
-
-__author__ = ('api.kwinter@gmail.com (Kevin Winter)'
- 'Joseph DiLallo')
-
-from googleads import adwords
-
-
-def GetLocationString(location):
- return '%s (%s)' % (location['locationName'], location['displayType']
- if 'displayType' in location else None)
-
-
-def main(client):
- # Initialize appropriate service.
- location_criterion_service = client.GetService(
- 'LocationCriterionService', version='v201502')
-
- location_names = ['Paris', 'Quebec', 'Spain', 'Deutchland']
-
- # Create the selector.
- selector = {
- 'fields': ['Id', 'LocationName', 'DisplayType', 'CanonicalName',
- 'ParentLocations', 'Reach', 'TargetingStatus'],
- 'predicates': [{
- 'field': 'LocationName',
- 'operator': 'IN',
- 'values': location_names
- }, {
- 'field': 'Locale',
- 'operator': 'EQUALS',
- 'values': ['en']
- }]
- }
-
- # Make the get request.
- location_criteria = location_criterion_service.get(selector)
-
- # Display the resulting location criteria.
- for location_criterion in location_criteria:
- parent_string = ''
- if ('parentLocations' in location_criterion['location']
- and location_criterion['location']['parentLocations']):
- parent_string = ', '.join([GetLocationString(parent)for parent in
- location_criterion['location']
- ['parentLocations']])
- print ('The search term \'%s\' returned the location \'%s\' of type \'%s\''
- ' with parent locations \'%s\', reach \'%s\' and id \'%s\' (%s)'
- % (location_criterion['searchTerm'],
- location_criterion['location']['locationName'],
- location_criterion['location']['displayType'], parent_string,
- location_criterion['reach']
- if 'reach' in location_criterion else None,
- location_criterion['location']['id'],
- location_criterion['location']['targetingStatus']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adwords/v201809/__init__.py b/examples/adwords/v201809/__init__.py
new file mode 100644
index 00000000..16ff256a
--- /dev/null
+++ b/examples/adwords/v201809/__init__.py
@@ -0,0 +1,15 @@
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Examples for AdWords."""
diff --git a/examples/adwords/v201809/account_management/__init__.py b/examples/adwords/v201809/account_management/__init__.py
new file mode 100644
index 00000000..94b5520f
--- /dev/null
+++ b/examples/adwords/v201809/account_management/__init__.py
@@ -0,0 +1,15 @@
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Account management examples."""
diff --git a/examples/adwords/v201809/account_management/accept_service_link.py b/examples/adwords/v201809/account_management/accept_service_link.py
new file mode 100755
index 00000000..354f87e0
--- /dev/null
+++ b/examples/adwords/v201809/account_management/accept_service_link.py
@@ -0,0 +1,62 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example accepts a pending Google Merchant Center invitation link.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+from googleads import adwords
+
+
+SERVICE_LINK_ID = 'INSERT_SERVICE_LINK_ID_HERE'
+
+
+def main(client, service_link_id):
+ # Initialize appropriate service.
+ customer_service = client.GetService(
+ 'CustomerService', version='v201809')
+
+ # Create the operation to set the status to ACTIVE.
+ operations = [{
+ 'operator': 'SET',
+ 'operand': {
+ 'serviceLinkId': service_link_id,
+ 'serviceType': 'MERCHANT_CENTER',
+ 'linkStatus': 'ACTIVE',
+ }
+ }]
+
+ # Update the service link.
+ mutated_service_links = customer_service.mutateServiceLinks(operations)
+
+ # Display results.
+ for mutated_service_link in mutated_service_links:
+ print('Service link with service link ID "%s", type "%s" was updated '
+ 'to status: "%s".' % (mutated_service_link['serviceLinkId'],
+ mutated_service_link['serviceType'],
+ mutated_service_link['linkStatus']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+ main(adwords_client, SERVICE_LINK_ID)
diff --git a/examples/adwords/v201809/account_management/create_account.py b/examples/adwords/v201809/account_management/create_account.py
new file mode 100755
index 00000000..8932714e
--- /dev/null
+++ b/examples/adwords/v201809/account_management/create_account.py
@@ -0,0 +1,63 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example illustrates how to create an account.
+
+Note by default this account will only be accessible via its parent AdWords
+manager account..
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+from datetime import datetime
+from googleads import adwords
+
+
+def main(client):
+ # Initialize appropriate service.
+ managed_customer_service = client.GetService(
+ 'ManagedCustomerService', version='v201809')
+
+ today = datetime.today().strftime('%Y%m%d %H:%M:%S')
+ # Construct operations and add campaign.
+ operations = [{
+ 'operator': 'ADD',
+ 'operand': {
+ 'name': 'Account created with ManagedCustomerService on %s' % today,
+ 'currencyCode': 'EUR',
+ 'dateTimeZone': 'Europe/London',
+ }
+ }]
+
+ # Create the account. It is possible to create multiple accounts with one
+ # request by sending an array of operations.
+ accounts = managed_customer_service.mutate(operations)
+
+ # Display results.
+ for account in accounts['value']:
+ print('Account with customer ID "%s" was successfully created.'
+ % account['customerId'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+ main(adwords_client)
diff --git a/examples/adwords/v201809/account_management/get_account_changes.py b/examples/adwords/v201809/account_management/get_account_changes.py
new file mode 100755
index 00000000..9bbed1c7
--- /dev/null
+++ b/examples/adwords/v201809/account_management/get_account_changes.py
@@ -0,0 +1,99 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets the changes in the account during the last 24 hours.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import datetime
+from googleads import adwords
+
+
+def main(client):
+ # Initialize appropriate service.
+ customer_sync_service = client.GetService(
+ 'CustomerSyncService', version='v201809')
+ campaign_service = client.GetService('CampaignService', version='v201809')
+
+ # Construct selector and get all campaigns.
+ selector = {
+ 'fields': ['Id', 'Name', 'Status']
+ }
+ campaigns = campaign_service.get(selector)
+ campaign_ids = []
+ if 'totalNumEntries' in campaigns and campaigns['totalNumEntries'] > 0:
+ for campaign in campaigns['entries']:
+ campaign_ids.append(campaign['id'])
+ else:
+ print('No campaigns were found.')
+ return
+
+ # Construct selector and get all changes.
+ today = datetime.datetime.today()
+ yesterday = today - datetime.timedelta(1)
+ selector = {
+ 'dateTimeRange': {
+ 'min': yesterday.strftime('%Y%m%d %H%M%S'),
+ 'max': today.strftime('%Y%m%d %H%M%S')
+ },
+ 'campaignIds': campaign_ids
+ }
+ account_changes = customer_sync_service.get(selector)
+
+ # Display results.
+ if account_changes:
+ if 'lastChangeTimestamp' in account_changes:
+ print('Most recent changes: %s' % account_changes['lastChangeTimestamp'])
+ if account_changes['changedCampaigns']:
+ for data in account_changes['changedCampaigns']:
+ print('Campaign with id "%s" has change status "%s".'
+ % (data['campaignId'], data['campaignChangeStatus']))
+ if (data['campaignChangeStatus'] != 'NEW' and
+ data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'):
+ if 'addedCampaignCriteria' in data:
+ print(' Added campaign criteria: %s' %
+ data['addedCampaignCriteria'])
+ if 'removedCampaignCriteria' in data:
+ print(' Removed campaign criteria: %s' %
+ data['removedCampaignCriteria'])
+ if 'changedAdGroups' in data:
+ for ad_group_data in data['changedAdGroups']:
+ print(' Ad group with id "%s" has change status "%s".'
+ % (ad_group_data['adGroupId'],
+ ad_group_data['adGroupChangeStatus']))
+ if ad_group_data['adGroupChangeStatus'] != 'NEW':
+ if 'changedAds' in ad_group_data:
+ print(' Changed ads: %s' % ad_group_data['changedAds'])
+ if 'changedCriteria' in ad_group_data:
+ print(' Changed criteria: %s' %
+ ad_group_data['changedCriteria'])
+ if 'removedCriteria' in ad_group_data:
+ print(' Removed criteria: %s' %
+ ad_group_data['removedCriteria'])
+ else:
+ print('No changes were found.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+ main(adwords_client)
diff --git a/examples/adwords/v201809/account_management/get_account_hierarchy.py b/examples/adwords/v201809/account_management/get_account_hierarchy.py
new file mode 100755
index 00000000..d6a7cb84
--- /dev/null
+++ b/examples/adwords/v201809/account_management/get_account_hierarchy.py
@@ -0,0 +1,104 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets the account hierarchy under the current account.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+from googleads import adwords
+
+
+PAGE_SIZE = 500
+
+
+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 = '-' * depth * 2
+ print('%s%s, %s' % (prefix, account['customerId'], account['name']))
+ if account['customerId'] in links:
+ for child_link in links[account['customerId']]:
+ child_account = accounts[child_link['clientCustomerId']]
+ DisplayAccountTree(child_account, accounts, links, depth + 1)
+
+
+def main(client):
+ # Initialize appropriate service.
+ managed_customer_service = client.GetService(
+ 'ManagedCustomerService', version='v201809')
+
+ # Construct selector to get all accounts.
+ offset = 0
+ selector = {
+ 'fields': ['CustomerId', 'Name'],
+ 'paging': {
+ 'startIndex': str(offset),
+ 'numberResults': str(PAGE_SIZE)
+ }
+ }
+ more_pages = True
+ accounts = {}
+ child_links = {}
+ parent_links = {}
+ root_account = None
+
+ while more_pages:
+ # Get serviced account graph.
+ page = managed_customer_service.get(selector)
+ if 'entries' in page and page['entries']:
+ # Create map from customerId to parent and child links.
+ if 'links' in page:
+ for link in page['links']:
+ if link['managerCustomerId'] not in child_links:
+ child_links[link['managerCustomerId']] = []
+ child_links[link['managerCustomerId']].append(link)
+ if link['clientCustomerId'] not in parent_links:
+ parent_links[link['clientCustomerId']] = []
+ parent_links[link['clientCustomerId']].append(link)
+ # Map from customerID to account.
+ for account in page['entries']:
+ accounts[account['customerId']] = account
+ offset += PAGE_SIZE
+ selector['paging']['startIndex'] = str(offset)
+ more_pages = offset < int(page['totalNumEntries'])
+
+ # Find the root account.
+ for customer_id in accounts:
+ if customer_id not in parent_links:
+ root_account = accounts[customer_id]
+
+ # Display account tree.
+ if root_account:
+ print('CustomerId, Name')
+ DisplayAccountTree(root_account, accounts, child_links, 0)
+ else:
+ print('Unable to determine a root account')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+ main(adwords_client)
diff --git a/examples/adwords/v201809/advanced_operations/__init__.py b/examples/adwords/v201809/advanced_operations/__init__.py
new file mode 100644
index 00000000..dc91ba79
--- /dev/null
+++ b/examples/adwords/v201809/advanced_operations/__init__.py
@@ -0,0 +1,15 @@
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Advanced operations examples."""
diff --git a/examples/adwords/v201809/advanced_operations/add_ad_customizer.py b/examples/adwords/v201809/advanced_operations/add_ad_customizer.py
new file mode 100755
index 00000000..9fa43c1d
--- /dev/null
+++ b/examples/adwords/v201809/advanced_operations/add_ad_customizer.py
@@ -0,0 +1,257 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Adds an ad customizer feed.
+
+Associates the feed with customer and adds an ad that uses the feed to populate
+dynamic data.
+
+"""
+
+
+from datetime import datetime
+from uuid import uuid4
+
+# Import appropriate classes from the client library.
+from googleads import adwords
+from googleads import errors
+
+
+FEED_NAME = 'Interplanetary Feed Name %s' % uuid4()
+ADGROUPS = [
+ 'INSERT_ADGROUP_ID_1_HERE',
+ 'INSERT_ADGROUP_ID_2_HERE'
+]
+
+
+def CreateAdsWithCustomizations(client, adgroup_ids, feed_name):
+ """Creates ExpandedTextAds that use ad customizations for specified AdGroups.
+
+ Args:
+ client: an AdWordsClient instance.
+ adgroup_ids: a list containing the AdGroup ids to add ExpandedTextAds to.
+ feed_name: the name of the feed used to apply customizations.
+
+ Raises:
+ GoogleAdsError: if no ExpandedTextAds were added.
+ """
+ # Get the AdGroupAdService
+ adgroup_ad_service = client.GetService('AdGroupAdService', 'v201809')
+
+ expanded_text_ad = {
+ 'xsi_type': 'ExpandedTextAd',
+ 'headlinePart1': 'Luxury Cruise to {=%s.Name}' % feed_name,
+ 'headlinePart2': 'Only {=%s.Price}' % feed_name,
+ 'description': 'Offer ends in {=countdown(%s.Date)}!' % feed_name,
+ 'finalUrls': ['http://www.example.com'],
+ }
+
+ # We add the same ad to both ad groups. When they serve, they will show
+ # different values, since they match different feed items.
+ operations = [{
+ 'operator': 'ADD',
+ 'operand': {
+ 'adGroupId': adgroup,
+ 'ad': expanded_text_ad
+ }
+ } for adgroup in adgroup_ids]
+
+ response = adgroup_ad_service.mutate(operations)
+
+ if response and 'value' in response:
+ for ad in response['value']:
+ print('Created an ad with ID "%s", type "%s", and status "%s".'
+ % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status']))
+ else:
+ raise errors.GoogleAdsError('No ads were added.')
+
+
+def CreateCustomizerFeed(client, feed_name):
+ """Creates a new AdCustomizerFeed.
+
+ Args:
+ client: an AdWordsClient instance.
+ feed_name: the name for the new AdCustomizerFeed.
+
+ Returns:
+ The new AdCustomizerFeed.
+ """
+ # Get the AdCustomizerFeedService
+ ad_customizer_feed_service = client.GetService('AdCustomizerFeedService',
+ 'v201809')
+ customizer_feed = {
+ 'feedName': feed_name,
+ 'feedAttributes': [
+ {'type': 'STRING', 'name': 'Name'},
+ {'type': 'STRING', 'name': 'Price'},
+ {'type': 'DATE_TIME', 'name': 'Date'}
+ ]
+ }
+
+ feed_service_operation = {
+ 'operator': 'ADD',
+ 'operand': customizer_feed
+ }
+
+ response = ad_customizer_feed_service.mutate([feed_service_operation])
+
+ if response and 'value' in response:
+ feed = response['value'][0]
+ feed_data = {
+ 'feedId': feed['feedId'],
+ 'nameId': feed['feedAttributes'][0]['id'],
+ 'priceId': feed['feedAttributes'][1]['id'],
+ 'dateId': feed['feedAttributes'][2]['id']
+ }
+ print('Feed with name "%s" and ID %s was added with:\n'
+ '\tName attribute ID %s and price attribute ID %s and date attribute'
+ 'ID %s') % (feed['feedName'], feed['feedId'], feed_data['nameId'],
+ feed_data['priceId'], feed_data['dateId'])
+ return feed
+ else:
+ raise errors.GoogleAdsError('No feeds were added')
+
+
+def RestrictFeedItemToAdGroup(client, feed_item, adgroup_id):
+ """Restricts the feed item to an ad group.
+
+ Args:
+ client: an AdWordsClient instance.
+ feed_item: The feed item.
+ adgroup_id: The ad group ID.
+ """
+ # Get the FeedItemTargetService
+ feed_item_target_service = client.GetService(
+ 'FeedItemTargetService', 'v201809')
+
+ # Optional: Restrict the first feed item to only serve with ads for the
+ # specified ad group ID.
+ ad_group_target = {
+ 'xsi_type': 'FeedItemAdGroupTarget',
+ 'feedId': feed_item['feedId'],
+ 'feedItemId': feed_item['feedItemId'],
+ 'adGroupId': adgroup_id
+ }
+
+ operation = {'operator': 'ADD', 'operand': ad_group_target}
+
+ response = feed_item_target_service.mutate([operation])
+ new_ad_group_target = response['value'][0]
+
+ print('Feed item target for feed ID %s and feed item ID %s was created to '
+ 'restrict serving to ad group ID %s' %
+ (new_ad_group_target['feedId'],
+ new_ad_group_target['feedItemId'],
+ new_ad_group_target['adGroupId']))
+
+
+def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed):
+ """Creates FeedItems for the specified AdGroups.
+
+ These FeedItems contain values to use in ad customizations for the AdGroups.
+
+ Args:
+ client: an AdWordsClient instance.
+ adgroup_ids: a list containing two AdGroup Ids.
+ ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems
+ with.
+
+ Raises:
+ GoogleAdsError: if no FeedItems were added.
+ """
+ # Get the FeedItemService
+ feed_item_service = client.GetService('FeedItemService', 'v201809')
+ now = datetime.now()
+ mars_date = datetime(now.year, now.month, 1, 0, 0)
+ venus_date = datetime(now.year, now.month, 15, 0, 0)
+ time_format = '%Y%m%d %H%M%S'
+
+ feed_item_operations = [
+ CreateFeedItemAddOperation(
+ 'Mars', '$1234.56', mars_date.strftime(time_format),
+ ad_customizer_feed),
+ CreateFeedItemAddOperation(
+ 'Venus', '$1450.00', venus_date.strftime(time_format),
+ ad_customizer_feed)
+ ]
+
+ response = feed_item_service.mutate(feed_item_operations)
+
+ if 'value' in response:
+ for feed_item in response['value']:
+ print('Added FeedItem with ID %d.' % feed_item['feedItemId'])
+ else:
+ raise errors.GoogleAdsError('No FeedItems were added.')
+
+ for feed_item, adgroup_id in zip(response['value'], adgroup_ids):
+ RestrictFeedItemToAdGroup(client, feed_item, adgroup_id)
+
+
+def CreateFeedItemAddOperation(name, price, date, ad_customizer_feed):
+ """Creates a FeedItemOperation.
+
+ The generated FeedItemOperation will create a FeedItem with the specified
+ values when sent to FeedItemService.mutate.
+
+ Args:
+ name: the value for the name attribute of the FeedItem.
+ price: the value for the price attribute of the FeedItem.
+ date: the value for the date attribute of the FeedItem.
+ ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems
+ with.
+
+ Returns:
+ A new FeedItemOperation for adding a FeedItem.
+ """
+ feed_item = {
+ 'feedId': ad_customizer_feed['feedId'],
+ 'attributeValues': [
+ {
+ 'feedAttributeId': ad_customizer_feed['feedAttributes'][0]['id'],
+ 'stringValue': name
+ },
+ {
+ 'feedAttributeId': ad_customizer_feed['feedAttributes'][1]['id'],
+ 'stringValue': price
+ },
+ {
+ 'feedAttributeId': ad_customizer_feed['feedAttributes'][2]['id'],
+ 'stringValue': date
+ }
+ ]
+ }
+
+ operation = {
+ 'operator': 'ADD',
+ 'operand': feed_item
+ }
+
+ return operation
+
+
+def main(client, adgroup_ids, feed_name=FEED_NAME):
+ # Create a customizer feed. One feed per account can be used for all ads.
+ ad_customizer_feed = CreateCustomizerFeed(client, feed_name)
+ # Add feed items containing the values we'd like to place in ads.
+ CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed)
+ # All set! We can now create ads with customizations.
+ CreateAdsWithCustomizations(client, adgroup_ids, feed_name)
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+ main(adwords_client, ADGROUPS)
diff --git a/examples/adwords/v201809/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201809/advanced_operations/add_ad_group_bid_modifier.py
new file mode 100755
index 00000000..5ff880cf
--- /dev/null
+++ b/examples/adwords/v201809/advanced_operations/add_ad_group_bid_modifier.py
@@ -0,0 +1,75 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Adds an ad group level mobile bid modifier override for a campaign.
+
+To get your ad groups, run get_ad_groups.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from googleads import adwords
+
+
+AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
+BID_MODIFIER = 'INSERT_BID_MODIFIER_HERE'
+
+
+def main(client, ad_group_id, bid_modifier):
+ # Initialize appropriate service.
+ ad_group_bid_modifier_service = client.GetService(
+ 'AdGroupBidModifierService', version='v201809')
+
+ # Mobile criterion ID.
+ criterion_id = '30001'
+
+ # Prepare to add an ad group level override.
+ operation = {
+ # Use 'ADD' to add a new modifier and 'SET' to update an existing one. A
+ # modifier can be removed with the 'REMOVE' operator.
+ 'operator': 'ADD',
+ 'operand': {
+ 'adGroupId': ad_group_id,
+ 'criterion': {
+ 'xsi_type': 'Platform',
+ 'id': criterion_id
+ },
+ 'bidModifier': bid_modifier
+ }
+ }
+
+ # Add ad group level mobile bid modifier.
+ response = ad_group_bid_modifier_service.mutate([operation])
+ if response and response['value']:
+ modifier = response['value'][0]
+ value = modifier['bidModifier'] if 'bidModifier' in modifier else 'unset'
+ print('Campaign ID %s, AdGroup ID %s, Criterion ID %s was updated with '
+ 'ad group level modifier: %s' %
+ (modifier['campaignId'], modifier['adGroupId'],
+ modifier['criterion']['id'], value))
+ else:
+ print('No modifiers were added.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, AD_GROUP_ID, BID_MODIFIER)
diff --git a/examples/adwords/v201809/advanced_operations/add_dynamic_page_feed.py b/examples/adwords/v201809/advanced_operations/add_dynamic_page_feed.py
new file mode 100755
index 00000000..34b461d2
--- /dev/null
+++ b/examples/adwords/v201809/advanced_operations/add_dynamic_page_feed.py
@@ -0,0 +1,296 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Adds page feed to specify URLs to use with your Dynamic Search Ads campaign.
+
+To create a Dynamic Search Ads campaign, run add_dynamic_search_ad_campaign.py.
+To get campaigns, run get_campaigns.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+"""
+
+from collections import namedtuple
+import uuid
+
+from googleads import adwords
+
+
+AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
+CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
+
+# Used to keep track of DSA page feed details.
+_DSAFeedDetails = namedtuple(
+ '_DSAFeedDetails', ['feed_id', 'url_attribute_id', 'label_attribute_id'])
+# ID that corresponds to the labels.
+DSA_LABEL_FIELD_ID = 2
+# The criterion type to be used for DSA page feeds.
+DSA_PAGE_FEED_CRITERION_TYPE = 61
+DSA_PAGE_URL_LABEL = 'discounts'
+# ID that corresponds to the page URLs.
+DSA_PAGE_URLS_FIELD_ID = 1
+
+
+def main(client, campaign_id, ad_group_id):
+ # Get the page feed details. This code example creates a new feed, but you can
+ # fetch and re-use an existing feed.
+ feed_details = _CreateFeed(client)
+ _CreateFeedMapping(client, feed_details)
+ _CreateFeedItems(client, feed_details, DSA_PAGE_URL_LABEL)
+
+ # Associate the page feed with the campaign.
+ _UpdateCampaignDSASetting(client, campaign_id, feed_details.feed_id)
+
+ # Optional: Target web pages matching the feed's label in the ad group.
+ _AddDSATargeting(client, ad_group_id, DSA_PAGE_URL_LABEL)
+
+ print('Dynamic page feed setup complete for campaign ID "%d".' % campaign_id)
+
+
+def _CreateFeed(client):
+ """Creates the feed for DSA page URLs.
+
+ Args:
+ client: an AdWordsClient instance.
+
+ Returns:
+ A _DSAFeedDetails instance containing details about the created feed.
+ """
+ # Get the FeedService.
+ feed_service = client.GetService('FeedService', version='v201809')
+
+ # Create operation.
+ operation = {
+ # Create the feed.
+ 'operand': {
+ 'name': 'DSA Feed %s' % uuid.uuid4(),
+ # Create attributes.
+ 'attributes': [
+ {'type': 'URL_LIST', 'name': 'Page URL'},
+ {'type': 'STRING_LIST', 'name': 'Label'}
+ ],
+ 'origin': 'USER'
+ },
+ 'operator': 'ADD'
+ }
+
+ # Add the feed.
+ feed = feed_service.mutate([operation])['value'][0]
+ return _DSAFeedDetails(feed['id'], feed['attributes'][0]['id'],
+ feed['attributes'][1]['id'])
+
+
+def _CreateFeedMapping(client, feed_details):
+ """Creates the feed mapping for DSA page feeds.
+
+ Args:
+ client: an AdWordsClient instance.
+ feed_details: a _DSAFeedDetails instance.
+ """
+ # Get the FeedMappingService.
+ feed_mapping_service = client.GetService('FeedMappingService',
+ version='v201809')
+
+ # Create the operation.
+ operation = {
+ # Create the feed mapping.
+ 'operand': {
+ 'criterionType': DSA_PAGE_FEED_CRITERION_TYPE,
+ 'feedId': feed_details.feed_id,
+ # Map the feedAttributeIds to the fieldId constants.
+ 'attributeFieldMappings': [
+ {
+ 'feedAttributeId': feed_details.url_attribute_id,
+ 'fieldId': DSA_PAGE_URLS_FIELD_ID
+ },
+ {
+ 'feedAttributeId': feed_details.label_attribute_id,
+ 'fieldId': DSA_LABEL_FIELD_ID
+ }
+ ]
+ },
+ 'operator': 'ADD'
+ }
+
+ # Add the feed mapping.
+ feed_mapping_service.mutate([operation])
+
+
+def _CreateFeedItems(client, feed_details, label_name):
+ """Creates the page URLs in the DSA page feed.
+
+ Args:
+ client: an AdWordsClient instance.
+ feed_details: a _DSAFeedDetails instance.
+ label_name: a str containing the page feed URL label.
+ """
+ # Get the FeedItemService.
+ feed_item_service = client.GetService('FeedItemService', version='v201809')
+
+ # For page feed URL recommendations and rules, see:
+ # https://support.google.com/adwords/answer/7166527
+ urls = ('http://www.example.com/discounts/rental-cars?id={feeditem}',
+ 'http://www.example.com/discounts/hotel-deals?id={feeditem}',
+ 'http://www.example.com/discounts/flight-deals?id={feeditem}')
+
+ # Create the operation.
+ operations = [{
+ # Create the feed item.
+ 'operand': {
+ 'feedId': feed_details.feed_id,
+ 'attributeValues': [
+ {
+ 'feedAttributeId': feed_details.url_attribute_id,
+ 'stringValues': [url]
+ },
+ {
+ 'feedAttributeId': feed_details.label_attribute_id,
+ 'stringValues': [label_name]
+ }
+ ]
+ },
+ 'operator': 'ADD'
+ } for url in urls]
+
+ # Add the feed item.
+ feed_item_service.mutate(operations)
+
+
+def _UpdateCampaignDSASetting(client, campaign_id, feed_id):
+ """Updates the campaign DSA setting to DSA pagefeeds.
+
+ Args:
+ client: an AdWordsClient instance.
+ campaign_id: a str Campaign ID.
+ feed_id: a str page Feed ID.
+
+ Raises:
+ ValueError: If the given campaign is found not to be a dynamic search ad
+ campaign.
+ """
+ # Get the CampaignService.
+ campaign_service = client.GetService('CampaignService', version='v201809')
+
+ selector = {
+ 'fields': ['Id', 'Settings'],
+ 'predicates': [{
+ 'field': 'Id',
+ 'operator': 'EQUALS',
+ 'values': [campaign_id]
+ }]
+ }
+
+ response = campaign_service.get(selector)
+
+ if response['totalNumEntries']:
+ campaign = response['entries'][0]
+ else:
+ raise ValueError('No campaign with ID "%d" exists.' % campaign_id)
+
+ if not campaign['settings']:
+ raise ValueError('This is not a DSA campaign.')
+
+ dsa_setting = None
+
+ campaign_settings = campaign['settings']
+
+ for setting in campaign_settings:
+ if setting['Setting.Type'] == 'DynamicSearchAdsSetting':
+ dsa_setting = setting
+ break
+
+ if dsa_setting is None:
+ raise ValueError('This is not a DSA campaign.')
+
+ dsa_setting['pageFeed'] = {
+ 'feedIds': [feed_id]
+ }
+
+ # Optional: Specify whether only the supplied URLs should be used with your
+ # Dynamic Search Ads.
+ dsa_setting['useSuppliedUrlsOnly'] = True
+
+ operation = {
+ 'operand': {
+ 'id': campaign_id,
+ 'settings': campaign_settings
+ },
+ 'operator': 'SET'
+ }
+
+ campaign_service.mutate([operation])
+ print('DSA page feed for campaign ID "%d" was updated with feed ID "%d".' % (
+ campaign_id, feed_id))
+
+
+def _AddDSATargeting(client, ad_group_id, label_name):
+ """Set custom targeting for the page feed URLs based on a list of labels.
+
+ Args:
+ client: an AdWordsClient instance.
+ ad_group_id: a str AdGroup ID.
+ label_name: a str label name.
+
+ Returns:
+ A zeep.objects.BiddableAdGroupCriterion representing the newly created
+ webpage criterion.
+ """
+ # Get the AdGroupCriterionService.
+ ad_group_criterion_service = client.GetService('AdGroupCriterionService',
+ version='v201809')
+
+ # Create the operation.
+ operation = {
+ 'operand': {
+ 'xsi_type': 'BiddableAdGroupCriterion',
+ 'adGroupId': ad_group_id,
+ # Create a webpage criterion.
+ 'criterion': {
+ 'xsi_type': 'Webpage',
+ 'parameter': {
+ 'criterionName': 'Test criterion',
+ # Add a condition for label=specified_label_name.
+ 'conditions': [{
+ 'operand': 'CUSTOM_LABEL',
+ 'argument': label_name
+ }],
+ }
+ },
+ # Set a custom bid for this criterion
+ 'biddingStrategyConfiguration': {
+ 'bids': [{
+ 'xsi_type': 'CpcBid',
+ 'bid': {
+ 'microAmount': 1500000
+ }
+ }]
+ }
+ },
+ 'operator': 'ADD'
+ }
+
+ criterion = ad_group_criterion_service.mutate([operation])['value'][0]
+ print('Web page criterion with ID "%d" and status "%s" was created.' % (
+ criterion['criterion']['id'], criterion['userStatus']))
+ return criterion
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+ main(adwords_client, CAMPAIGN_ID, AD_GROUP_ID)
diff --git a/examples/adwords/v201809/advanced_operations/add_dynamic_search_ads_campaign.py b/examples/adwords/v201809/advanced_operations/add_dynamic_search_ads_campaign.py
new file mode 100755
index 00000000..2f154e36
--- /dev/null
+++ b/examples/adwords/v201809/advanced_operations/add_dynamic_search_ads_campaign.py
@@ -0,0 +1,259 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example adds a Dynamic Search Ads campaign.
+
+To get campaigns, run get_campaigns.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+"""
+
+
+import datetime
+import uuid
+from googleads import adwords
+
+
+def main(client):
+ budget = _CreateBudget(client)
+ campaign_id = _CreateCampaign(client, budget)
+ ad_group_id = _CreateAdGroup(client, campaign_id)
+ _CreateExpandedDSA(client, ad_group_id)
+ _AddWebPageCriteria(client, ad_group_id)
+
+ print('Dynamic Search Ads campaign setup is complete.')
+
+
+def _CreateBudget(client):
+ """Creates the budget.
+
+ Args:
+ client: an AdWordsClient instance.
+
+ Returns:
+ a zeep.objects.Budget representation of the created budget.
+ """
+ budget_service = client.GetService('BudgetService', version='v201809')
+
+ # Create the campaign budget
+ operation = {
+ 'operand': {
+ 'name': 'Interplanetary Cruise Budget #%d' % uuid.uuid4(),
+ 'deliveryMethod': 'STANDARD',
+ 'amount': {
+ 'microAmount': 500000
+ }
+ },
+ 'operator': 'ADD'
+ }
+
+ budget = budget_service.mutate([operation])['value'][0]
+
+ print('Budget with ID "%d" and name "%s" was created.' % (
+ budget['budgetId'], budget['name']))
+
+ return budget
+
+
+def _CreateCampaign(client, budget):
+ """Creates the campaign.
+
+ Args:
+ client: an AdWordsClient instance.
+ budget: a zeep.objects.Budget representation of a created budget.
+
+ Returns:
+ An integer campaign ID.
+ """
+ campaign_service = client.GetService('CampaignService')
+
+ operations = [{
+ 'operator': 'ADD',
+ 'operand': {
+ 'name': 'Interplanetary Cruise #%d' % uuid.uuid4(),
+ # Recommendation: Set the campaign to PAUSED when creating it to
+ # prevent the ads from immediately serving. Set to ENABLED once you've
+ # added targeting and the ads are ready to serve.
+ 'status': 'PAUSED',
+ 'advertisingChannelType': 'SEARCH',
+ 'biddingStrategyConfiguration': {
+ 'biddingStrategyType': 'MANUAL_CPC',
+ },
+ 'budget': budget,
+ # Required: Set the campaign's Dynamic Search Ad settings.
+ 'settings': [{
+ 'xsi_type': 'DynamicSearchAdsSetting',
+ # Required: Set the domain name and language.
+ 'domainName': 'example.com',
+ 'languageCode': 'en'
+ }],
+ # Optional: Set the start date.
+ 'startDate': (datetime.datetime.now() +
+ datetime.timedelta(1)).strftime('%Y%m%d'),
+ # Optional: Set the end date.
+ 'endDate': (datetime.datetime.now() +
+ datetime.timedelta(365)).strftime('%Y%m%d'),
+ }
+ }]
+
+ campaign = campaign_service.mutate(operations)['value'][0]
+ campaign_id = campaign['id']
+
+ print('Campaign with ID "%d" and name "%s" was added.' % (
+ campaign_id, campaign['name']))
+
+ return campaign_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': {
+ 'campaignId': campaign_id,
+ 'adGroupType': 'SEARCH_DYNAMIC_ADS',
+ 'name': 'Earth to Mars Cruises #%d' % uuid.uuid4(),
+ 'status': 'PAUSED',
+ 'biddingStrategyConfiguration': {
+ 'bids': [{
+ 'xsi_type': 'CpcBid',
+ 'bid': {
+ 'microAmount': '3000000'
+ },
+ }]
+ }
+ }
+ }]
+
+ ad_group = ad_group_service.mutate(operations)['value'][0]
+ ad_group_id = ad_group['id']
+
+ print('Ad group with ID "%d" and name "%s" was created.' % (
+ ad_group_id, ad_group['name']))
+
+ return ad_group_id
+
+
+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')
+
+ # Create the operation
+ operations = [{
+ 'operator': 'ADD',
+ 'operand': {
+ 'xsi_type': 'AdGroupAd',
+ 'adGroupId': ad_group_id,
+ # Create the expanded dynamic search ad. This ad will have its
+ # headline and final URL auto-generated at serving time according to
+ # domain name specific information provided by DynamicSearchAdsSetting
+ # at the campaign level.
+ 'ad': {
+ 'xsi_type': 'ExpandedDynamicSearchAd',
+ # Set the ad description.
+ 'description': 'Buy your tickets now!',
+ 'description2': 'Discount ends soon'
+ },
+ # Optional: Set the status.
+ 'status': 'PAUSED',
+ }
+ }]
+
+ # Create the ad.
+ ad = ad_group_ad_service.mutate(operations)['value'][0]['ad']
+
+ # Display the results.
+ print('Expanded dynamic search ad with ID "%d", description "%s", and '
+ 'description 2 "%s" was added'
+ % (ad['id'], ad['description'], ad['description2']))
+
+
+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',
+ version='v201809')
+
+ operations = [{
+ 'operator': 'ADD',
+ # Create biddable ad group criterion.
+ 'operand': {
+ 'xsi_type': 'BiddableAdGroupCriterion',
+ 'adGroupId': ad_group_id,
+ # Create a webpage criterion for special offers for children.
+ 'criterion': {
+ 'xsi_type': 'Webpage',
+ 'parameter': {
+ 'criterionName': 'Special offers for children.',
+ 'conditions': [
+ {
+ 'operand': 'URL',
+ 'argument': '/marscruise/children'
+ },
+ {
+ 'operand': 'PAGE_TITLE',
+ 'argument': 'Special Offer'
+ }
+ ]
+ }
+ },
+ 'userStatus': 'PAUSED',
+ # Optional: set a custom bid.
+ 'biddingStrategyConfiguration': {
+ 'bids': [{
+ 'xsi_type': 'CpcBid',
+ 'bid': {
+ 'microAmount': 10000000L
+ }
+ }]
+ }
+ }
+ }]
+
+ criterion = ad_group_criterion_service.mutate(operations)['value'][0]
+
+ print('Webpage criterion with ID "%d" was added to ad group ID "%d".' % (
+ criterion['criterion']['id'], criterion['adGroupId']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client)
diff --git a/examples/adwords/v201809/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py b/examples/adwords/v201809/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py
new file mode 100755
index 00000000..b2ae7c4e
--- /dev/null
+++ b/examples/adwords/v201809/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py
@@ -0,0 +1,113 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example adds an expanded text ad that uses upgraded URLS.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from googleads import adwords
+from googleads import errors
+
+
+ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE'
+
+
+def main(client, adgroup_id):
+ # Initialize appropriate service.
+ adgroup_ad_service = client.GetService('AdGroupAdService', version='v201809')
+
+ # Create the expanded text ad
+ expanded_text_ad = {
+ 'xsi_type': 'ExpandedTextAd',
+ 'headlinePart1': 'Luxury Cruise to Mars',
+ 'headlinePart2': 'Visit the Red Planet in style.',
+ 'description': 'Low-gravity fun for everyone!',
+ # Specify a list of final URLs. This field cannot be set if URL
+ # field is set, or finalUrls is unset. This may be specified at ad,
+ # criterion, and feed item levels.
+ 'finalUrls': [
+ 'http://www.example.com/cruise/space/',
+ 'http://www.example.com/locations/mars/'
+ ],
+ # Specify a list of final mobile URLs. This field cannot be set if URL
+ # field is set, or finalUrls is unset. This may be specified at ad,
+ # criterion, and feed item levels.
+ 'finalMobileUrls': [
+ 'http://mobile.example.com/cruise/space/',
+ 'http://mobile.example.com/locations/mars/'
+ ]
+ }
+
+ # Specify a tracking URL for 3rd party tracking provider. You may specify
+ # one at customer, campaign, ad group, ad, criterion or feed item levels.
+ expanded_text_ad['trackingUrlTemplate'] = (
+ 'http://tracker.example.com/?season={_season}&promocode={_promocode}'
+ '&u={lpurl}'
+ )
+
+ expanded_text_ad['urlCustomParameters'] = {
+ 'parameters': [
+ # Since your tracking URL has two custom parameters, provide
+ # their values too. This can be provided at campaign, ad group,
+ # ad, criterion, or feed item levels.
+ {
+ 'key': 'season',
+ 'value': 'christmas'
+ },
+ {
+ 'key': 'promocode',
+ 'value': 'NYC123'
+ }
+ ]
+ }
+
+ text_adgroup_ad = {
+ 'adGroupId': adgroup_id,
+ 'ad': expanded_text_ad,
+ # Optional: Set the status.
+ 'status': 'PAUSED'
+ }
+
+ operations = [{
+ 'operator': 'ADD',
+ 'operand': text_adgroup_ad
+ }]
+
+ response = adgroup_ad_service.mutate(operations)
+
+ if 'value' in response:
+ for adgroup_ad in response['value']:
+ print('AdGroupAd with ID "%s" was added.' % adgroup_ad['ad']['id'])
+ print('Upgraded URL properties:')
+ print('Final Urls: %s' % adgroup_ad['ad']['finalUrls'])
+ print('Final Mobile URLs: %s' % adgroup_ad['ad']['finalMobileUrls'])
+ print('Tracking URL template: %s'
+ % adgroup_ad['ad']['trackingUrlTemplate'])
+ print('Custom parameters: %s' % adgroup_ad['ad']['urlCustomParameters'])
+ else:
+ raise errors.GoogleAdsError('Failed to create AdGroupAd.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, ADGROUP_ID)
diff --git a/examples/adwords/v201809/advanced_operations/add_gmail_ad.py b/examples/adwords/v201809/advanced_operations/add_gmail_ad.py
new file mode 100755
index 00000000..683136f3
--- /dev/null
+++ b/examples/adwords/v201809/advanced_operations/add_gmail_ad.py
@@ -0,0 +1,115 @@
+#!/usr/bin/env python
+#
+# Copyright 2018 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This code example adds a Gmail ad to a given ad group.
+
+The ad group's campaign needs to have an AdvertisingChannelType of DISPLAY and
+AdvertisingChannelSubType of DISPLAY_GMAIL_AD.
+
+To get your ad groups, run get_ad_groups.py.
+"""
+
+
+# Import appropriate classes from the client library.
+from googleads import adwords
+
+
+ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
+
+
+def main(client, ad_group_id):
+ media_service = client.GetService('MediaService', 'v201809')
+ ad_group_ad_service = client.GetService('AdGroupAdService', 'v201809')
+ opener = client.proxy_config.BuildOpener()
+
+ try:
+ # This ad format doesn't allow the creation of an image using the Image.data
+ # field. An image must first be created using the MediaService, and an
+ # Image.mediaId must be populated when creating the ad.
+ uploaded_logo_image = _CreateImage(
+ media_service, opener, 'https://goo.gl/mtt54n')
+ uploaded_marketing_image = _CreateImage(
+ media_service, opener, 'http://goo.gl/3b9Wfh')
+
+ teaser = {
+ 'headline': 'Dream',
+ 'description': 'Create your own adventure',
+ 'businessName': 'Interplanetary Ships',
+ 'logoImage': uploaded_logo_image
+ }
+
+ # Creates a Gmail ad.
+ gmail_ad = {
+ 'xsi_type': 'GmailAd',
+ 'teaser': teaser,
+ 'marketingImage': uploaded_marketing_image,
+ 'marketingImageHeadline': 'Travel',
+ 'marketingImageDescription': 'Take to the skies!',
+ 'finalUrls': ['http://wwww.example.com']
+ }
+
+ # Creates ad group ad for the Gmail ad.
+ ad_group_ad = {
+ 'adGroupId': ad_group_id,
+ 'ad': gmail_ad,
+ # Optional: Set additional settings.
+ 'status': 'PAUSED'
+ }
+
+ # Creates ad group ad operations.
+ operations = [{
+ 'operator': 'ADD',
+ 'operand': ad_group_ad
+ }]
+
+ # Adds a Gmail ad.
+ ad_group_ads = ad_group_ad_service.mutate(operations)
+
+ # Display results.
+ for ad_group_ad in ad_group_ads['value']:
+ print('A Gmail ad with id "%d" and short headline "%s" was '
+ 'added.' % (ad_group_ad['ad']['id'],
+ ad_group_ad['ad']['teaser']['headline']))
+ except Exception as e:
+ raise Exception('Failed to create Gmail ad: %s' % e)
+
+
+def _CreateImage(media_service, opener, url):
+ """Creates an image and uploads it to the server.
+
+ Args:
+ media_service: a ZeepServiceProxy 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.
+ """
+ # Note: The utf-8 decode is for 2to3 Python 3 compatibility.
+ image_data = opener.open(url).read().decode('utf-8')
+ image = {
+ 'type': 'IMAGE',
+ 'data': image_data,
+ 'xsi_type': 'Image'
+ }
+
+ return media_service.upload(image)[0]
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+ main(adwords_client, ADGROUP_ID)
diff --git a/examples/adwords/v201809/advanced_operations/add_html5_ad.py b/examples/adwords/v201809/advanced_operations/add_html5_ad.py
new file mode 100755
index 00000000..2fde31f9
--- /dev/null
+++ b/examples/adwords/v201809/advanced_operations/add_html5_ad.py
@@ -0,0 +1,111 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example adds an HTML5 ad to a given AdGroup.
+
+To get ad_group_id, run get_ad_groups.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+from urllib.request import urlopen
+
+from googleads import adwords
+
+
+AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
+
+
+def main(client, ad_group_id):
+ # Initialize appropriate service.
+ ad_group_ad_service = client.GetService('AdGroupAdService', version='v201809')
+
+ # Create HTML5 media.
+ html5_zip = GetHTML5ZipFromUrl('https://goo.gl/9Y7qI2')
+ # Create a media bundle containing the zip file with all the HTML5 components.
+ media_bundle = {
+ 'xsi_type': 'MediaBundle',
+ 'data': html5_zip,
+ 'entryPoint': 'carousel/index.html',
+ 'type': 'MEDIA_BUNDLE'
+ }
+
+ ad_data = {
+ 'uniqueName': 'adData',
+ 'fields': [
+ {
+ 'name': 'Custom_layout',
+ 'fieldMedia': media_bundle,
+ 'type': 'MEDIA_BUNDLE'
+ },
+ {
+ 'name': 'layout',
+ 'fieldText': 'Custom',
+ 'type': 'ENUM'
+ }
+ ]
+ }
+
+ html5_ad = {
+ 'xsi_type': 'TemplateAd',
+ 'name': 'Ad for HTML5',
+ 'templateId': 419,
+ 'finalUrls': ['https://www.google.com'],
+ 'displayUrl': 'www.google.com?tip=ENTER_YOUR_OWN_FINAL_AND_DISPLAY_URLS',
+ 'dimensions': {
+ 'width': '300',
+ 'height': '250'
+ },
+ 'templateElements': [ad_data]
+ }
+
+ ad_group_ad = {
+ 'adGroupId': ad_group_id,
+ 'ad': html5_ad,
+ 'status': 'PAUSED'
+ }
+
+ operations = [
+ {
+ 'operator': 'ADD',
+ 'operand': ad_group_ad
+ }
+ ]
+ ads = ad_group_ad_service.mutate(operations)
+
+ # Display results.
+ for ad in ads['value']:
+ print('New HTML5 Ad with id "%s" and of display url "%s" was added.'
+ % (ad['ad']['id'], ad['ad']['displayUrl']))
+
+
+def GetHTML5ZipFromUrl(url):
+ """Retrieve zip file from the given URL."""
+ response = urlopen(url)
+ # Note: The utf-8 decode is for 2to3 Python 3 compatibility.
+ return response.read().decode('utf-8')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201809/advanced_operations/add_multi_asset_responsive_display_ad.py b/examples/adwords/v201809/advanced_operations/add_multi_asset_responsive_display_ad.py
new file mode 100755
index 00000000..71213023
--- /dev/null
+++ b/examples/adwords/v201809/advanced_operations/add_multi_asset_responsive_display_ad.py
@@ -0,0 +1,177 @@
+#!/usr/bin/env python
+#
+# Copyright 2018 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example adds a responsive display ad to an ad group.
+
+Image assets are uploaded using AssetService. To get ad groups, run
+get_ad_groups.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+from googleads import adwords
+import requests
+
+
+AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
+
+
+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')
+
+ # Download the image.
+ image_request = requests.get(url)
+
+ # Create the image asset.
+ image_asset = {
+ 'xsi_type': 'ImageAsset',
+ 'imageData': image_request.content,
+ # This field is optional, and if provided should be unique.
+ # 'assetName': 'Image asset ' + str(uuid.uuid4()),
+ }
+
+ # Create the operation.
+ operation = {
+ 'operator': 'ADD',
+ 'operand': image_asset
+ }
+
+ # Create the asset and return the ID.
+ result = asset_service.mutate([operation])
+
+ return result['value'][0]['assetId']
+
+
+def main(client, ad_group_id):
+ # Initialize appropriate service.
+ ad_group_ad_service = client.GetService('AdGroupAdService', version='v201809')
+
+ # Create the ad.
+ multi_asset_responsive_display_ad = {
+ 'xsi_type': 'MultiAssetResponsiveDisplayAd',
+ 'headlines': [{
+ 'asset': {
+ 'xsi_type': 'TextAsset',
+ 'assetText': 'Travel to Mars'
+ }
+ }, {
+ 'asset': {
+ 'xsi_type': 'TextAsset',
+ 'assetText': 'Travel to Jupiter',
+ }
+ }, {
+ 'asset': {
+ 'xsi_type': 'TextAsset',
+ 'assetText': 'Travel to Pluto'
+ }
+ }],
+ 'descriptions': [{
+ 'asset': {
+ 'xsi_type': 'TextAsset',
+ 'assetText': 'Visit the planet in a luxury spaceship.',
+ }
+ }, {
+ 'asset': {
+ 'xsi_type': 'TextAsset',
+ 'assetText': 'See the planet in style.',
+ }
+ }],
+ 'businessName': 'Galactic Luxury Cruises',
+ 'longHeadline': {
+ 'asset': {
+ 'xsi_type': 'TextAsset',
+ 'assetText': 'Visit the planet in a luxury spaceship.',
+ }
+ },
+ # This ad format does not allow the creation of an image asset by setting
+ # the asset.imageData field. An image asset must first be created using
+ # the AssetService, and asset.assetId must be populated when creating
+ # the ad.
+ 'marketingImages': [{
+ 'asset': {
+ 'xsi_type': 'ImageAsset',
+ 'assetId': UploadImageAsset(client, 'https://goo.gl/3b9Wfh')
+ }
+ }],
+ 'squareMarketingImages': [{
+ 'asset': {
+ 'xsi_type': 'ImageAsset',
+ 'assetId': UploadImageAsset(client, 'https://goo.gl/mtt54n')
+ }
+ }],
+ # Optional values
+ 'finalUrls': ['http://www.example.com'],
+ 'callToActionText': 'Shop Now',
+ # Set color settings using hexadecimal values. Set allowFlexibleColor to
+ # false if you want your ads to render by always using your colors
+ # strictly.
+ 'mainColor': '#0000ff',
+ 'accentColor': '#ffff00',
+ 'allowFlexibleColor': False,
+ 'formatSetting': 'NON_NATIVE',
+ # Set dynamic display ad settings, composed of landscape logo image,
+ # promotion text, and price prefix.
+ 'dynamicSettingsPricePrefix': 'as low as',
+ 'dynamicSettingsPromoText': 'Free shipping!',
+ 'logoImages': [{
+ 'asset': {
+ 'xsi_type': 'ImageAsset',
+ 'assetId': UploadImageAsset(client, 'https://goo.gl/mtt54n')
+ }
+ }]
+ }
+
+ # Create ad group ad.
+ ad_group_ad = {
+ 'adGroupId': ad_group_id,
+ 'ad': multi_asset_responsive_display_ad,
+ # Optional.
+ 'status': 'PAUSED'
+ }
+
+ # Add ad.
+ ads = ad_group_ad_service.mutate([
+ {'operator': 'ADD', 'operand': ad_group_ad}
+ ])
+ # Display results.
+ if 'value' in ads:
+ for ad in ads['value']:
+ print('Added new responsive display ad ad with ID "%d" '
+ 'and long headline "%s".'
+ % (ad['ad']['id'], ad['ad']['longHeadline']['asset']['assetText']))
+ else:
+ print('No ads were added.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+ main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201809/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201809/advanced_operations/add_responsive_display_ad.py
new file mode 100755
index 00000000..e4e0002a
--- /dev/null
+++ b/examples/adwords/v201809/advanced_operations/add_responsive_display_ad.py
@@ -0,0 +1,158 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example adds a responsive display ad to a given ad group.
+
+To get ad_group_id, run get_ad_groups.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from urllib.request import build_opener
+
+from googleads import adwords
+
+
+AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
+
+
+def main(client, ad_group_id):
+ # Initialize appropriate services.
+ ad_group_ad_service = client.GetService('AdGroupAdService', version='v201809')
+ media_service = client.GetService('MediaService', version='v201809')
+ opener = build_opener(*client.proxy_config.GetHandlers())
+
+ try:
+ # Create marketing image.
+ marketing_image = _CreateImage(media_service, opener,
+ 'https://goo.gl/3b9Wfh')
+
+ # Create square marketing image.
+ square_marketing_image = _CreateImage(media_service, opener,
+ 'https://goo.gl/mtt54n')
+
+ # Create a responsive display ad.
+ operations = [{
+ 'operator': 'ADD',
+ 'operand': {
+ 'xsi_type': 'AdGroupAd',
+ 'adGroupId': ad_group_id,
+ 'ad': {
+ 'xsi_type': 'ResponsiveDisplayAd',
+ 'marketingImage': {'mediaId': marketing_image['mediaId']},
+ 'shortHeadline': 'Travel',
+ 'longHeadline': 'Travel the World',
+ 'description': 'Take to the air!',
+ 'businessName': 'Interplanetary Cruises',
+ 'finalUrls': ['http://www.example.com'],
+ # Optional: Set a square marketing image to the ad.
+ 'squareMarketingImage': {
+ 'mediaId': square_marketing_image['mediaId']
+ },
+ # Optional: Set call-to-action text.
+ 'callToActionText': 'Shop Now',
+ # Optional: Set dynamic display ad settings, composed of
+ # landscape logo image, promotion text, and price prefix.
+ 'dynamicDisplayAdSettings': _CreateDynamicDisplayAdSettings(
+ media_service, opener),
+ # Whitelisted accounts only: Set color settings using
+ # hexadecimal numbers.
+ # Set allowFlexibleColor to False if you want your ads to render
+ # by always using your colors strictly.
+ # 'mainColor': '#0000ff',
+ # 'accentColor': '#ffff00',
+ # 'allowFlexibleColor': False
+ # Whitelisted accounts only: Set the format setting that the ad
+ # will be served in.
+ # 'formatSetting': 'NON_NATIVE'
+
+ },
+ # Optional fields.
+ 'status': 'PAUSED'
+ }
+ }]
+
+ # Make the mutate request.
+ ads = ad_group_ad_service.mutate(operations)
+
+ # Display results.
+ for ad in ads['value']:
+ print('ResponsiveDisplayAd with id "%d" and short headline "%s" was '
+ 'added.' % (ad['ad']['id'], ad['ad']['shortHeadline']))
+
+ except:
+ raise Exception('Failed to create responsive display ad.')
+
+
+def _CreateImage(media_service, opener, url):
+ """Creates an image and uploads it to the server.
+
+ Args:
+ media_service: a ZeepServiceProxy 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.
+ """
+ # Note: The utf-8 decode is for 2to3 Python 3 compatibility.
+ image_data = opener.open(url).read().decode('utf-8')
+ image = {
+ 'type': 'IMAGE',
+ 'data': image_data,
+ 'xsi_type': 'Image'
+ }
+
+ return media_service.upload(image)[0]
+
+
+def _CreateDynamicDisplayAdSettings(media_service, opener):
+ """Creates settings for dynamic display ad.
+
+ Args:
+ media_service: a ZeepServiceProxy instance for AdWords's MediaService.
+ opener: an OpenerDirector instance.
+
+ Returns:
+ The dynamic display ad settings.
+ """
+ image = _CreateImage(media_service, opener, 'https://goo.gl/dEvQeF')
+
+ logo = {
+ 'type': 'IMAGE',
+ 'mediaId': image['mediaId'],
+ 'xsi_type': 'Image'
+ }
+
+ dynamic_settings = {
+ 'landscapeLogoImage': logo,
+ 'pricePrefix': 'as low as',
+ 'promoText': 'Free shipping!',
+ 'xsi_type': 'DynamicSettings',
+ }
+
+ return dynamic_settings
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201809/advanced_operations/add_shopping_dynamic_remarketing_campaign.py b/examples/adwords/v201809/advanced_operations/add_shopping_dynamic_remarketing_campaign.py
new file mode 100755
index 00000000..62f724c1
--- /dev/null
+++ b/examples/adwords/v201809/advanced_operations/add_shopping_dynamic_remarketing_campaign.py
@@ -0,0 +1,301 @@
+#!/usr/bin/env python
+#
+# Copyright 2018 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Adds a Shopping dynamic remarketing campaign for the Display Network.
+
+This example steps through the following:
+* Creates a new Display Network campaign.
+* Links the campaign with Merchant Center.
+* Links the user list to the ad group.
+* Creates a responsive display ad to render the dynamic text.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+"""
+
+
+import uuid
+
+from googleads import adwords
+
+
+MERCHANT_ID = 'INSERT_MERCHANT_CENTER_ID_HERE'
+BUDGET_ID = 'INSERT_BUDGET_ID_HERE'
+USER_LIST_ID = 'INSERT_USER_LIST_ID_HERE'
+
+
+def main(client, merchant_id, budget_id, user_list_id):
+ opener = client.proxy_config.BuildOpener()
+
+ campaign = CreateCampaign(client, merchant_id, budget_id)
+ campaign_id = campaign['id']
+ print('Campaign with name "%s" and ID "%d" was added.' % (
+ campaign['name'], campaign_id))
+
+ ad_group = CreateAdGroup(client, campaign_id)
+ ad_group_id = ad_group['id']
+ print('Ad group with name "%s" and ID "%d" was added.' % (
+ ad_group['name'], ad_group_id))
+
+ ad_group_ad = CreateAd(client, opener, ad_group_id)
+ print('Responsive display ad with ID "%d" was added.' % (
+ ad_group_ad['ad']['id']))
+
+ AttachUserList(client, ad_group_id, user_list_id)
+ print('User list with ID "%d" was attached to ad group with ID "%d".' % (
+ user_list_id, ad_group_id))
+
+
+def CreateCampaign(client, merchant_id, budget_id):
+ """Creates a new Display Network campaign.
+
+ Args:
+ client: an AdWordsClient instance.
+ merchant_id: a int merchant center ID.
+ budget_id: a int budget ID.
+
+ Returns:
+ The campaign that was successfully created.
+ """
+ campaign_service = client.GetService('CampaignService', 'v201809')
+
+ campaign = {
+ 'name': 'Shopping campaign #%d' % uuid.uuid4(),
+ # Dynamic remarketing campaigns are only available on the Google Display
+ # Network.
+ 'advertisingChannelType': 'DISPLAY',
+ 'status': 'PAUSED',
+ 'budget': {
+ 'budgetId': budget_id
+ },
+ # This example uses a Manual CPC bidding strategy, but you should select
+ # the strategy that best aligns with your sales goals. More details here:
+ # https://support.google.com/adwords/answer/2472725
+ 'biddingStrategyConfiguration': {
+ 'biddingStrategyType': 'MANUAL_CPC'
+ },
+ 'settings': [{
+ 'xsi_type': 'ShoppingSetting',
+ # Campaigns with numerically higher priorities take precedence over
+ # those with lower priorities.
+ 'campaignPriority': 0,
+ 'merchantId': merchant_id,
+ # Display network campaigns do not support partition by country. The
+ # only supported value is "ZZ". This signals that products from all
+ # countries are available in this campaign. The actual products which
+ # serve are based on the products tagged in the user list entry.
+ 'salesCountry': 'ZZ',
+ # Optional: Enable local inventory ads (items for sale in physical
+ # stores.)
+ 'enableLocal': True,
+ }]
+ }
+
+ operations = [{
+ 'operator': 'ADD',
+ 'operand': campaign
+ }]
+
+ return campaign_service.mutate(operations)['value'][0]
+
+
+def CreateAdGroup(client, campaign_id):
+ """Creates a dynamic remarketing campaign.
+
+ Args:
+ client: an AdWordsClient instance.
+ campaign_id: an int campaign ID.
+
+ Returns:
+ The ad group that was successfully created.
+ """
+ ad_group_service = client.GetService('AdGroupService', 'v201809')
+
+ ad_group = {
+ 'name': 'Dynamic remarketing ad group',
+ 'campaignId': campaign_id,
+ 'status': 'ENABLED'
+ }
+
+ operations = [{
+ 'operator': 'ADD',
+ 'operand': ad_group
+ }]
+
+ return ad_group_service.mutate(operations)['value'][0]
+
+
+def CreateAd(client, opener, ad_group_id):
+ """Creates a ResponsiveDisplayAd.
+
+ Args:
+ client: an AdWordsClient instance.
+ opener: an OpenerDirector instance.
+ ad_group_id: an int ad group ID.
+
+ Returns:
+ The ad group ad that was successfully created.
+ """
+ ad_group_ad_service = client.GetService('AdGroupAdService', 'v201809')
+ media_service = client.GetService('MediaService', 'v201809')
+
+ marketing_image_id = _CreateImage(
+ media_service, opener, 'https://goo.gl/3b9Wfh')
+ logo_image_id = _CreateImage(media_service, opener, 'https://goo.gl/mtt54n')
+
+ ad = {
+ 'xsi_type': 'ResponsiveDisplayAd',
+ # This ad format doesn't allow the creation of an image using the
+ # Image.data field. An image must first be created using the MediaService,
+ # and Image.mediaId must be populated when creating the ad.
+ 'marketingImage': {
+ 'xsi_type': 'Image',
+ 'mediaId': marketing_image_id
+ },
+ 'shortHeadline': 'Travel',
+ 'longHeadline': 'Travel the World',
+ 'description': 'Take to the air!',
+ 'businessName': 'Interplanetary Cruises',
+ 'finalUrls': ['http://wwww.example.com'],
+ # Optional: Call to action text.
+ # Valid texts: https://support.google.com/adwords/answer/7005917
+ 'callToActionText': 'Apply Now',
+ # Optional: Set dynamic display ad settings, composed of landscape logo
+ # image, promotion text, and price prefix.
+ 'dynamicDisplayAdSettings': CreateDynamicDisplayAdSettings(
+ client, opener),
+ # Optional: Create a logo image and set it to the ad.
+ 'logoImage': {
+ 'xsi_type': 'Image',
+ 'mediaId': logo_image_id
+ },
+ # Optional: Create a square marketing image and set it to the ad.
+ 'squareMarketingImage': {
+ 'xsi_type': 'Image',
+ 'mediaId': logo_image_id
+ },
+ # Whitelisted accounts only: Set color settings using hexadecimal values.
+ # Set allowFlexibleColor to False if you want your ads to render by always
+ # using your colors strictly.
+ # 'mainColor': '#000fff',
+ # 'accentColor': '#fff000',
+ # 'allowFlexibleColor': False,
+ # Whitelisted accounts only: Set the format setting that the ad will be
+ # served in.
+ # 'formatSetting': 'NON_NATIVE'
+ }
+
+ ad_group_ad = {
+ 'ad': ad,
+ 'adGroupId': ad_group_id
+ }
+
+ operations = [{
+ 'operation': 'ADD',
+ 'operand': ad_group_ad
+ }]
+
+ return ad_group_ad_service.mutate(operations)['value'][0]
+
+
+def AttachUserList(client, ad_group_id, user_list_id):
+ """Links the provided ad group and user list.
+
+ Args:
+ client: an AdWordsClient instance.
+ ad_group_id: an int ad group ID.
+ user_list_id: an int user list ID.
+
+ Returns:
+ The ad group criterion that was successfully created.
+ """
+ ad_group_criterion_service = client.GetService(
+ 'AdGroupCriterionService', 'v201809')
+
+ user_list = {
+ 'xsi_type': 'CriterionUserList',
+ 'userListId': user_list_id
+ }
+
+ ad_group_criterion = {
+ 'xsi_type': 'BiddableAdGroupCriterion',
+ 'criterion': user_list,
+ 'adGroupId': ad_group_id
+ }
+
+ operations = [{
+ 'operator': 'ADD',
+ 'operand': ad_group_criterion
+ }]
+
+ return ad_group_criterion_service.mutate(operations)['value'][0]
+
+
+def CreateDynamicDisplayAdSettings(client, opener):
+ """Creates dynamic display ad settings.
+
+ Args:
+ client: an AdWordsClient instance.
+ opener: an OpenerDirector instance.
+
+ Returns:
+ A dict containing the dynamic display ad settings.
+ """
+ media_service = client.GetService('MediaService', 'v201809')
+
+ logo = {
+ 'xsi_type': 'Image',
+ 'mediaId': _CreateImage(media_service, opener, 'https://goo.gl/dEvQeF')
+ }
+
+ dynamic_settings = {
+ 'landscapeLogoImage': logo,
+ 'pricePrefix': 'as low as',
+ 'promoText': 'Free shipping!'
+ }
+
+ return dynamic_settings
+
+
+def _CreateImage(media_service, opener, url):
+ """Creates an image and uploads it to the server.
+
+ Args:
+ media_service: a ZeepServiceProxy 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.
+ """
+ # Note: The utf-8 decode is for 2to3 Python 3 compatibility.
+ image_data = opener.open(url).read().decode('utf-8')
+ image = {
+ 'type': 'IMAGE',
+ 'data': image_data,
+ 'xsi_type': 'Image'
+ }
+
+ return media_service.upload(image)[0]
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, MERCHANT_ID, BUDGET_ID, USER_LIST_ID)
diff --git a/examples/adwords/v201809/advanced_operations/add_universal_app_campaign.py b/examples/adwords/v201809/advanced_operations/add_universal_app_campaign.py
new file mode 100755
index 00000000..6ae29105
--- /dev/null
+++ b/examples/adwords/v201809/advanced_operations/add_universal_app_campaign.py
@@ -0,0 +1,218 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example adds a Universal App campaign.
+
+To get campaigns, run get_campaigns.py. To upload image assets for this
+campaign, run upload_image.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import datetime
+import uuid
+from googleads import adwords
+
+
+def main(client):
+ # Initialize appropriate services.
+ campaign_service = client.GetService('CampaignService', version='v201809')
+
+ budget_id = CreateBudget(client)
+
+ # Create the Universal App campaign.
+ universal_app_campaign = {
+ 'name': 'Interplanetary Cruise App #%s' % uuid.uuid4(),
+ # Recommendation: Set the campaign to PAUSED when creating it to stop the
+ # ads from immediately serving. Set to ENABLED once you've added targeting
+ # and the ads are ready to serve.
+ 'status': 'PAUSED',
+ 'advertisingChannelType': 'MULTI_CHANNEL',
+ 'advertisingChannelSubType': 'UNIVERSAL_APP_CAMPAIGN',
+ # Set the campaign's bidding strategy. Universal app campaigns only
+ # support TARGET_CPA bidding strategy.
+ 'biddingStrategyConfiguration': {
+ # Set the target CPA to $1 / app install.
+ 'biddingScheme': {
+ 'xsi_type': 'TargetCpaBiddingScheme',
+ 'targetCpa': {
+ 'microAmount': '1000000'
+ }
+ },
+ 'biddingStrategyType': 'TARGET_CPA'
+ },
+ # Note that only the budgetId is required
+ 'budget': {
+ 'budgetId': budget_id
+ },
+ # Optional fields
+ 'startDate': (datetime.datetime.now() +
+ datetime.timedelta(1)).strftime('%Y%m%d'),
+ 'endDate': (datetime.datetime.now() +
+ datetime.timedelta(365)).strftime('%Y%m%d'),
+ }
+
+ universal_app_campaign['settings'] = [
+ # Set the campaign's assets and ad text ideas. These values will
+ # be used to generate ads.
+ {
+ 'xsi_type': 'UniversalAppCampaignSetting',
+ 'appId': 'com.labpixies.colordrips',
+ 'appVendor': 'VENDOR_GOOGLE_MARKET',
+ 'description1': 'A cool puzzle game',
+ 'description2': 'Remove connected blocks',
+ 'description3': '3 difficulty levels',
+ 'description4': '4 colorful fun skins',
+ # Optional: You can set up to 20 image assets for your campaign.
+ # See upload_image.py for an example on how to upload images.
+ #
+ # 'imageMediaIds': [INSERT_IMAGE_MEDIA_ID(s)_HERE]
+ }
+ ]
+
+ # Optimize this campaign for getting new users for your app.
+ universal_app_campaign_setting = universal_app_campaign['settings'][0]
+ universal_app_campaign_setting['universalAppBiddingStrategyGoalType'] = (
+ 'OPTIMIZE_FOR_INSTALL_CONVERSION_VOLUME')
+
+ # Optional: If you select the OPTIMIZE_FOR_IN_APP_CONVERSION_VOLUME goal type,
+ # then also specify your in-app conversion types so AdWords can focus your
+ # campaign on people who are most likely to complete the corresponding in-app
+ # actions.
+ #
+ # Conversions type IDs can be retrieved using ConversionTrackerService.get.
+ # universal_app_campaign['selectiveOptimization'] = {
+ # 'conversionTypeIds': [INSERT_CONVERSION_TYPE_ID(s)_HERE]
+ # }
+
+ # Optional: Set the campaign settings for Advanced location options.
+ universal_app_campaign['settings'].append({
+ 'xsi_type': 'GeoTargetTypeSetting',
+ 'positiveGeoTargetType': 'DONT_CARE',
+ 'negativeGeoTargetType': 'DONT_CARE'
+ })
+
+ # Construct operations and add campaigns.
+ operations = [{
+ 'operator': 'ADD',
+ 'operand': universal_app_campaign
+ }]
+
+ campaigns = campaign_service.mutate(operations)['value']
+
+ # Display results.
+ if campaigns:
+ for campaign in campaigns:
+ print('Universal App Campaign with name "%s" and id "%s" was added.'
+ % (campaign['name'], campaign['id']))
+ # Optional: Set the campaign's location and language targeting. No other
+ # targeting criteria can be used for Universal App campaigns.
+ SetCampaignTargetingCriteria(client, campaign)
+ else:
+ print('No Universal App campaigns were added.')
+
+
+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': 'Interplanetary Cruise App Budget #%s' % uuid.uuid4(),
+ 'amount': {
+ 'microAmount': '50000000'
+ },
+ 'deliveryMethod': 'STANDARD',
+ 'isExplicitlyShared': False
+ }
+
+ budget_operations = [{
+ 'operator': 'ADD',
+ 'operand': budget
+ }]
+
+ # Create the budget and return its ID.
+ budget_id = budget_service.mutate(budget_operations)['value'][0]['budgetId']
+
+ return budget_id
+
+
+def SetCampaignTargetingCriteria(client, campaign):
+ """Sets targeting criteria for the given campaign.
+
+ Args:
+ client: An AdWordsClient instance.
+ campaign: A zeep.objects.Campaign representing the campaign we wish to attach
+ targeting criteria.
+ """
+ campaign_criterion_service = client.GetService('CampaignCriterionService')
+
+ # Create locations. The IDs can be found in the documentation or retrieved
+ # with the LocationCriterionService.
+ criteria = [
+ {
+ 'xsi_type': 'Location',
+ 'id': 21137 # California
+ },
+ {
+ 'xsi_type': 'Location',
+ 'id': 2484 # Mexico
+ },
+ {
+ 'xsi_type': 'Language',
+ 'id': 1000 # English
+ },
+ {
+ 'xsi_type': 'Language',
+ 'id': 1003 # Spanish
+ }
+ ]
+
+ operations = [{
+ 'operator': 'ADD',
+ 'operand': {
+ 'campaignId': campaign['id'],
+ 'criterion': criterion
+ }
+ } for criterion in criteria]
+
+ response = campaign_criterion_service.mutate(operations)
+
+ if response and 'value' in response:
+ # Display the added campaign targets.
+ for criterion in response['value']:
+ print('Campaign criteria of type "%s" and id "%s" was added.'
+ % (criterion['criterion']['type'],
+ criterion['criterion']['id']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client)
diff --git a/examples/adwords/v201502/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201809/advanced_operations/create_and_attach_shared_keyword_set.py
similarity index 85%
rename from examples/adwords/v201502/advanced_operations/create_and_attach_shared_keyword_set.py
rename to examples/adwords/v201809/advanced_operations/create_and_attach_shared_keyword_set.py
index 7dd535da..4d3a3800 100755
--- a/examples/adwords/v201502/advanced_operations/create_and_attach_shared_keyword_set.py
+++ b/examples/adwords/v201809/advanced_operations/create_and_attach_shared_keyword_set.py
@@ -1,6 +1,6 @@
-#!/usr/bin/python
+#!/usr/bin/env python
#
-# Copyright 2015 Google Inc. All Rights Reserved.
+# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -21,14 +21,10 @@
directory. For more information, see the "Caching authentication information"
section of our README.
-Tags: CampaignSharedSetService.mutate, SharedCriterionService.mutate,
- SharedSetService.mutate
"""
-__author__ = 'Mark Saniscalchi'
import uuid
-
from googleads import adwords
from googleads import errors
@@ -38,11 +34,11 @@
def main(client, campaign_id):
# Initialize appropriate services.
- shared_set_service = client.GetService('SharedSetService', version='v201502')
+ shared_set_service = client.GetService('SharedSetService', version='v201809')
shared_criterion_service = client.GetService('SharedCriterionService',
- version='v201502')
+ version='v201809')
campaign_shared_set_service = client.GetService('CampaignSharedSetService',
- version='v201502')
+ version='v201809')
# Keywords to create a shared set of.
keywords = ['mars cruise', 'mars hotels']
@@ -64,9 +60,9 @@ def main(client, campaign_id):
shared_set = response['value'][0]
shared_set_id = shared_set['sharedSetId']
- print 'Shared set with ID %d and name "%s" was successfully added.' % (
+ print('Shared set with ID %d and name "%s" was successfully added.' % (
shared_set_id, shared_set['name']
- )
+ ))
else:
raise errors.GoogleAdsError('No shared set was added.')
@@ -94,11 +90,11 @@ def main(client, campaign_id):
if 'value' in response:
for shared_criteria in response['value']:
- print 'Added shared criterion ID %d "%s" to shared set with ID %d.' % (
+ print('Added shared criterion ID %d "%s" to shared set with ID %d.' % (
shared_criteria['criterion']['id'],
shared_criteria['criterion']['text'],
shared_criteria['sharedSetId']
- )
+ ))
else:
raise errors.GoogleAdsError('No shared keyword was added.')
@@ -118,9 +114,9 @@ def main(client, campaign_id):
response = campaign_shared_set_service.mutate(operations)
if 'value' in response:
- print 'Shared set ID %d was attached to campaign ID %d' % (
+ print('Shared set ID %d was attached to campaign ID %d' % (
response['value'][0]['sharedSetId'], response['value'][0]['campaignId']
- )
+ ))
else:
raise errors.GoogleAdsError('No campaign shared set was added.')
diff --git a/examples/adwords/v201809/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201809/advanced_operations/find_and_remove_criteria_from_shared_set.py
new file mode 100755
index 00000000..916a04ee
--- /dev/null
+++ b/examples/adwords/v201809/advanced_operations/find_and_remove_criteria_from_shared_set.py
@@ -0,0 +1,155 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Demonstrates how to find and remove shared sets/shared set criterions.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from googleads import adwords
+
+
+CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
+PAGE_SIZE = 500
+
+
+def main(client, campaign_id):
+ # Initialize appropriate services.
+ shared_criterion_service = client.GetService('SharedCriterionService',
+ version='v201809')
+ campaign_shared_set_service = client.GetService('CampaignSharedSetService',
+ version='v201809')
+
+ shared_set_ids = []
+ criterion_ids = []
+
+ # First, retrieve all shared sets associated with the campaign.
+
+ # Create selector for shared sets to:
+ # - filter by campaign ID,
+ # - filter by shared set type.
+ selector = {
+ 'fields': ['SharedSetId', 'CampaignId', 'SharedSetName', 'SharedSetType',
+ 'Status'],
+ 'predicates': [
+ {
+ 'field': 'CampaignId',
+ 'operator': 'EQUALS',
+ 'values': [campaign_id]
+ },
+ {
+ 'field': 'SharedSetType',
+ 'operator': 'IN',
+ 'values': ['NEGATIVE_KEYWORDS', 'NEGATIVE_PLACEMENTS']
+ }
+ ],
+ 'paging': {
+ 'startIndex': 0,
+ 'numberResults': PAGE_SIZE
+ }
+ }
+
+ # Set initial values:
+ offset = 0
+ page = {'totalNumEntries': 1}
+
+ while page['totalNumEntries'] > offset:
+ page = campaign_shared_set_service.get(selector)
+ if 'entries' in page:
+ for shared_set in page['entries']:
+ print('Campaign shared set ID %d and name "%s"' % (
+ shared_set['sharedSetId'], shared_set['sharedSetName']
+ ))
+ shared_set_ids.append(shared_set['sharedSetId'])
+ # Increment values to request the next page.
+ offset += PAGE_SIZE
+ selector['paging']['startIndex'] = offset
+
+ # Next, retrieve criterion IDs for all found shared sets.
+ selector = {
+ 'fields': ['SharedSetId', 'Id', 'KeywordText', 'KeywordMatchType',
+ 'PlacementUrl'],
+ 'predicates': [
+ {
+ 'field': 'SharedSetId',
+ 'operator': 'IN',
+ 'values': shared_set_ids
+ }
+ ],
+ 'paging': {
+ 'startIndex': 0,
+ 'numberResults': PAGE_SIZE
+ }
+ }
+
+ # Set initial values:
+ offset = 0
+ page = {'totalNumEntries': 1}
+
+ while page['totalNumEntries'] > offset:
+ page = shared_criterion_service.get(selector)
+ if 'entries' in page:
+ for shared_criterion in page['entries']:
+ if shared_criterion['criterion']['type'] == 'KEYWORD':
+ print('Shared negative keyword with ID %d and text "%s" was'
+ 'found.' % (shared_criterion['criterion']['id'],
+ shared_criterion['criterion']['text']))
+ elif shared_criterion['criterion']['type'] == 'PLACEMENT':
+ print('Shared negative placement with ID %d and url "%s" was'
+ 'found.' % (shared_criterion['criterion']['id'],
+ shared_criterion['criterion']['url']))
+ else:
+ print('Shared criterion with ID %d was found.' % (
+ shared_criterion['criterion']['id'],
+ ))
+ criterion_ids.append({
+ 'sharedSetId': shared_criterion['sharedSetId'],
+ 'criterionId': shared_criterion['criterion']['id']
+ })
+ # Increment values to request the next page.
+ offset += PAGE_SIZE
+ selector['paging']['startIndex'] = offset
+
+ # Finally, remove the criteria.
+ if criterion_ids:
+ operations = [
+ {
+ 'operator': 'REMOVE',
+ 'operand': {
+ 'criterion': {'id': criterion['criterionId']},
+ 'sharedSetId': criterion['sharedSetId']
+ }
+ } for criterion in criterion_ids
+ ]
+
+ response = shared_criterion_service.mutate(operations)
+ if 'value' in response:
+ for criterion in response['value']:
+ print('Criterion ID %d was successfully removed from shared set ID'
+ '%d.' % (criterion['criterion']['id'], criterion['sharedSetId']))
+ else:
+ print('No shared criteria were removed.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201809/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201809/advanced_operations/get_ad_group_bid_modifier.py
new file mode 100755
index 00000000..c5880795
--- /dev/null
+++ b/examples/adwords/v201809/advanced_operations/get_ad_group_bid_modifier.py
@@ -0,0 +1,73 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Retrieves the ad group level bid modifiers for a campaign.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from googleads import adwords
+
+
+PAGE_SIZE = 500
+
+
+def main(client):
+ # Initialize appropriate service.
+ ad_group_bid_modifier_service = client.GetService(
+ 'AdGroupBidModifierService', version='v201809')
+
+ # Get all ad group bid modifiers for the campaign.
+ selector = {
+ 'fields': ['CampaignId', 'AdGroupId', 'BidModifier', 'Id'],
+ 'paging': {
+ 'startIndex': '0',
+ 'numberResults': str(PAGE_SIZE)
+ }
+ }
+
+ # Set initial values.
+ offset, page = 0, {}
+ more_results = True
+
+ while more_results:
+ page = ad_group_bid_modifier_service.get(selector)
+ if page['entries']:
+ for modifier in page['entries']:
+ value = (modifier['bidModifier'] if 'bidModifier' in modifier
+ else 'unset')
+ print('Campaign ID %s, AdGroup ID %s, Criterion ID %s has ad group '
+ 'level modifier: %s' %
+ (modifier['campaignId'], modifier['adGroupId'],
+ modifier['criterion']['id'], value))
+
+ # Increment values to request the next page.
+ offset += PAGE_SIZE
+ selector['paging']['startIndex'] = str(offset)
+ else:
+ print('No ad group bid modifiers returned.')
+ more_results = int(page['totalNumEntries']) > offset
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client)
diff --git a/examples/adwords/v201809/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201809/advanced_operations/use_shared_bidding_strategy.py
new file mode 100755
index 00000000..3ede5fae
--- /dev/null
+++ b/examples/adwords/v201809/advanced_operations/use_shared_bidding_strategy.py
@@ -0,0 +1,171 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Adds a Shared Bidding Strategy and uses it to construct a campaign.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import uuid
+from googleads import adwords
+
+
+# Enter a shared budget ID to re-use an existing budget or leave as None to
+# create a new one.
+BUDGET_ID = None
+
+
+def main(client, budget_id):
+ bidding_strategy = CreateBiddingStrategy(client)
+
+ if budget_id is None:
+ budget = CreateSharedBudget(client)
+ budget_id = budget['budgetId']
+
+ CreateCampaignWithBiddingStrategy(client, bidding_strategy['id'], budget_id)
+
+
+def CreateBiddingStrategy(client):
+ """Creates a bidding strategy object.
+
+ Args:
+ client: AdWordsClient the client to run the example with.
+
+ Returns:
+ dict An object representing a bidding strategy.
+ """
+ # Initialize appropriate service.
+ bidding_strategy_service = client.GetService(
+ 'BiddingStrategyService', version='v201809')
+
+ # Create a shared bidding strategy.
+ shared_bidding_strategy = {
+ 'name': 'Maximize Clicks %s' % uuid.uuid4(),
+ 'biddingScheme': {
+ 'xsi_type': 'TargetSpendBiddingScheme',
+ # Optionally set additional bidding scheme parameters.
+ 'bidCeiling': {
+ 'microAmount': '2000000'
+ }
+ }
+ }
+
+ # Create operation.
+ operation = {
+ 'operator': 'ADD',
+ 'operand': shared_bidding_strategy
+ }
+
+ response = bidding_strategy_service.mutate([operation])
+ new_bidding_strategy = response['value'][0]
+
+ print('Shared bidding strategy with name "%s" and ID "%s" of type "%s"'
+ 'was created.' %
+ (new_bidding_strategy['name'], new_bidding_strategy['id'],
+ new_bidding_strategy['biddingScheme']['BiddingScheme.Type']))
+
+ return new_bidding_strategy
+
+
+def CreateSharedBudget(client):
+ """Creates an explicit budget to be used only to create the Campaign.
+
+ Args:
+ client: AdWordsClient the client to run the example with.
+
+ Returns:
+ dict An object representing a shared budget.
+ """
+ # Initialize appropriate service.
+ budget_service = client.GetService('BudgetService', version='v201809')
+
+ # Create a shared budget
+ budget = {
+ 'name': 'Shared Interplanetary Budget #%s' % uuid.uuid4(),
+ 'amount': {
+ 'microAmount': '2000000'
+ },
+ 'deliveryMethod': 'STANDARD',
+ 'isExplicitlyShared': 'true'
+ }
+
+ # Create operation.
+ operation = {
+ 'operator': 'ADD',
+ 'operand': budget
+ }
+
+ response = budget_service.mutate([operation])
+ return response['value'][0]
+
+
+def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id):
+ """Create a Campaign with a Shared Bidding Strategy.
+
+ Args:
+ client: AdWordsClient the client to run the example with.
+ bidding_strategy_id: string the bidding strategy ID to use.
+ budget_id: string the shared budget ID to use.
+
+ Returns:
+ dict An object representing a campaign.
+ """
+ # Initialize appropriate service.
+ campaign_service = client.GetService('CampaignService', version='v201809')
+
+ # Create campaign.
+ campaign = {
+ 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(),
+ 'budget': {
+ 'budgetId': budget_id
+ },
+ 'biddingStrategyConfiguration': {
+ 'biddingStrategyId': bidding_strategy_id
+ },
+ 'advertisingChannelType': 'SEARCH',
+ 'networkSetting': {
+ 'targetGoogleSearch': 'true',
+ 'targetSearchNetwork': 'true',
+ 'targetContentNetwork': 'true'
+ }
+ }
+
+ # Create operation.
+ operation = {
+ 'operator': 'ADD',
+ 'operand': campaign
+ }
+
+ response = campaign_service.mutate([operation])
+ new_campaign = response['value'][0]
+
+ print('Campaign with name "%s", ID "%s" and bidding scheme ID "%s" '
+ 'was created.' %
+ (new_campaign['name'], new_campaign['id'],
+ new_campaign['biddingStrategyConfiguration']['biddingStrategyId']))
+
+ return new_campaign
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+ main(adwords_client, BUDGET_ID)
diff --git a/examples/adwords/v201809/basic_operations/__init__.py b/examples/adwords/v201809/basic_operations/__init__.py
new file mode 100644
index 00000000..1a2bc84a
--- /dev/null
+++ b/examples/adwords/v201809/basic_operations/__init__.py
@@ -0,0 +1,15 @@
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Basic operations examples."""
diff --git a/examples/adwords/v201809/basic_operations/add_ad_groups.py b/examples/adwords/v201809/basic_operations/add_ad_groups.py
new file mode 100755
index 00000000..52ef7c65
--- /dev/null
+++ b/examples/adwords/v201809/basic_operations/add_ad_groups.py
@@ -0,0 +1,115 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example adds ad groups to a given campaign.
+
+To get ad groups, run get_ad_groups.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import uuid
+from googleads import adwords
+
+
+CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
+
+
+def main(client, campaign_id):
+ # Initialize appropriate service.
+ ad_group_service = client.GetService('AdGroupService', version='v201809')
+
+ # Construct operations and add ad groups.
+ operations = [{
+ 'operator': 'ADD',
+ 'operand': {
+ 'campaignId': campaign_id,
+ 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(),
+ 'status': 'ENABLED',
+ 'biddingStrategyConfiguration': {
+ 'bids': [
+ {
+ 'xsi_type': 'CpcBid',
+ 'bid': {
+ 'microAmount': '1000000'
+ },
+ }
+ ]
+ },
+ 'settings': [
+ {
+ # Targeting restriction settings. Depending on the
+ # criterionTypeGroup value, most TargetingSettingDetail only
+ # affect Display campaigns. However, the
+ # USER_INTEREST_AND_LIST value works for RLSA campaigns -
+ # Search campaigns targeting using a remarketing list.
+ 'xsi_type': 'TargetingSetting',
+ 'details': [
+ # Restricting to serve ads that match your ad group
+ # placements. This is equivalent to choosing
+ # "Target and bid" in the UI.
+ {
+ 'xsi_type': 'TargetingSettingDetail',
+ 'criterionTypeGroup': 'PLACEMENT',
+ 'targetAll': 'false',
+ },
+ # Using your ad group verticals only for bidding. This is
+ # equivalent to choosing "Bid only" in the UI.
+ {
+ 'xsi_type': 'TargetingSettingDetail',
+ 'criterionTypeGroup': 'VERTICAL',
+ 'targetAll': 'true',
+ },
+ ]
+ }
+ ]
+ }
+ }, {
+ 'operator': 'ADD',
+ 'operand': {
+ 'campaignId': campaign_id,
+ 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(),
+ 'status': 'ENABLED',
+ 'biddingStrategyConfiguration': {
+ 'bids': [
+ {
+ 'xsi_type': 'CpcBid',
+ 'bid': {
+ 'microAmount': '1000000'
+ }
+ }
+ ]
+ }
+ }
+ }]
+ ad_groups = ad_group_service.mutate(operations)
+
+ # Display results.
+ for ad_group in ad_groups['value']:
+ print('Ad group with name "%s" and id "%s" was added.'
+ % (ad_group['name'], ad_group['id']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201809/basic_operations/add_campaigns.py b/examples/adwords/v201809/basic_operations/add_campaigns.py
new file mode 100755
index 00000000..f0e91d67
--- /dev/null
+++ b/examples/adwords/v201809/basic_operations/add_campaigns.py
@@ -0,0 +1,127 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example adds campaigns.
+
+To get campaigns, run get_campaigns.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import datetime
+import uuid
+from googleads import adwords
+
+
+def main(client):
+ # Initialize appropriate services.
+ campaign_service = client.GetService('CampaignService', version='v201809')
+ budget_service = client.GetService('BudgetService', version='v201809')
+
+ # Create a budget, which can be shared by multiple campaigns.
+ budget = {
+ 'name': 'Interplanetary budget #%s' % uuid.uuid4(),
+ 'amount': {
+ 'microAmount': '50000000'
+ },
+ 'deliveryMethod': 'STANDARD'
+ }
+
+ budget_operations = [{
+ 'operator': 'ADD',
+ 'operand': budget
+ }]
+
+ # Add the budget.
+ budget_id = budget_service.mutate(budget_operations)['value'][0][
+ 'budgetId']
+
+ # Construct operations and add campaigns.
+ operations = [{
+ 'operator': 'ADD',
+ 'operand': {
+ 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(),
+ # Recommendation: Set the campaign to PAUSED when creating it to
+ # stop the ads from immediately serving. Set to ENABLED once you've
+ # added targeting and the ads are ready to serve.
+ 'status': 'PAUSED',
+ 'advertisingChannelType': 'SEARCH',
+ 'biddingStrategyConfiguration': {
+ 'biddingStrategyType': 'MANUAL_CPC',
+ },
+ 'endDate': (datetime.datetime.now() +
+ datetime.timedelta(365)).strftime('%Y%m%d'),
+ # Note that only the budgetId is required
+ 'budget': {
+ 'budgetId': budget_id
+ },
+ 'networkSetting': {
+ 'targetGoogleSearch': 'true',
+ 'targetSearchNetwork': 'true',
+ 'targetContentNetwork': 'false',
+ 'targetPartnerSearchNetwork': 'false'
+ },
+ # Optional fields
+ 'startDate': (datetime.datetime.now() +
+ datetime.timedelta(1)).strftime('%Y%m%d'),
+ 'frequencyCap': {
+ 'impressions': '5',
+ 'timeUnit': 'DAY',
+ 'level': 'ADGROUP'
+ },
+ 'settings': [
+ {
+ 'xsi_type': 'GeoTargetTypeSetting',
+ 'positiveGeoTargetType': 'DONT_CARE',
+ 'negativeGeoTargetType': 'DONT_CARE'
+ }
+ ]
+ }
+ }, {
+ 'operator': 'ADD',
+ 'operand': {
+ 'name': 'Interplanetary Cruise banner #%s' % uuid.uuid4(),
+ 'status': 'PAUSED',
+ 'biddingStrategyConfiguration': {
+ 'biddingStrategyType': 'MANUAL_CPC'
+ },
+ 'endDate': (datetime.datetime.now() +
+ datetime.timedelta(365)).strftime('%Y%m%d'),
+ # Note that only the budgetId is required
+ 'budget': {
+ 'budgetId': budget_id
+ },
+ 'advertisingChannelType': 'DISPLAY'
+ }
+ }]
+ campaigns = campaign_service.mutate(operations)
+
+ # Display results.
+ for campaign in campaigns['value']:
+ print('Campaign with name "%s" and id "%s" was added.'
+ % (campaign['name'], campaign['id']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client)
diff --git a/examples/adwords/v201809/basic_operations/add_expanded_text_ads.py b/examples/adwords/v201809/basic_operations/add_expanded_text_ads.py
new file mode 100755
index 00000000..60c99731
--- /dev/null
+++ b/examples/adwords/v201809/basic_operations/add_expanded_text_ads.py
@@ -0,0 +1,77 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example adds expanded text ads to a given ad group.
+
+To get ad_group_id, run get_ad_groups.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+import uuid
+
+from googleads import adwords
+
+
+AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
+NUMBER_OF_ADS = 5
+
+
+def main(client, ad_group_id):
+ # Initialize appropriate service.
+ ad_group_ad_service = client.GetService('AdGroupAdService', version='v201809')
+
+ operations = [
+ {
+ 'operator': 'ADD',
+ 'operand': {
+ 'xsi_type': 'AdGroupAd',
+ 'adGroupId': ad_group_id,
+ 'ad': {
+ 'xsi_type': 'ExpandedTextAd',
+ 'headlinePart1': ('Cruise #%s to Mars'
+ % str(uuid.uuid4())[:8]),
+ 'headlinePart2': 'Best Space Cruise Line',
+ 'headlinePart3': 'For Your Loved Ones',
+ 'description': 'Buy your tickets now!',
+ 'description2': 'Discount ends soon',
+ 'finalUrls': ['http://www.example.com/%s' % i],
+ },
+ # Optional fields.
+ 'status': 'PAUSED'
+ }
+ } for i in range(NUMBER_OF_ADS)
+ ]
+ ads = ad_group_ad_service.mutate(operations)
+
+ # Display results.
+ for ad in ads['value']:
+ print('Ad of type "%s" with id "%d" was added.'
+ '\n\theadlinePart1: %s\n\theadlinePart2: %s\n\theadlinePart3: %s'
+ % (ad['ad']['Ad.Type'], ad['ad']['id'],
+ ad['ad']['headlinePart1'], ad['ad']['headlinePart2'],
+ ad['ad']['headlinePart3']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201809/basic_operations/add_keywords.py b/examples/adwords/v201809/basic_operations/add_keywords.py
new file mode 100755
index 00000000..dc6fbd3f
--- /dev/null
+++ b/examples/adwords/v201809/basic_operations/add_keywords.py
@@ -0,0 +1,92 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example adds ad group criteria to an ad group.
+
+To get ad groups, run get_ad_groups.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from googleads import adwords
+
+
+AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
+
+
+def main(client, ad_group_id):
+ # Initialize appropriate service.
+ ad_group_criterion_service = client.GetService(
+ 'AdGroupCriterionService', version='v201809')
+
+ # Construct keyword ad group criterion object.
+ keyword1 = {
+ 'xsi_type': 'BiddableAdGroupCriterion',
+ 'adGroupId': ad_group_id,
+ 'criterion': {
+ 'xsi_type': 'Keyword',
+ 'matchType': 'BROAD',
+ 'text': 'mars'
+ },
+ # These fields are optional.
+ 'userStatus': 'PAUSED',
+ 'finalUrls': {
+ 'urls': ['http://example.com/mars']
+ }
+ }
+
+ keyword2 = {
+ 'xsi_type': 'NegativeAdGroupCriterion',
+ 'adGroupId': ad_group_id,
+ 'criterion': {
+ 'xsi_type': 'Keyword',
+ 'matchType': 'EXACT',
+ 'text': 'pluto'
+ }
+ }
+
+ # Construct operations and add ad group criteria.
+ operations = [
+ {
+ 'operator': 'ADD',
+ 'operand': keyword1
+ },
+ {
+ 'operator': 'ADD',
+ 'operand': keyword2
+ }
+ ]
+ ad_group_criteria = ad_group_criterion_service.mutate(
+ operations)['value']
+
+ # Display results.
+ for criterion in ad_group_criteria:
+ print('Keyword ad group criterion with ad group id "%s", criterion id '
+ '"%s", text "%s", and match type "%s" was added.'
+ % (criterion['adGroupId'], criterion['criterion']['id'],
+ criterion['criterion']['text'],
+ criterion['criterion']['matchType']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201809/basic_operations/add_responsive_search_ad.py b/examples/adwords/v201809/basic_operations/add_responsive_search_ad.py
new file mode 100755
index 00000000..038ce20a
--- /dev/null
+++ b/examples/adwords/v201809/basic_operations/add_responsive_search_ad.py
@@ -0,0 +1,112 @@
+#!/usr/bin/env python
+#
+# Copyright 2018 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example adds a responsive search ad to a given ad group.
+
+To get ad groups, run get_ad_groups.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+import uuid
+
+from googleads import adwords
+
+
+AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
+NUMBER_OF_ADS = 5
+
+
+def main(client, ad_group_id):
+ # Initialize appropriate service.
+ ad_group_ad_service = client.GetService('AdGroupAdService', version='v201809')
+
+ responsive_search_ad = {
+ 'xsi_type': 'AdGroupAd',
+ 'adGroupId': ad_group_id,
+ 'ad': {
+ 'xsi_type': 'ResponsiveSearchAd',
+ 'finalUrls': ['http://www.example.com/cruise'],
+ 'path1': 'all-inclusive',
+ 'path2': 'deals',
+ 'headlines': [{
+ 'asset': {
+ 'xsi_type': 'TextAsset',
+ 'assetText': 'Cruise to Mars # ' + str(uuid.uuid4())[:8]
+ },
+ 'pinnedField': 'HEADLINE_1'
+ }, {
+ 'asset': {
+ 'xsi_type': 'TextAsset',
+ 'assetText': 'Best Space Cruise Line',
+ }
+ }, {
+ 'asset': {
+ 'xsi_type': 'TextAsset',
+ 'assetText': 'Experience the Stars'
+ }
+ }],
+ 'descriptions': [{
+ 'asset': {
+ 'xsi_type': 'TextAsset',
+ 'assetText': 'Buy your tickets now.'
+ }
+ }, {
+ 'asset': {
+ 'xsi_type': 'TextAsset',
+ 'assetText': 'Visit the Red Planet',
+ }
+ }],
+ },
+ # Optional fields.
+ 'status': 'PAUSED'
+ }
+
+ # Create the operations.
+ operations = [{
+ 'operator': 'ADD',
+ 'operand': responsive_search_ad
+ }]
+
+ # Create the ad on the server.
+ ads = ad_group_ad_service.mutate(operations)
+
+ # Display results.
+ for ad in ads['value']:
+ ad = ad['ad']
+ print('Ad of type "%s" with id "%d" was added.\n'
+ 'Headlines:\n%s\n'
+ 'Descriptions:\n%s'
+ % (ad['Ad.Type'], ad['id'],
+ '\n'.join(['\t%s (pinned to %s)' %
+ (headline['asset']['assetText'],
+ headline['pinnedField'])
+ for headline in ad['headlines']]),
+ '\n'.join(['\t%s (pinned to %s)' %
+ (headline['asset']['assetText'],
+ headline['pinnedField'])
+ for headline in ad['descriptions']])))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201809/basic_operations/get_ad_groups.py b/examples/adwords/v201809/basic_operations/get_ad_groups.py
new file mode 100755
index 00000000..3c23b6aa
--- /dev/null
+++ b/examples/adwords/v201809/basic_operations/get_ad_groups.py
@@ -0,0 +1,76 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all ad groups for a given campaign.
+
+To add an ad group, run add_ad_group.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from googleads import adwords
+
+
+PAGE_SIZE = 500
+CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
+
+
+def main(client, campaign_id):
+ # Initialize appropriate service.
+ ad_group_service = client.GetService('AdGroupService', version='v201809')
+
+ # Construct selector and get all ad groups.
+ offset = 0
+ selector = {
+ 'fields': ['Id', 'Name', 'Status'],
+ 'predicates': [
+ {
+ 'field': 'CampaignId',
+ 'operator': 'EQUALS',
+ 'values': [campaign_id]
+ }
+ ],
+ 'paging': {
+ 'startIndex': str(offset),
+ 'numberResults': str(PAGE_SIZE)
+ }
+ }
+ more_pages = True
+ while more_pages:
+ page = ad_group_service.get(selector)
+
+ # Display results.
+ if 'entries' in page:
+ for ad_group in page['entries']:
+ print('Ad group with name "%s", id "%s" and status "%s" was '
+ 'found.' % (ad_group['name'], ad_group['id'],
+ ad_group['status']))
+ else:
+ print('No ad groups were found.')
+ offset += PAGE_SIZE
+ selector['paging']['startIndex'] = str(offset)
+ more_pages = offset < int(page['totalNumEntries'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201809/basic_operations/get_campaigns.py b/examples/adwords/v201809/basic_operations/get_campaigns.py
new file mode 100755
index 00000000..c8ae3cb9
--- /dev/null
+++ b/examples/adwords/v201809/basic_operations/get_campaigns.py
@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all campaigns.
+
+To add a campaign, run add_campaign.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+from googleads import adwords
+
+
+PAGE_SIZE = 100
+
+
+def main(client):
+ # Initialize appropriate service.
+ campaign_service = client.GetService('CampaignService', version='v201809')
+
+ # Construct selector and get all campaigns.
+ offset = 0
+ selector = {
+ 'fields': ['Id', 'Name', 'Status'],
+ 'paging': {
+ 'startIndex': str(offset),
+ 'numberResults': str(PAGE_SIZE)
+ }
+ }
+
+ more_pages = True
+ while more_pages:
+ page = campaign_service.get(selector)
+
+ # Display results.
+ if 'entries' in page:
+ for campaign in page['entries']:
+ print('Campaign with id "%s", name "%s", and status "%s" was '
+ 'found.' % (campaign['id'], campaign['name'],
+ campaign['status']))
+ else:
+ print('No campaigns were found.')
+ offset += PAGE_SIZE
+ selector['paging']['startIndex'] = str(offset)
+ more_pages = offset < int(page['totalNumEntries'])
+
+
+if __name__ == '__main__':
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+ main(adwords_client)
diff --git a/examples/adwords/v201809/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201809/basic_operations/get_campaigns_with_awql.py
new file mode 100755
index 00000000..f5e511a2
--- /dev/null
+++ b/examples/adwords/v201809/basic_operations/get_campaigns_with_awql.py
@@ -0,0 +1,61 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all campaigns with AWQL.
+
+To add a campaign, run add_campaign.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+from googleads import adwords
+
+
+PAGE_SIZE = 100
+
+
+def main(client):
+ # Initialize appropriate service.
+ campaign_service = client.GetService('CampaignService', version='v201809')
+
+ # Construct query and get all campaigns.
+ query = (adwords.ServiceQueryBuilder()
+ .Select('Id', 'Name', 'Status')
+ .Where('Status').EqualTo('ENABLED')
+ .OrderBy('Name')
+ .Limit(0, PAGE_SIZE)
+ .Build())
+
+ for page in query.Pager(campaign_service):
+ # Display results.
+ if 'entries' in page:
+ for campaign in page['entries']:
+ print('Campaign with id "%s", name "%s", and status "%s" was '
+ 'found.' % (campaign['id'], campaign['name'],
+ campaign['status']))
+ else:
+ print('No campaigns were found.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+ main(adwords_client)
diff --git a/examples/adwords/v201809/basic_operations/get_expanded_text_ads.py b/examples/adwords/v201809/basic_operations/get_expanded_text_ads.py
new file mode 100755
index 00000000..99d409b1
--- /dev/null
+++ b/examples/adwords/v201809/basic_operations/get_expanded_text_ads.py
@@ -0,0 +1,90 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all expanded text ads for a given ad group.
+
+To add an expanded text ad, run add_expanded_text_ads.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from googleads import adwords
+
+
+PAGE_SIZE = 500
+AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
+
+
+def main(client, ad_group_id):
+ # Initialize appropriate service.
+ ad_group_ad_service = client.GetService('AdGroupAdService', version='v201809')
+
+ # Construct selector and get all ads for a given ad group.
+ offset = 0
+ selector = {
+ 'fields': ['Id', 'AdGroupId', 'Status', 'HeadlinePart1', 'HeadlinePart2',
+ 'Description'],
+ 'predicates': [
+ {
+ 'field': 'AdGroupId',
+ 'operator': 'EQUALS',
+ 'values': [ad_group_id]
+ },
+ {
+ 'field': 'AdType',
+ 'operator': 'EQUALS',
+ 'values': ['EXPANDED_TEXT_AD']
+ }
+ ],
+ 'paging': {
+ 'startIndex': str(offset),
+ 'numberResults': str(PAGE_SIZE)
+ },
+ 'ordering': [
+ {
+ 'field': 'Id',
+ 'sortOrder': 'ASCENDING'
+ }
+ ]
+ }
+ more_pages = True
+ while more_pages:
+ page = ad_group_ad_service.get(selector)
+
+ # Display results.
+ if 'entries' in page:
+ for ad in page['entries']:
+ print('ExpandedTextAd with id "%d", AdGroupId "%d", status "%s", '
+ 'headlinePart1 "%s", headlinePart2 "%s", description "%s" was '
+ 'found.' % (ad['ad']['id'], ad['adGroupId'], ad['status'],
+ ad['ad']['headlinePart1'], ad['ad']['headlinePart2'],
+ ad['ad']['description']))
+ else:
+ print('No ads were found.')
+ offset += PAGE_SIZE
+ selector['paging']['startIndex'] = str(offset)
+ more_pages = offset < int(page['totalNumEntries'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201809/basic_operations/get_keywords.py b/examples/adwords/v201809/basic_operations/get_keywords.py
new file mode 100755
index 00000000..c0a7da95
--- /dev/null
+++ b/examples/adwords/v201809/basic_operations/get_keywords.py
@@ -0,0 +1,87 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all ad group criteria in an account.
+
+To add keywords, run add_keywords.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from googleads import adwords
+
+
+PAGE_SIZE = 500
+
+ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE'
+
+
+def main(client, adgroup_id):
+ # Initialize appropriate service.
+ ad_group_criterion_service = client.GetService(
+ 'AdGroupCriterionService', version='v201809')
+
+ # Construct selector and get all ad group criteria.
+ offset = 0
+ selector = {
+ 'fields': ['Id', 'CriteriaType', 'KeywordMatchType', 'KeywordText'],
+ 'predicates': [
+ {
+ 'field': 'AdGroupId',
+ 'operator': 'EQUALS',
+ 'values': [adgroup_id]
+ },
+ {
+ 'field': 'CriteriaType',
+ 'operator': 'EQUALS',
+ 'values': ['KEYWORD']
+ }
+ ],
+ 'paging': {
+ 'startIndex': str(offset),
+ 'numberResults': str(PAGE_SIZE)
+ },
+ 'ordering': [{'field': 'KeywordText', 'sortOrder': 'ASCENDING'}]
+ }
+ more_pages = True
+ while more_pages:
+ page = ad_group_criterion_service.get(selector)
+
+ # Display results.
+ if 'entries' in page:
+ for keyword in page['entries']:
+ print('Keyword ID "%s", type "%s", text "%s", and match type '
+ '"%s" was found.' % (
+ keyword['criterion']['id'],
+ keyword['criterion']['type'],
+ keyword['criterion']['text'],
+ keyword['criterion']['matchType']))
+ else:
+ print('No keywords were found.')
+ offset += PAGE_SIZE
+ selector['paging']['startIndex'] = str(offset)
+ more_pages = offset < int(page['totalNumEntries'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, ADGROUP_ID)
diff --git a/examples/adwords/v201809/basic_operations/get_responsive_search_ads.py b/examples/adwords/v201809/basic_operations/get_responsive_search_ads.py
new file mode 100755
index 00000000..42c6be89
--- /dev/null
+++ b/examples/adwords/v201809/basic_operations/get_responsive_search_ads.py
@@ -0,0 +1,100 @@
+#!/usr/bin/env python
+#
+# Copyright 2018 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets non-removed responsive search ads in a specified ad group.
+
+To add responsive search ads, run add_responsive_search_ad.py. To get ad groups,
+run get_ad_groups.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from googleads import adwords
+
+
+PAGE_SIZE = 500
+AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
+
+
+def main(client, ad_group_id):
+ # Initialize appropriate service.
+ ad_group_ad_service = client.GetService('AdGroupAdService', version='v201809')
+
+ # Construct selector and get all ads for a given ad group.
+ offset = 0
+ selector = {
+ 'fields': ['Id', 'Status', 'ResponsiveSearchAdHeadlines',
+ 'ResponsiveSearchAdDescriptions'],
+ 'predicates': [
+ {
+ 'field': 'AdGroupId',
+ 'operator': 'EQUALS',
+ 'values': [ad_group_id]
+ },
+ {
+ 'field': 'AdType',
+ 'operator': 'EQUALS',
+ 'values': ['RESPONSIVE_SEARCH_AD']
+ }
+ ],
+ 'paging': {
+ 'startIndex': str(offset),
+ 'numberResults': str(PAGE_SIZE)
+ },
+ 'ordering': [
+ {
+ 'field': 'Id',
+ 'sortOrder': 'ASCENDING'
+ }
+ ]
+ }
+
+ more_pages = True
+ while more_pages:
+ page = ad_group_ad_service.get(selector)
+
+ # Display results.
+ if 'entries' in page:
+ for ad_group_ad in page['entries']:
+ ad = ad_group_ad['ad']
+ print('Responsive search ad with status %s and id "%d" was found.\n'
+ 'Headlines:\n%s\n'
+ 'Descriptions:\n%s'
+ % (ad_group_ad['status'], ad['id'],
+ '\n'.join(['\t%s (pinned to %s)' %
+ (headline['asset']['assetText'],
+ headline['pinnedField'])
+ for headline in ad['headlines']]),
+ '\n'.join(['\t%s (pinned to %s)' %
+ (headline['asset']['assetText'],
+ headline['pinnedField'])
+ for headline in ad['descriptions']])))
+ else:
+ print('No ads were found.')
+ offset += PAGE_SIZE
+ selector['paging']['startIndex'] = str(offset)
+ more_pages = offset < int(page['totalNumEntries'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201809/basic_operations/pause_ad.py b/examples/adwords/v201809/basic_operations/pause_ad.py
new file mode 100755
index 00000000..1e5f9733
--- /dev/null
+++ b/examples/adwords/v201809/basic_operations/pause_ad.py
@@ -0,0 +1,61 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example updates status for a given ad.
+
+To get ads, run get_text_ads.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from googleads import adwords
+
+
+AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
+AD_ID = 'INSERT_AD_ID_HERE'
+
+
+def main(client, ad_group_id, ad_id):
+ # Initialize appropriate service.
+ ad_group_ad_service = client.GetService('AdGroupAdService', version='v201809')
+
+ # Construct operations and update an ad.
+ operations = [{
+ 'operator': 'SET',
+ 'operand': {
+ 'adGroupId': ad_group_id,
+ 'ad': {
+ 'id': ad_id,
+ },
+ 'status': 'PAUSED'
+ }
+ }]
+ ads = ad_group_ad_service.mutate(operations)
+
+ # Display results.
+ for ad in ads['value']:
+ print('Ad with id "%s" was updated.'% ad['ad']['id'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, AD_GROUP_ID, AD_ID)
diff --git a/examples/adwords/v201809/basic_operations/remove_ad.py b/examples/adwords/v201809/basic_operations/remove_ad.py
new file mode 100755
index 00000000..1f0753f6
--- /dev/null
+++ b/examples/adwords/v201809/basic_operations/remove_ad.py
@@ -0,0 +1,62 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example deletes an ad using the 'REMOVE' operator.
+
+To get ads, run get_expanded_text_ads.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from googleads import adwords
+
+
+AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
+AD_ID = 'INSERT_AD_ID_HERE'
+
+
+def main(client, ad_group_id, ad_id):
+ # Initialize appropriate service.
+ ad_group_ad_service = client.GetService('AdGroupAdService', version='v201809')
+
+ # Construct operations and delete ad.
+ operations = [{
+ 'operator': 'REMOVE',
+ 'operand': {
+ 'xsi_type': 'AdGroupAd',
+ 'adGroupId': ad_group_id,
+ 'ad': {
+ 'id': ad_id
+ }
+ }
+ }]
+ result = ad_group_ad_service.mutate(operations)
+
+ # Display results.
+ for ad in result['value']:
+ print('Ad with id "%s" and type "%s" was deleted.'
+ % (ad['ad']['id'], ad['ad']['Ad.Type']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, AD_GROUP_ID, AD_ID)
diff --git a/examples/adwords/v201809/basic_operations/remove_ad_group.py b/examples/adwords/v201809/basic_operations/remove_ad_group.py
new file mode 100755
index 00000000..b35c356a
--- /dev/null
+++ b/examples/adwords/v201809/basic_operations/remove_ad_group.py
@@ -0,0 +1,58 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example deletes an ad group by setting the status to 'REMOVED'.
+
+To get ad groups, run get_ad_groups.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from googleads import adwords
+
+
+AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
+
+
+def main(client, ad_group_id):
+ # Initialize appropriate service.
+ ad_group_service = client.GetService('AdGroupService', version='v201809')
+
+ # Construct operations and delete ad group.
+ operations = [{
+ 'operator': 'SET',
+ 'operand': {
+ 'id': ad_group_id,
+ 'status': 'REMOVED'
+ }
+ }]
+ result = ad_group_service.mutate(operations)
+
+ # Display results.
+ for ad_group in result['value']:
+ print('Ad group with name "%s" and id "%s" was deleted.'
+ % (ad_group['name'], ad_group['id']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201809/basic_operations/remove_campaign.py b/examples/adwords/v201809/basic_operations/remove_campaign.py
new file mode 100755
index 00000000..778f9dc6
--- /dev/null
+++ b/examples/adwords/v201809/basic_operations/remove_campaign.py
@@ -0,0 +1,58 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example deletes a campaign by setting the status to 'REMOVED'.
+
+To get campaigns, run get_campaigns.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from googleads import adwords
+
+
+CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
+
+
+def main(client, campaign_id):
+ # Initialize appropriate service.
+ campaign_service = client.GetService('CampaignService', version='v201809')
+
+ # Construct operations and delete campaign.
+ operations = [{
+ 'operator': 'SET',
+ 'operand': {
+ 'id': campaign_id,
+ 'status': 'REMOVED'
+ }
+ }]
+ result = campaign_service.mutate(operations)
+
+ # Display results.
+ for campaign in result['value']:
+ print('Campaign with name "%s" and id "%s" was deleted.'
+ % (campaign['name'], campaign['id']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201809/basic_operations/remove_keyword.py b/examples/adwords/v201809/basic_operations/remove_keyword.py
new file mode 100755
index 00000000..f75a6547
--- /dev/null
+++ b/examples/adwords/v201809/basic_operations/remove_keyword.py
@@ -0,0 +1,67 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example deletes an ad group criterion using the 'REMOVE' operator.
+
+To get ad group criteria, run get_keywords.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from googleads import adwords
+
+
+AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
+CRITERION_ID = 'INSERT_CRITERION_ID_HERE'
+
+
+def main(client, ad_group_id, criterion_id):
+ # Initialize appropriate service.
+ ad_group_criterion_service = client.GetService(
+ 'AdGroupCriterionService', version='v201809')
+
+ # Construct operations and delete ad group criteria.
+ operations = [
+ {
+ 'operator': 'REMOVE',
+ 'operand': {
+ 'xsi_type': 'BiddableAdGroupCriterion',
+ 'adGroupId': ad_group_id,
+ 'criterion': {
+ 'id': criterion_id
+ }
+ }
+ }
+ ]
+ result = ad_group_criterion_service.mutate(operations)
+
+ # Display results.
+ for criterion in result['value']:
+ print('Ad group criterion with ad group id "%s", criterion id "%s", '
+ 'and type "%s" was deleted.'
+ % (criterion['adGroupId'], criterion['criterion']['id'],
+ criterion['criterion']['Criterion.Type']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, AD_GROUP_ID, CRITERION_ID)
diff --git a/examples/adwords/v201809/basic_operations/update_ad_group.py b/examples/adwords/v201809/basic_operations/update_ad_group.py
new file mode 100755
index 00000000..be3bad7c
--- /dev/null
+++ b/examples/adwords/v201809/basic_operations/update_ad_group.py
@@ -0,0 +1,85 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example updates the CPC bid and status for a given ad group.
+
+To get ad groups, run get_ad_groups.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from googleads import adwords
+
+
+AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
+CPC_BID_MICRO_AMOUNT = 'INSERT_CPC_BID_MICRO_AMOUNT_HERE'
+
+
+def main(client, ad_group_id, bid_micro_amount=None):
+ # Initialize appropriate service.
+ ad_group_service = client.GetService('AdGroupService', version='v201809')
+
+ # Construct operations and update an ad group.
+ operations = [{
+ 'operator': 'SET',
+ 'operand': {
+ 'id': ad_group_id,
+ 'status': 'PAUSED'
+ }
+ }]
+
+ if bid_micro_amount:
+ operations[0]['operand']['biddingStrategyConfiguration'] = {
+ 'bids': [{
+ 'xsi_type': 'CpcBid',
+ 'bid': {
+ 'microAmount': bid_micro_amount,
+ }
+ }]
+ }
+
+ ad_groups = ad_group_service.mutate(operations)
+
+ # Display results.
+ for ad_group in ad_groups['value']:
+ bidding_strategy_configuration = ad_group['biddingStrategyConfiguration']
+ # Find the CpcBid in the bidding strategy configuration's bids collection.
+ cpc_bid_micros = None
+
+ if bidding_strategy_configuration:
+ bids = bidding_strategy_configuration['bids']
+
+ if bids:
+ for bid in bids:
+ if bid['Bids.Type'] == 'CpcBid':
+ cpc_bid_micros = bid['bid']['microAmount']
+ break
+
+ print('Ad group with name "%s", and id "%s" was updated to have status '
+ '"%s" and CPC bid %d.'
+ % (ad_group['name'], ad_group['id'], ad_group['status'],
+ cpc_bid_micros))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, AD_GROUP_ID, CPC_BID_MICRO_AMOUNT)
diff --git a/examples/adwords/v201809/basic_operations/update_campaign.py b/examples/adwords/v201809/basic_operations/update_campaign.py
new file mode 100755
index 00000000..ecd19f1f
--- /dev/null
+++ b/examples/adwords/v201809/basic_operations/update_campaign.py
@@ -0,0 +1,58 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example updates a campaign by setting its status to PAUSED.
+
+To get campaigns, run get_campaigns.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from googleads import adwords
+
+
+CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
+
+
+def main(client, campaign_id):
+ # Initialize appropriate service.
+ campaign_service = client.GetService('CampaignService', version='v201809')
+
+ # Construct operations and update campaign.
+ operations = [{
+ 'operator': 'SET',
+ 'operand': {
+ 'id': campaign_id,
+ 'status': 'PAUSED'
+ }
+ }]
+ campaigns = campaign_service.mutate(operations)
+
+ # Display results.
+ for campaign in campaigns['value']:
+ print('Campaign with name "%s" and id "%s" was updated.'
+ % (campaign['name'], campaign['id']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201809/basic_operations/update_expanded_text_ad.py b/examples/adwords/v201809/basic_operations/update_expanded_text_ad.py
new file mode 100755
index 00000000..ba35d9a6
--- /dev/null
+++ b/examples/adwords/v201809/basic_operations/update_expanded_text_ad.py
@@ -0,0 +1,74 @@
+#!/usr/bin/env python
+#
+# Copyright 2018 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example updates an expanded text ad.
+
+To get expanded text ads, run get_expanded_text_ads.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+import uuid
+from googleads import adwords
+
+
+AD_ID = 'INSERT_AD_ID_HERE'
+
+
+def main(client, ad_id):
+ # Initialize appropriate service.
+ ad_service = client.GetService('AdService', version='v201809')
+
+ # Create an expanded text ad using the provided ad ID.
+ expanded_text_ad = {
+ 'xsi_type': 'ExpandedTextAd',
+ 'id': ad_id,
+ 'headlinePart1': 'Cruise to Pluto #' + str(uuid.uuid4())[:8],
+ 'headlinePart2': 'Tickets on sale now',
+ 'description': 'Best space cruise ever.',
+ 'finalUrls': ['http://www.example.com'],
+ 'finalMobileUrls': ['http://www.example.com/mobile']
+ }
+
+ # Create ad group ad operation.
+ operations = [{
+ 'operator': 'SET',
+ 'operand': expanded_text_ad
+ }]
+
+ # Updates the ad on ther server.
+ result = ad_service.mutate(operations)
+ updated_ad = result['value'][0]
+
+ print('Expanded text ad with ID %s was updated.' % updated_ad['id'])
+ print('\tHeadline part 1: %s\nHeadline part 2: %s\nDescription: %s\n'
+ 'Final URL: %s\nFinal mobile URL: %s' %
+ (updated_ad['headlinePart1'],
+ updated_ad['headlinePart2'],
+ updated_ad['description'],
+ updated_ad['finalUrls'][0],
+ updated_ad['finalMobileUrls'][0]))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, AD_ID)
diff --git a/examples/adwords/v201809/basic_operations/update_keyword.py b/examples/adwords/v201809/basic_operations/update_keyword.py
new file mode 100755
index 00000000..951ba220
--- /dev/null
+++ b/examples/adwords/v201809/basic_operations/update_keyword.py
@@ -0,0 +1,82 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example updates the bid of a keyword.
+
+To add a keyword, run add_keywords.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from googleads import adwords
+
+
+AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
+CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE'
+
+
+def main(client, ad_group_id, criterion_id):
+ # Initialize appropriate service.
+ ad_group_criterion_service = client.GetService(
+ 'AdGroupCriterionService', version='v201809')
+
+ # Construct operations and update bids.
+
+ operations = [{
+ 'operator': 'SET',
+ 'operand': {
+ 'xsi_type': 'BiddableAdGroupCriterion',
+ 'adGroupId': ad_group_id,
+ 'criterion': {
+ 'id': criterion_id,
+ },
+ 'biddingStrategyConfiguration': {
+ 'bids': [
+ {
+ 'xsi_type': 'CpcBid',
+ 'bid': {
+ 'microAmount': '1000000'
+ }
+ }
+ ]
+ }
+ }
+ }]
+ ad_group_criteria = ad_group_criterion_service.mutate(operations)
+
+ # Display results.
+ if 'value' in ad_group_criteria:
+ for criterion in ad_group_criteria['value']:
+ if criterion['criterion']['Criterion.Type'] == 'Keyword':
+ print('Ad group criterion with ad group id "%s" and criterion id '
+ '"%s" currently has bids:'
+ % (criterion['adGroupId'], criterion['criterion']['id']))
+ for bid in criterion['biddingStrategyConfiguration']['bids']:
+ print('\tType: "%s", value: %s' %
+ (bid['Bids.Type'], bid['bid']['microAmount']))
+ else:
+ print('No ad group criteria were updated.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, AD_GROUP_ID, CRITERION_ID)
diff --git a/examples/adwords/v201809/campaign_management/__init__.py b/examples/adwords/v201809/campaign_management/__init__.py
new file mode 100644
index 00000000..afa503f3
--- /dev/null
+++ b/examples/adwords/v201809/campaign_management/__init__.py
@@ -0,0 +1,15 @@
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Campaign management examples."""
diff --git a/examples/adwords/v201809/campaign_management/add_campaign_groups_and_performance_targets.py b/examples/adwords/v201809/campaign_management/add_campaign_groups_and_performance_targets.py
new file mode 100755
index 00000000..58aa128c
--- /dev/null
+++ b/examples/adwords/v201809/campaign_management/add_campaign_groups_and_performance_targets.py
@@ -0,0 +1,152 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example adds a campaign group and sets a performance target for it.
+
+To get campaigns, run get_campaigns.py. To download reports, run
+download_criteria_report_with_awql.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+"""
+
+import datetime
+import uuid
+from googleads import adwords
+
+
+CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE'
+CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE'
+
+
+def main(client, campaign_id1, campaign_id2):
+ campaign_group_id = _CreateCampaignGroup(client)
+ _AddCampaignsToGroup(client, campaign_group_id, [campaign_id1, campaign_id2])
+ _CreatePerformanceTarget(client, campaign_group_id)
+ print('Campaign group and its performance target were setup successfully.')
+
+
+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',
+ version='v201809')
+
+ # Create the operation.
+ operations = [{
+ 'operator': 'ADD',
+ # Create the campaign group.
+ 'operand': {
+ 'name': 'Mars campaign group #%d' % uuid.uuid4()
+ }
+ }]
+
+ campaign_group = campaign_group_service.mutate(operations)['value'][0]
+ campaign_group_id = campaign_group['id']
+
+ # Display the results.
+ print('Campaign group with ID "%d" and name "%s" was created.' % (
+ campaign_group_id, campaign_group['name']))
+
+ return campaign_group_id
+
+
+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.
+ campaign_service = client.GetService('CampaignService', version='v201809')
+
+ # Create the operations.
+ operations = [{
+ 'operator': 'SET',
+ 'operand': {
+ 'id': campaign_id,
+ 'campaignGroupId': campaign_group_id
+ }
+ } for campaign_id in campaign_ids]
+
+ campaign_service.mutate(operations)
+
+ # Display the results.
+ print('The following campaign IDs were added to the campaign group with ID '
+ '"%d":\n\t%s' % (campaign_group_id, campaign_ids))
+
+
+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('CampaignGroupPerformanceTargetService',
+ version='v201809')
+
+ # Create the operation.
+ operations = [{
+ 'operator': 'ADD',
+ # Create the performance target.
+ 'operand': {
+ 'campaignGroupId': campaign_group_id,
+ 'performanceTarget': {
+ # Keep the CPC for the campaigns < $3.
+ 'efficiencyTargetType': 'CPC_LESS_THAN_OR_EQUAL_TO',
+ 'efficiencyTargetValue': 3000000,
+ # Keep the maximum spend under $50.
+ 'spendTargetType': 'MAXIMUM',
+ 'spendTarget': {
+ 'microAmount': 500000000
+ },
+ # Aim for at least 3000 clicks.
+ 'volumeGoalType': 'MAXIMIZE_CLICKS',
+ 'volumeTargetValue': 3000,
+ # Start the performance target today, and run it for the next 90
+ # days.
+ 'startDate': datetime.datetime.now().strftime('%Y%m%d'),
+ 'endDate': (datetime.datetime.now() +
+ datetime.timedelta(90)).strftime('%Y%m%d')
+ }
+ }
+ }]
+
+ cgpt = cgpt_service.mutate(operations)['value'][0]
+
+ # Display the results.
+ print('Campaign performance target with ID "%d" was added for campaign '
+ 'group ID "%d".' % (cgpt['id'], cgpt['campaignGroupId']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2)
diff --git a/examples/adwords/v201809/campaign_management/add_campaign_labels.py b/examples/adwords/v201809/campaign_management/add_campaign_labels.py
new file mode 100755
index 00000000..138c5dc3
--- /dev/null
+++ b/examples/adwords/v201809/campaign_management/add_campaign_labels.py
@@ -0,0 +1,67 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example adds a label to multiple campaigns.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from googleads import adwords
+
+
+CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE'
+CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE'
+LABEL_ID = 'INSERT_LABEL_ID_HERE'
+
+
+def main(client, campaign_id1, campaign_id2, label_id):
+ # Initialize appropriate service.
+ campaign_service = client.GetService('CampaignService', version='v201809')
+
+ operations = [
+ {
+ 'operator': 'ADD',
+ 'operand': {
+ 'campaignId': campaign_id1,
+ 'labelId': label_id,
+ }
+ },
+ {
+ 'operator': 'ADD',
+ 'operand': {
+ 'campaignId': campaign_id2,
+ 'labelId': label_id,
+ }
+ }
+ ]
+
+ result = campaign_service.mutateLabel(operations)
+
+ # Display results.
+ for label in result['value']:
+ print('CampaignLabel with campaignId "%s" and labelId "%s" was added.'
+ % (label['campaignId'], label['labelId']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2, LABEL_ID)
diff --git a/examples/adwords/v201809/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201809/campaign_management/add_complete_campaigns_using_batch_job.py
new file mode 100755
index 00000000..dc18b4f4
--- /dev/null
+++ b/examples/adwords/v201809/campaign_management/add_complete_campaigns_using_batch_job.py
@@ -0,0 +1,428 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This uses the BatchJobService to create a complete Campaign.
+
+The complete Campaign created by this example also includes AdGroups and
+KeyWords.
+
+"""
+
+import random
+import time
+import uuid
+from urllib.request import urlopen
+
+from googleads import adwords
+
+
+NUMBER_OF_CAMPAIGNS_TO_ADD = 2
+NUMBER_OF_ADGROUPS_TO_ADD = 2
+NUMBER_OF_KEYWORDS_TO_ADD = 5
+MAX_POLL_ATTEMPTS = 5
+PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING')
+
+
+def main(client, number_of_campaigns, number_of_adgroups, number_of_keywords):
+ # Initialize BatchJobHelper.
+ batch_job_helper = client.GetBatchJobHelper(version='v201809')
+
+ # Create a BatchJob.
+ batch_job = AddBatchJob(client)
+ # Retrieve the URL used to upload the BatchJob operations.
+ upload_url = batch_job['uploadUrl']['url']
+ batch_job_id = batch_job['id']
+ print('Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % (
+ batch_job['id'], batch_job['status'], upload_url))
+
+ # Generate operations to upload.
+ budget_operations = BuildBudgetOperations(batch_job_helper)
+ campaign_operations = BuildCampaignOperations(
+ batch_job_helper, budget_operations, number_of_campaigns)
+ campaign_criterion_operations = BuildCampaignCriterionOperations(
+ campaign_operations)
+ adgroup_operations = BuildAdGroupOperations(
+ batch_job_helper, campaign_operations, number_of_adgroups)
+ adgroup_criterion_operations = BuildAdGroupCriterionOperations(
+ adgroup_operations, number_of_keywords)
+ adgroup_ad_operations = BuildAdGroupAdOperations(adgroup_operations)
+
+ # Upload operations.
+ batch_job_helper.UploadOperations(
+ upload_url, budget_operations, campaign_operations,
+ campaign_criterion_operations, adgroup_operations,
+ adgroup_criterion_operations, adgroup_ad_operations)
+
+ # Download and display results.
+ download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id)
+ response = urlopen(download_url).read()
+ PrintResponse(batch_job_helper, response)
+
+
+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', version='v201809')
+ # Create a BatchJob.
+ batch_job_operations = [{
+ 'operand': {},
+ 'operator': 'ADD'
+ }]
+ return batch_job_service.mutate(batch_job_operations)['value'][0]
+
+
+def BuildAdGroupAdOperations(adgroup_operations):
+ """Builds the operations adding an ExpandedTextAd to each AdGroup.
+
+ Args:
+ adgroup_operations: a list containing the operations that will add AdGroups.
+
+ Returns:
+ a list containing the operations that will create a new ExpandedTextAd for
+ each of the provided AdGroups.
+ """
+ adgroup_ad_operations = [
+ {
+ # The xsi_type of the operation can usually be guessed by the API
+ # because a given service only handles one type of operation.
+ # However, batch jobs process operations of different types, so
+ # the xsi_type must always be explicitly defined for these
+ # operations.
+ 'xsi_type': 'AdGroupAdOperation',
+ 'operand': {
+ 'adGroupId': adgroup_operation['operand']['id'],
+ 'ad': {
+ 'xsi_type': 'ExpandedTextAd',
+ 'headlinePart1': 'Luxury Cruise to Mars',
+ 'headlinePart2': 'Visit the Red Planet in style.',
+ 'description': 'Low-gravity fun for everyone!',
+ 'finalUrls': ['http://www.example.com/1']
+ }
+ },
+ 'operator': 'ADD'
+ }
+ for adgroup_operation in adgroup_operations]
+
+ return adgroup_ad_operations
+
+
+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.
+
+ Returns:
+ a list containing the operations that will create a new Keyword Criterion
+ associated with each provided AdGroup.
+ """
+ criterion_operations = [
+ {
+ # The xsi_type of the operation can usually be guessed by the API
+ # because a given service only handles one type of operation.
+ # However, batch jobs process operations of different types, so
+ # the xsi_type must always be explicitly defined for these
+ # operations.
+ 'xsi_type': 'AdGroupCriterionOperation',
+ 'operand': {
+ 'xsi_type': 'BiddableAdGroupCriterion',
+ 'adGroupId': adgroup_operation['operand']['id'],
+ 'criterion': {
+ 'xsi_type': 'Keyword',
+ # Make 50% of keywords invalid to demonstrate error handling.
+ 'text': 'mars%s%s' % (i, '!!!' if i % 2 == 0 else ''),
+ 'matchType': 'BROAD'
+ }
+ },
+ 'operator': 'ADD'
+ }
+ for adgroup_operation in adgroup_operations
+ for i in range(number_of_keywords)]
+
+ return criterion_operations
+
+
+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 is just used to identify them in the
+ BatchJobService.
+
+ Args:
+ batch_job_helper: a BatchJobHelper instance.
+ campaign_operations: a list containing the operations that will add
+ Campaigns.
+ number_of_adgroups: an int defining the number of AdGroups to be created per
+ Campaign.
+
+ Returns:
+ a list containing the operations that will add the desired number of
+ AdGroups to each of the provided Campaigns.
+ """
+ adgroup_operations = [
+ {
+ # The xsi_type of the operation can usually be guessed by the API
+ # because a given service only handles one type of operation.
+ # However, batch jobs process operations of different types, so
+ # the xsi_type must always be explicitly defined for these
+ # operations.
+ 'xsi_type': 'AdGroupOperation',
+ 'operand': {
+ 'campaignId': campaign_operation['operand']['id'],
+ 'id': batch_job_helper.GetId(),
+ 'name': 'Batch Ad Group #%s' % uuid.uuid4(),
+ 'biddingStrategyConfiguration': {
+ 'bids': [
+ {
+ 'xsi_type': 'CpcBid',
+ 'bid': {
+ 'microAmount': 10000000
+ }
+ }
+ ]
+ }
+ },
+ 'operator': 'ADD'
+ }
+ for campaign_operation in campaign_operations
+ for _ in range(number_of_adgroups)]
+
+ return adgroup_operations
+
+
+def BuildBudgetOperations(batch_job_helper):
+ """Builds the operations needed to create a new Budget.
+
+ Note: When the Budget is created, it will have a different Id than the one
+ generated here as a temporary Id. This is just used to identify it in the
+ BatchJobService.
+
+ Args:
+ batch_job_helper: a BatchJobHelper instance.
+
+ Returns:
+ a list containing the operation that will create a new Budget.
+ """
+ # A list of operations creating a Budget.
+ budget_operations = [{
+ # The xsi_type of the operation can usually be guessed by the API because
+ # a given service only handles one type of operation. However, batch jobs
+ # process operations of different types, so the xsi_type must always be
+ # explicitly defined for these operations.
+ 'xsi_type': 'BudgetOperation',
+ 'operand': {
+ 'name': 'Batch budget #%s' % uuid.uuid4(),
+ # This is a temporary Id used by the BatchJobService to identify the
+ # Budget for operations that require a budgetId.
+ 'budgetId': batch_job_helper.GetId(),
+ 'amount': {
+ 'microAmount': '50000000'
+ },
+ 'deliveryMethod': 'STANDARD'
+ },
+ 'operator': 'ADD'
+ }]
+
+ return budget_operations
+
+
+def BuildCampaignCriterionOperations(campaign_operations):
+ """Builds the operations needed to create Negative Campaign Criterion.
+
+ Args:
+ campaign_operations: a list containing the operations that will add
+ Campaigns.
+
+ Returns:
+ a list containing the operations that will create a new Negative Campaign
+ Criterion associated with each provided Campaign.
+ """
+ criterion_operations = [
+ {
+ # The xsi_type of the operation can usually be guessed by the API
+ # because a given service only handles one type of operation.
+ # However, batch jobs process operations of different types, so
+ # the xsi_type must always be explicitly defined for these
+ # operations.
+ 'xsi_type': 'CampaignCriterionOperation',
+ 'operand': {
+ 'xsi_type': 'NegativeCampaignCriterion',
+ 'campaignId': campaign_operation['operand']['id'],
+ 'criterion': {
+ 'xsi_type': 'Keyword',
+ 'matchType': 'BROAD',
+ 'text': 'venus'
+ }
+ },
+ 'operator': 'ADD'
+ }
+ for campaign_operation in campaign_operations]
+
+ return criterion_operations
+
+
+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 identify them in the
+ BatchJobService.
+
+ Args:
+ batch_job_helper: a BatchJobHelper instance.
+ budget_operations: a list containing the operation that will add the budget
+ used by these Campaigns.
+ number_of_campaigns: an int number defining the number of campaigns to be
+ created.
+
+ Returns:
+ a list containing the operations to create the desired number of Campaigns.
+ """
+ # Grab the temporary budgetId to associate with the new Campaigns.
+ budget_id = budget_operations[0]['operand']['budgetId']
+
+ campaign_operations = [
+ {
+ # The xsi_type of the operation can usually be guessed by the API
+ # because a given service only handles one type of operation.
+ # However, batch jobs process operations of different types, so
+ # the xsi_type must always be explicitly defined for these
+ # operations.
+ 'xsi_type': 'CampaignOperation',
+ 'operand': {
+ 'name': 'Batch Campaign #%s' % uuid.uuid4(),
+ # Recommendation: Set the campaign to PAUSED when creating it to
+ # stop the ads from immediately serving. Set to ENABLED once
+ # you've added targeting and the ads are ready to serve.
+ 'status': 'PAUSED',
+ # This is a temporary Id used by the BatchJobService to identify
+ # the Campaigns for operations that require a campaignId.
+ 'id': batch_job_helper.GetId(),
+ 'advertisingChannelType': 'SEARCH',
+ # Note that only the budgetId is required
+ 'budget': {
+ 'budgetId': budget_id
+ },
+ 'biddingStrategyConfiguration': {
+ 'biddingStrategyType': 'MANUAL_CPC'
+ }
+ },
+ 'operator': 'ADD'
+ }
+ for _ in range(number_of_campaigns)]
+
+ return campaign_operations
+
+
+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 = client.GetService('BatchJobService', 'v201809')
+
+ selector = {
+ 'fields': ['Id', 'Status', 'DownloadUrl'],
+ 'predicates': [
+ {
+ 'field': 'Id',
+ 'operator': 'EQUALS',
+ 'values': [batch_job_id]
+ }
+ ]
+ }
+
+ return batch_job_service.get(selector)['entries'][0]
+
+
+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 BatchJob to be polled.
+ max_poll_attempts: an int defining the number of times the BatchJob will be
+ checked to determine whether it has completed.
+
+ Returns:
+ A str containing the downloadUrl of the completed BatchJob.
+
+ Raises:
+ Exception: If the BatchJob hasn't finished after the maximum poll attempts
+ have been made.
+ """
+ batch_job = GetBatchJob(client, batch_job_id)
+ poll_attempt = 0
+ while (poll_attempt in range(max_poll_attempts) and
+ batch_job['status'] in PENDING_STATUSES):
+ sleep_interval = (30 * (2 ** poll_attempt) +
+ (random.randint(0, 10000) / 1000))
+ print('Batch Job not ready, sleeping for %s seconds.' % sleep_interval)
+ time.sleep(sleep_interval)
+ batch_job = GetBatchJob(client, batch_job_id)
+ poll_attempt += 1
+
+ if 'downloadUrl' in batch_job:
+ url = batch_job['downloadUrl']['url']
+ print('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.'
+ % (batch_job['id'], batch_job['status'], url))
+ return url
+ raise Exception('Batch Job not finished downloading. Try checking later.')
+
+
+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['mutateResponse']:
+ for data in response['mutateResponse']['rval']:
+ if 'errorList' in data:
+ print('Operation %s - FAILURE:' % data['index'])
+ print('\terrorType=%s' % data['errorList']['errors']['ApiError.Type'])
+ print('\ttrigger=%s' % data['errorList']['errors']['trigger'])
+ print('\terrorString=%s' % data['errorList']['errors']['errorString'])
+ print('\tfieldPath=%s' % data['errorList']['errors']['fieldPath'])
+ print('\treason=%s' % data['errorList']['errors']['reason'])
+ if 'result' in data:
+ print('Operation %s - SUCCESS.' % data['index'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+ main(adwords_client, NUMBER_OF_CAMPAIGNS_TO_ADD, NUMBER_OF_ADGROUPS_TO_ADD,
+ NUMBER_OF_KEYWORDS_TO_ADD)
diff --git a/examples/adwords/v201809/campaign_management/add_draft.py b/examples/adwords/v201809/campaign_management/add_draft.py
new file mode 100755
index 00000000..c2c5b8ca
--- /dev/null
+++ b/examples/adwords/v201809/campaign_management/add_draft.py
@@ -0,0 +1,81 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Creates a draft and accesses its associated draft campaign.
+
+See the Campaign Drafts and Experiments guide for more information:
+https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import uuid
+from googleads import adwords
+
+
+BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE'
+
+
+def main(client, base_campaign_id):
+ draft_service = client.GetService('DraftService', version='v201809')
+
+ draft = {
+ 'baseCampaignId': base_campaign_id,
+ 'draftName': 'Test Draft #%s' % uuid.uuid4()
+ }
+
+ draft_operation = {'operator': 'ADD', 'operand': draft}
+ draft = draft_service.mutate([draft_operation])['value'][0]
+ draft_campaign_id = draft['draftCampaignId']
+
+ # Once the draft is created, you can modify the draft campaign as if it were a
+ # real campaign. For example, you may add criteria, adjust bids, or even
+ # include additional ads. Adding a criteria is shown here.
+ campaign_criterion_service = client.GetService('CampaignCriterionService',
+ version='v201809')
+
+ criterion = {
+ 'xsi_type': 'Language',
+ 'id': 1003 # Spanish
+ }
+
+ criterion_operation = {
+ # Make sure to use the draftCampaignId when modifying the virtual draft
+ # campaign.
+ 'operator': 'ADD',
+ 'operand': {
+ 'campaignId': draft_campaign_id,
+ 'criterion': criterion
+ }
+ }
+
+ criterion = campaign_criterion_service.mutate([criterion_operation])[
+ 'value'][0]
+
+ print('Draft updated to include criteria in campaign with ID %d' %
+ draft_campaign_id)
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, BASE_CAMPAIGN_ID)
diff --git a/examples/adwords/v201809/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201809/campaign_management/add_keywords_using_incremental_batch_job.py
new file mode 100755
index 00000000..6fabf0da
--- /dev/null
+++ b/examples/adwords/v201809/campaign_management/add_keywords_using_incremental_batch_job.py
@@ -0,0 +1,257 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example illustrates how to incrementally upload keywords.
+
+Uses the BatchJobService and BatchJobHelper to incrementally upload operations.
+"""
+
+import random
+import time
+import uuid
+from urllib.request import urlopen
+
+from googleads import adwords
+
+
+ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE'
+KEYWORD_COUNT = 100
+MAX_POLL_ATTEMPTS = 5
+PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING')
+
+
+def main(client, adgroup_id):
+ # Initialize BatchJobHelper.
+ batch_job_helper = client.GetBatchJobHelper(version='v201809')
+ # Create a BatchJob.
+ batch_job = AddBatchJob(client)
+
+ # Retrieve the URL used to upload the BatchJob operations.
+ upload_url = batch_job['uploadUrl']['url']
+ batch_job_id = batch_job['id']
+ print('Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % (
+ batch_job['id'], batch_job['status'], upload_url))
+
+ # Initialize IncrementalUploadHelper.
+ incremental_uploader = batch_job_helper.GetIncrementalUploadHelper(upload_url)
+
+ # Generate and upload first set of operations.
+ adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id)
+ incremental_uploader.UploadOperations(
+ [adgroup_criterion_operations])
+ # Generate and upload second set of operations.
+ adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id)
+ incremental_uploader.UploadOperations(
+ [adgroup_criterion_operations])
+ # Generate and upload third and final set of operations.
+ adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id)
+ incremental_uploader.UploadOperations(
+ [adgroup_criterion_operations], is_last=True)
+
+ # Download and display results.
+ download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id)
+ response = urlopen(download_url).read()
+ PrintResponse(batch_job_helper, response)
+
+
+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', version='v201809')
+ # Create a BatchJob.
+ batch_job_operations = [{
+ 'operand': {},
+ 'operator': 'ADD'
+ }]
+ return batch_job_service.mutate(batch_job_operations)['value'][0]
+
+
+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
+ associated with each provided AdGroup.
+ """
+ criterion_operations = [
+ {
+ # You must specify the xsi_type of operations run by the
+ # BatchJobService.
+ 'xsi_type': 'AdGroupCriterionOperation',
+ 'operand': {
+ 'xsi_type': 'BiddableAdGroupCriterion',
+ 'adGroupId': adgroup_id,
+ 'criterion': {
+ 'xsi_type': 'Keyword',
+ # Make 10% of keywords invalid to demonstrate error handling.
+ 'text': 'mars%s%s' % (uuid.uuid4(),
+ '!!!' if i % 10 == 0 else ''),
+ 'matchType': 'BROAD'
+ }
+ },
+ 'operator': 'ADD'
+ }
+ for i in range(KEYWORD_COUNT)]
+
+ return criterion_operations
+
+
+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
+ checked to determine whether it has been canceled.
+ """
+ batch_job_service = client.GetService('BatchJobService', 'v201809')
+ batch_job['status'] = 'CANCELING'
+
+ operation = {
+ 'operator': 'SET',
+ 'operand': batch_job
+ }
+
+ batch_job_service.mutate([operation])
+
+ # Verify that the Batch Job cancels.
+ poll_attempt = 0
+
+ while (poll_attempt in range(max_poll_attempts) and
+ batch_job['status'] != 'CANCELED'):
+ sleep_interval = (30 * (2 ** poll_attempt) +
+ (random.randint(0, 10000) / 1000))
+ print('Batch Job not finished canceling, sleeping for %s seconds.'
+ % sleep_interval)
+ time.sleep(sleep_interval)
+ batch_job = GetBatchJob(client, batch_job['id'])
+ poll_attempt += 1
+
+ if batch_job['status'] == 'CANCELED':
+ print('Batch Job with ID "%d" has been successfully canceled.' %
+ batch_job['id'])
+ else:
+ print('Batch Job with ID "%d" failed to cancel after polling %d times.'
+ % (batch_job['id'], max_poll_attempts))
+
+
+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 = client.GetService('BatchJobService', 'v201809')
+
+ selector = {
+ 'fields': ['Id', 'Status', 'DownloadUrl'],
+ 'predicates': [
+ {
+ 'field': 'Id',
+ 'operator': 'EQUALS',
+ 'values': [batch_job_id]
+ }
+ ]
+ }
+
+ return batch_job_service.get(selector)['entries'][0]
+
+
+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 BatchJob to be polled.
+ max_poll_attempts: an int defining the number of times the BatchJob will be
+ checked to determine whether it has completed.
+
+ Returns:
+ A str containing the downloadUrl of the completed BatchJob.
+
+ Raises:
+ Exception: If the BatchJob hasn't finished after the maximum poll attempts
+ have been made.
+ """
+ batch_job = GetBatchJob(client, batch_job_id)
+ if batch_job['status'] == 'CANCELED':
+ raise Exception('Batch Job with ID "%s" was canceled before completing.'
+ % batch_job_id)
+
+ poll_attempt = 0
+
+ while (poll_attempt in range(max_poll_attempts) and
+ batch_job['status'] in PENDING_STATUSES):
+ sleep_interval = (30 * (2 ** poll_attempt) +
+ (random.randint(0, 10000) / 1000))
+ print('Batch Job not ready, sleeping for %s seconds.' % sleep_interval)
+ time.sleep(sleep_interval)
+ batch_job = GetBatchJob(client, batch_job_id)
+ poll_attempt += 1
+
+ if 'downloadUrl' in batch_job:
+ url = batch_job['downloadUrl']['url']
+ print('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.'
+ % (batch_job['id'], batch_job['status'], url))
+ return url
+
+ print('BatchJob with ID "%s" is being canceled because it was in a pending '
+ 'state after polling %d times.' % (batch_job_id, max_poll_attempts))
+ CancelBatchJob(client, batch_job)
+
+
+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['mutateResponse']:
+ for data in response['mutateResponse']['rval']:
+ if 'errorList' in data:
+ print('Operation %s - FAILURE:' % data['index'])
+ print('\terrorType=%s' % data['errorList']['errors']['ApiError.Type'])
+ print('\ttrigger=%s' % data['errorList']['errors']['trigger'])
+ print('\terrorString=%s' % data['errorList']['errors']['errorString'])
+ print('\tfieldPath=%s' % data['errorList']['errors']['fieldPath'])
+ print('\treason=%s' % data['errorList']['errors']['reason'])
+ if 'result' in data:
+ print('Operation %s - SUCCESS.' % data['index'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+ main(adwords_client, ADGROUP_ID)
diff --git a/examples/adwords/v201809/campaign_management/add_trial.py b/examples/adwords/v201809/campaign_management/add_trial.py
new file mode 100755
index 00000000..3237d432
--- /dev/null
+++ b/examples/adwords/v201809/campaign_management/add_trial.py
@@ -0,0 +1,117 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Creates a trial and waits for it to complete.
+
+See the Campaign Drafts and Experiments guide for more information:
+https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import time
+import uuid
+from googleads import adwords
+
+
+BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE'
+DRAFT_ID = 'INSERT_DRAFT_ID_HERE'
+MAX_POLL_ATTEMPTS = 6
+
+
+def main(client, base_campaign_id, draft_id):
+ # Initialize appropriate services.
+ trial_service = client.GetService('TrialService', version='v201809')
+ trial_async_error_service = client.GetService('TrialAsyncErrorService',
+ version='v201809')
+
+ trial = {
+ 'draftId': draft_id,
+ 'baseCampaignId': base_campaign_id,
+ 'name': 'Test Trial #%d' % uuid.uuid4(),
+ 'trafficSplitPercent': 50,
+ 'trafficSplitType': 'RANDOM_QUERY'
+ }
+
+ trial_operation = {'operator': 'ADD', 'operand': trial}
+ trial_id = trial_service.mutate([trial_operation])['value'][0]['id']
+ selector = {
+ 'fields': ['Id', 'Status', 'BaseCampaignId', 'TrialCampaignId'],
+ 'predicates': [{
+ 'field': 'Id',
+ 'operator': 'IN',
+ 'values': [trial_id]
+ }]
+ }
+
+ # Since creating a trial is asynchronous, we have to poll it to wait for it to
+ # finish.
+ poll_attempts = 0
+ is_pending = True
+ trial = None
+
+ while is_pending and poll_attempts < MAX_POLL_ATTEMPTS:
+ trial = trial_service.get(selector)['entries'][0]
+ print('Trial ID %d has status "%s"' % (trial['id'], trial['status']))
+ poll_attempts += 1
+ is_pending = trial['status'] == 'CREATING'
+
+ if is_pending:
+ sleep_seconds = 30 * (2 ** poll_attempts)
+ print('Sleeping for %d seconds.' % sleep_seconds)
+ time.sleep(sleep_seconds)
+
+ if trial['status'] == 'ACTIVE':
+ # The trial creation was successful.
+ print('Trial created with ID %d and trial campaign ID %d' % (
+ trial['id'], trial['trialCampaignId']))
+ elif trial['status'] == 'CREATION_FAILED':
+ # The trial creation failed, and errors can be fetched from the
+ # TrialAsyncErrorService.
+ selector = {
+ 'fields': ['TrialId', 'AsyncError'],
+ 'predicates': [{
+ 'field': 'TrialId',
+ 'operator': 'IN',
+ 'values': [trial['id']]
+ }]
+ }
+
+ errors = trial_async_error_service.get(selector)['entries']
+
+ if not errors:
+ print('Could not retrieve errors for trial %d' % trial['id'])
+ else:
+ print('Could not create trial due to the following errors:')
+ for error in errors:
+ print('Error: %s' % error['asyncError'])
+ else:
+ # Most likely, the trial is still being created. You can continue polling,
+ # but we have limited the number of attempts in the example.
+ print('Timed out waiting to create trial from draft %d with base campaign '
+ '%d' % (draft_id, base_campaign_id))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, BASE_CAMPAIGN_ID, DRAFT_ID)
diff --git a/examples/adwords/v201809/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201809/campaign_management/get_all_disapproved_ads.py
new file mode 100755
index 00000000..c7afeb7b
--- /dev/null
+++ b/examples/adwords/v201809/campaign_management/get_all_disapproved_ads.py
@@ -0,0 +1,103 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all disapproved ads for a given campaign.
+
+To add an ad, run add_ads.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from googleads import adwords
+
+
+AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
+PAGE_SIZE = 100
+
+
+def main(client, ad_group_id):
+ # Initialize appropriate service.
+ ad_group_ad_service = client.GetService('AdGroupAdService', version='v201809')
+
+ # Construct selector and get all ads for a given ad group.
+ offset = 0
+ selector = {
+ 'fields': ['Id', 'PolicySummary'],
+ 'predicates': [
+ {
+ 'field': 'AdGroupId',
+ 'operator': 'EQUALS',
+ 'values': [ad_group_id]
+ },
+ {
+ 'field': 'CombinedApprovalStatus',
+ 'operator': 'EQUALS',
+ 'values': 'DISAPPROVED'
+ }
+ ],
+ 'paging': {
+ 'startIndex': str(offset),
+ 'numberResults': str(PAGE_SIZE)
+ }
+ }
+
+ more_pages = True
+ disapproved_count = 0
+
+ # Display results.
+ while more_pages:
+ page = ad_group_ad_service.get(selector)
+
+ if 'entries' in page:
+ for ad in page['entries']:
+ disapproved_count += 1
+ policy_summary = ad['policySummary']
+
+ print('Ad with id "%s" was disapproved with the following policy '
+ 'topic entries:' % ad['ad']['id'])
+ # Display the policy topic entries related to the ad disapproval.
+ for policy_topic_entry in policy_summary['policyTopicEntries']:
+ print(' topic ID: %s, topic name: %s, Help Center URL: %s' % (
+ policy_topic_entry['policyTopicId'],
+ policy_topic_entry['policyTopicName'],
+ policy_topic_entry['policyTopicHelpCenterUrl']))
+ # Display the attributes and values that triggered the policy topic.
+ policy_topic_evidences = policy_topic_entry['policyTopicEvidences']
+ if policy_topic_evidences:
+ for evidence in policy_topic_entry['policyTopicEvidences']:
+ print(' evidence type: %s'
+ % evidence['policyTopicEvidenceType'])
+ evidence_text_list = evidence['evidenceTextList']
+ if evidence_text_list:
+ for index, evidence_text in enumerate(evidence_text_list):
+ print(' evidence text[%d]: %s' % (index, evidence_text))
+
+ offset += PAGE_SIZE
+ selector['paging']['startIndex'] = str(offset)
+ more_pages = offset < int(page['totalNumEntries'])
+
+ print('%d disapproved ads were found.' % disapproved_count)
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201809/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201809/campaign_management/get_all_disapproved_ads_with_awql.py
new file mode 100755
index 00000000..f4f890cf
--- /dev/null
+++ b/examples/adwords/v201809/campaign_management/get_all_disapproved_ads_with_awql.py
@@ -0,0 +1,88 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all disapproved ads for a given campaign with AWQL.
+
+To add an ad, run add_ads.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from googleads import adwords
+
+
+AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
+PAGE_SIZE = 100
+
+
+def main(client, ad_group_id):
+ # Initialize appropriate service.
+ ad_group_ad_service = client.GetService('AdGroupAdService',
+ version='v201809')
+
+ # Construct query and get all ads for a given campaign.
+ query = (adwords.ServiceQueryBuilder()
+ .Select('Id', 'PolicySummary')
+ .Where('AdGroupId').EqualTo(ad_group_id)
+ .Where('CombinedApprovalStatus').EqualTo('DISAPPROVED')
+ .OrderBy('Id')
+ .Limit(0, PAGE_SIZE)
+ .Build())
+ disapproved_count = 0
+
+ # Display results.
+ while True:
+ page = ad_group_ad_service.query(query)
+
+ if 'entries' in page:
+ for ad in page['entries']:
+ disapproved_count += 1
+ policy_summary = ad['policySummary']
+
+ print('Ad with id "%s" was disapproved with the following policy '
+ 'topic entries:' % ad['ad']['id'])
+ # Display the policy topic entries related to the ad disapproval.
+ for policy_topic_entry in policy_summary['policyTopicEntries']:
+ print(' topic ID: %s, topic name: %s' % (
+ policy_topic_entry['policyTopicId'],
+ policy_topic_entry['policyTopicName']))
+ # Display the attributes and values that triggered the policy topic.
+ if ('policyTopicEvidences' in policy_topic_entry
+ and policy_topic_entry['policyTopicEvidences']):
+ for evidence in policy_topic_entry['policyTopicEvidences']:
+ print(' evidence type: %s'
+ % evidence['policyTopicEvidenceType'])
+ evidence_text_list = evidence['evidenceTextList']
+ if evidence_text_list:
+ for index, evidence_text in enumerate(evidence_text_list):
+ print(' evidence text[%d]: %s' % (index, evidence_text))
+
+ if not query.HasNext(page):
+ break
+ query.NextPage()
+
+ print('%d disapproved ads were found.' % disapproved_count)
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201809/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201809/campaign_management/get_campaigns_by_label.py
new file mode 100755
index 00000000..6a401529
--- /dev/null
+++ b/examples/adwords/v201809/campaign_management/get_campaigns_by_label.py
@@ -0,0 +1,83 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all campaigns with a specific label.
+
+To add a label to campaigns, run add_campaign_labels.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+from googleads import adwords
+
+
+LABEL_ID = 'INSERT_LABEL_ID_HERE'
+PAGE_SIZE = 100
+
+
+def main(client, label_id):
+ # Initialize appropriate service.
+ campaign_service = client.GetService('CampaignService', version='v201809')
+
+ offset = 0
+ selector = {
+ 'fields': ['Id', 'Name', 'Labels'],
+ # Labels filtering is performed by ID. You can use CONTAINS_ANY to select
+ # campaigns with any of the label IDs, CONTAINS_ALL to select campaigns
+ # with all of the label IDs, or CONTAINS_NONE to select campaigns with
+ # none of the label IDs.
+ 'ordering': {
+ 'field': 'Name',
+ 'sortOrder': 'ASCENDING'
+ },
+ 'paging': {
+ 'startIndex': str(offset),
+ 'numberResults': str(PAGE_SIZE)
+ },
+ 'predicates': {
+ 'field': 'Labels',
+ 'operator': 'CONTAINS_ANY',
+ 'values': [label_id]
+ }
+ }
+
+ more_pages = True
+ while more_pages:
+ page = campaign_service.get(selector)
+
+ # Display results.
+ if 'entries' in page:
+ for campaign in page['entries']:
+ print('Campaign found with Id "%s", name "%s", and labels: %s'
+ % (campaign['id'], campaign['name'], campaign['labels']))
+ else:
+ print('No campaigns were found.')
+
+ offset += PAGE_SIZE
+ selector['paging']['startIndex'] = str(offset)
+ more_pages = offset < int(page['totalNumEntries'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, LABEL_ID)
diff --git a/examples/adwords/v201809/campaign_management/graduate_trial.py b/examples/adwords/v201809/campaign_management/graduate_trial.py
new file mode 100755
index 00000000..73e24f12
--- /dev/null
+++ b/examples/adwords/v201809/campaign_management/graduate_trial.py
@@ -0,0 +1,79 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Illustrates how to graduate a trial.
+
+See the Campaign Drafts and Experiments guide for more information:
+https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import uuid
+from googleads import adwords
+
+
+TRIAL_ID = 'INSERT_TRIAL_ID_HERE'
+
+
+def main(client, trial_id):
+ # Initialize appropriate services.
+ trial_service = client.GetService('TrialService', version='v201809')
+ budget_service = client.GetService('BudgetService', version='v201809')
+
+ # To graduate a trial, you must specify a different budget from the base
+ # campaign. The base campaign (in order to have had a trial based on it) must
+ # have a non-shared budget, so it cannot be shared with the new independent
+ # campaign created by graduation.
+ budget = {
+ 'name': 'Budget #%d' % uuid.uuid4(),
+ 'amount': {'microAmount': 50000000},
+ 'deliveryMethod': 'STANDARD'
+ }
+
+ budget_operation = {'operator': 'ADD', 'operand': budget}
+ # Add budget
+ budget_id = budget_service.mutate([budget_operation])['value'][0]['budgetId']
+
+ trial = {
+ 'id': trial_id,
+ 'budgetId': budget_id,
+ 'status': 'GRADUATED'
+ }
+
+ trial_operation = {'operator': 'SET', 'operand': trial}
+
+ # Update the trial.
+ trial = trial_service.mutate([trial_operation])['value'][0]
+
+ # Graduation is a synchronous operation, so the campaign is already ready. If
+ # you promote instead, make sure to see the polling scheme demonstrated in
+ # add_trial.py to wait for the asynchronous operation to finish.
+ print('Trial ID %d graduated. Campaign %d was given a new budget ID %d and '
+ 'is no longer dependent on this trial.' % (
+ trial['id'], trial['trialCampaignId'], budget_id))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, TRIAL_ID)
diff --git a/examples/adwords/v201809/campaign_management/set_ad_parameters.py b/examples/adwords/v201809/campaign_management/set_ad_parameters.py
new file mode 100755
index 00000000..bab7186f
--- /dev/null
+++ b/examples/adwords/v201809/campaign_management/set_ad_parameters.py
@@ -0,0 +1,100 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example adds a text ad with ad parameters.
+
+To get ad groups, run get_ad_groups.py. To get keywords, run add_keywords.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from googleads import adwords
+
+
+AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
+CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE'
+
+
+def main(client, ad_group_id, criterion_id):
+ # Initialize appropriate service.
+ ad_group_ad_service = client.GetService('AdGroupAdService', version='v201809')
+ ad_param_service = client.GetService('AdParamService', version='v201809')
+
+ # Construct operations for adding text ad object and add to an ad group.
+ operations = [{
+ 'operator': 'ADD',
+ 'operand': {
+ 'xsi_type': 'AdGroupAd',
+ 'adGroupId': ad_group_id,
+ 'ad': {
+ 'xsi_type': 'TextAd',
+ 'finalUrls': ['http://www.example.com'],
+ 'displayUrl': 'example.com',
+ 'description1': 'Low-gravity fun for {param1:cheap}.',
+ 'description2': 'Only {param2:a few} seats left!',
+ 'headline': 'Luxury Mars Cruises'
+ },
+ 'status': 'ENABLED'
+ }
+ }]
+ ads = ad_group_ad_service.mutate(operations)['value']
+
+ # Display results.
+ for ad in ads:
+ print('Text ad with id "%s" was successfully added to an ad group with '
+ 'id "%s".' % (ad['adGroupId'], ad['ad']['id']))
+
+ # Construct operations for setting ad parameters.
+ operations = [
+ {
+ 'operator': 'SET',
+ 'operand': {
+ 'adGroupId': ad_group_id,
+ 'criterionId': criterion_id,
+ 'insertionText': u'£100',
+ 'paramIndex': '1'
+ }
+ },
+ {
+ 'operator': 'SET',
+ 'operand': {
+ 'adGroupId': ad_group_id,
+ 'criterionId': criterion_id,
+ 'insertionText': '50',
+ 'paramIndex': '2'
+ }
+ }
+ ]
+ ad_params = ad_param_service.mutate(operations)
+
+ # Display results.
+ for ad_param in ad_params:
+ print('Ad parameter with text "%s" was successfully set for criterion '
+ 'with id "%s" and ad group id "%s".'
+ % (ad_param['insertionText'], ad_param['criterionId'],
+ ad_param['adGroupId']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, AD_GROUP_ID, CRITERION_ID)
diff --git a/examples/adwords/v201809/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201809/campaign_management/set_criterion_bid_modifier.py
new file mode 100755
index 00000000..9c7a869c
--- /dev/null
+++ b/examples/adwords/v201809/campaign_management/set_criterion_bid_modifier.py
@@ -0,0 +1,77 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example sets a bid modifier for the mobile platform on given campaign.
+
+To get campaigns, run get_campaigns.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+from googleads import adwords
+
+
+CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
+BID_MODIFIER = '1.5'
+
+
+def main(client, campaign_id, bid_modifier):
+ # Initialize appropriate service.
+ campaign_criterion_service = client.GetService(
+ 'CampaignCriterionService', version='v201809')
+
+ # Create mobile platform.The ID can be found in the documentation.
+ # https://developers.google.com/adwords/api/docs/appendix/platforms
+ mobile = {
+ 'xsi_type': 'Platform',
+ 'id': '30001'
+ }
+
+ # Create campaign criterion with modified bid.
+ campaign_criterion = {
+ 'campaignId': campaign_id,
+ 'criterion': mobile,
+ 'bidModifier': bid_modifier
+ }
+
+ # Create operations.
+ operations = [
+ {
+ 'operator': 'SET',
+ 'operand': campaign_criterion
+ }
+ ]
+
+ # Make the mutate request.
+ result = campaign_criterion_service.mutate(operations)
+
+ # Display the resulting campaign criteria.
+ for campaign_criterion in result['value']:
+ print('Campaign criterion with campaign id "%s" and criterion id "%s" '
+ 'was updated with bid modifier "%s".'
+ % (campaign_criterion['campaignId'],
+ campaign_criterion['criterion']['id'],
+ campaign_criterion['bidModifier']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, CAMPAIGN_ID, BID_MODIFIER)
diff --git a/examples/adwords/v201809/campaign_management/validate_text_ad.py b/examples/adwords/v201809/campaign_management/validate_text_ad.py
new file mode 100755
index 00000000..ea1035d9
--- /dev/null
+++ b/examples/adwords/v201809/campaign_management/validate_text_ad.py
@@ -0,0 +1,84 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example shows how to use validateOnly SOAP header.
+
+No objects will be created, but exceptions will still be returned.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+from googleads import adwords
+from googleads import errors
+
+
+AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
+
+
+def main(client, ad_group_id):
+ # Initialize appropriate service with validate only flag enabled.
+ client.validate_only = True
+ ad_group_ad_service = client.GetService('AdGroupAdService', version='v201809')
+
+ # Construct operations to add an expanded text ad.
+ operations = [{
+ 'operator': 'ADD',
+ 'operand': {
+ 'xsi_type': 'AdGroupAd',
+ 'adGroupId': ad_group_id,
+ 'ad': {
+ 'xsi_type': 'ExpandedTextAd',
+ 'headlinePart1': 'Luxury Cruise to Mars',
+ 'headlinePart2': 'Visit the Red Planet in style.',
+ 'description': 'Low-gravity fun for everyone!',
+ 'finalUrls': ['http://www.example.com']
+ }
+ }
+ }]
+ ad_group_ad_service.mutate(operations)
+ # No error means the request is valid.
+
+ # Now let's check an invalid ad using a very long line to trigger an error.
+ operations = [{
+ 'operator': 'ADD',
+ 'operand': {
+ 'xsi_type': 'AdGroupAd',
+ 'adGroupId': ad_group_id,
+ 'ad': {
+ 'xsi_type': 'ExpandedTextAd',
+ 'headlinePart1': 'Luxury Cruise to Mars',
+ 'headlinePart2': 'Visit the Red Planet in style.',
+ 'description': 'Low-gravity fun for all astronauts in orbit',
+ 'finalUrls': ['http://www.example.com'],
+ }
+ }
+ }]
+ try:
+ ad_group_ad_service.mutate(operations)
+ except errors.GoogleAdsServerFault as e:
+ print('Validation correctly failed with "%s".' % str(e))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201809/error_handling/__init__.py b/examples/adwords/v201809/error_handling/__init__.py
new file mode 100644
index 00000000..7b767e05
--- /dev/null
+++ b/examples/adwords/v201809/error_handling/__init__.py
@@ -0,0 +1,15 @@
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Error handling examples."""
diff --git a/examples/adwords/v201809/error_handling/handle_partial_failures.py b/examples/adwords/v201809/error_handling/handle_partial_failures.py
new file mode 100755
index 00000000..fc4c703d
--- /dev/null
+++ b/examples/adwords/v201809/error_handling/handle_partial_failures.py
@@ -0,0 +1,131 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example demonstrates how to handle partial failures.
+
+To get ad groups, run get_ad_groups.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+from googleads import adwords
+
+
+AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
+
+
+def main(client, ad_group_id):
+ # Enable partial failure.
+ client.partial_failure = True
+
+ # Initialize appropriate service.
+ ad_group_criterion_service = client.GetService(
+ 'AdGroupCriterionService', version='v201809')
+
+ # Construct keyword ad group criteria objects.
+ keywords = [
+ {
+ 'xsi_type': 'BiddableAdGroupCriterion',
+ 'adGroupId': ad_group_id,
+ 'criterion': {
+ 'xsi_type': 'Keyword',
+ 'matchType': 'BROAD',
+ 'text': 'mars cruise'
+ }
+ },
+ {
+ 'xsi_type': 'BiddableAdGroupCriterion',
+ 'adGroupId': ad_group_id,
+ 'criterion': {
+ 'xsi_type': 'Keyword',
+ 'matchType': 'BROAD',
+ 'text': r'inv\@lid cruise'
+ }
+ },
+ {
+ 'xsi_type': 'BiddableAdGroupCriterion',
+ 'adGroupId': ad_group_id,
+ 'criterion': {
+ 'xsi_type': 'Keyword',
+ 'matchType': 'BROAD',
+ 'text': 'venus cruise'
+ }
+ },
+ {
+ 'xsi_type': 'BiddableAdGroupCriterion',
+ 'adGroupId': ad_group_id,
+ 'criterion': {
+ 'xsi_type': 'Keyword',
+ 'matchType': 'BROAD',
+ 'text': r'b\(a\)d keyword cruise'
+ }
+ }
+ ]
+
+ # Construct operations and add ad group criteria.
+ operations = []
+ for keyword in keywords:
+ operations.append(
+ {
+ 'operator': 'ADD',
+ 'operand': keyword
+ })
+ result = ad_group_criterion_service.mutate(operations)
+
+ # Display results.
+ for criterion in result['value']:
+ if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion':
+ print('Added keyword ad group criterion with ad group id "%s", '
+ 'criterion id "%s", text "%s", and match type "%s" was '
+ 'added.'
+ % (criterion['adGroupId'], criterion['criterion']['id'],
+ criterion['criterion']['text'],
+ criterion['criterion']['matchType']))
+
+ for error in result['partialFailureErrors']:
+ field_path_elements = error['fieldPathElements']
+ first_field_path_element = None
+
+ if field_path_elements:
+ first_field_path_element = field_path_elements[0]
+
+ if (first_field_path_element and
+ first_field_path_element['field'] == 'operations' and
+ 'index' in first_field_path_element):
+ operation_index = first_field_path_element['index']
+
+ adgroup_criterion = operations[operation_index]['operand']
+
+ print('Ad group criterion with ad group ID %s and keyword "%s" triggered '
+ 'a failure for the following reason: %s.'
+ % (adgroup_criterion['adGroupId'],
+ adgroup_criterion['criterion']['text'],
+ error['errorString']))
+ else:
+ print('A failure has occurred for the following reasons: %s\n'
+ % error['errorString'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201809/extensions/__init__.py b/examples/adwords/v201809/extensions/__init__.py
new file mode 100644
index 00000000..594717b1
--- /dev/null
+++ b/examples/adwords/v201809/extensions/__init__.py
@@ -0,0 +1,15 @@
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Extension examples."""
diff --git a/examples/adwords/v201809/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201809/extensions/add_google_my_business_location_extensions.py
new file mode 100755
index 00000000..0a467e25
--- /dev/null
+++ b/examples/adwords/v201809/extensions/add_google_my_business_location_extensions.py
@@ -0,0 +1,156 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+"""Adds a feed that syncs feed items from a Google My Business (GMB) account.
+
+This example associates the feed with a customer.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import time
+import uuid
+
+from googleads import adwords
+from googleads import errors
+
+GMB_EMAIL_ADDRESS = 'INSERT_GMB_EMAIL_ADDRESS_HERE'
+
+# If the gmb_email_address above is for a GMB manager instead of
+# the GMB account owner, then set business_account_identifier to the
+# +Page ID of a location for which the manager has access. See the
+# location extensions guide at
+# https://developers.google.com/adwords/api/docs/guides/feed-services-locations
+# for details.
+BUSINESS_ACCOUNT_IDENTIFIER = None
+
+# The placeholder type for location extensions.
+# See the Placeholder reference page for a list of all the placeholder types
+# and fields:
+# https://developers.google.com/adwords/api/docs/appendix/placeholders
+PLACEHOLDER_LOCATION = 7
+
+# The maximum number of CustomerFeed ADD operation attempts to make before
+# throwing an exception.
+MAX_CUSTOMER_FEED_ADD_ATTEMPTS = 10
+
+
+def main(client, gmb_email_address, gmb_access_token,
+ business_account_identifier=None):
+ # Create a feed that will sync to the Google Places account specified by
+ # gmb_email_address. Do not add FeedAttributes to this object,
+ # as AdWords will add them automatically because this will be a
+ # system generated feed.
+ feed = {
+ 'name': 'GMB feed #%s' % uuid.uuid4(),
+ 'systemFeedGenerationData': {
+ 'xsi_type': 'PlacesLocationFeedData',
+ 'oAuthInfo': {
+ 'httpMethod': 'GET',
+ 'httpRequestUrl': 'https://www.googleapis.com/auth/adwords',
+ 'httpAuthorizationHeader': 'Bearer %s' % gmb_access_token
+ },
+ 'emailAddress': gmb_email_address,
+ },
+ # Since this feed's feed items will be managed by AdWords, you must set
+ # its origin to ADWORDS.
+ 'origin': 'ADWORDS'
+ }
+
+ # Only include the business_account_identifier if it's specified.
+ if business_account_identifier:
+ feed['systemFeedGenerationData']['businessAccountIdentifier'] = (
+ business_account_identifier
+ )
+
+ # Create an operation to add the feed.
+ gmb_operations = [{
+ 'operator': 'ADD',
+ 'operand': feed
+ }]
+
+ gmb_response = client.GetService('FeedService', version='v201809').mutate(
+ gmb_operations)
+ added_feed = gmb_response['value'][0]
+ print('Added GMB feed with ID: %d\n' % added_feed['id'])
+
+ # Add a CustomerFeed that associates the feed with this customer for the
+ # LOCATION placeholder type.
+ customer_feed = {
+ 'feedId': added_feed['id'],
+ 'placeholderTypes': [PLACEHOLDER_LOCATION],
+ # Create a matching function that will always evaluate to True.
+ 'matchingFunction': {
+ 'operator': 'IDENTITY',
+ 'lhsOperand': {
+ 'xsi_type': 'ConstantOperand',
+ 'type': 'BOOLEAN',
+ 'booleanValue': True
+ }
+ }
+ }
+
+ customer_feed_operation = {
+ 'xsi_type': 'CustomerFeedOperation',
+ 'operator': 'ADD',
+ 'operand': customer_feed
+ }
+
+ customer_feed_service = client.GetService(
+ 'CustomerFeedService', version='v201809')
+ added_customer_feed = None
+
+ i = 0
+ while i < MAX_CUSTOMER_FEED_ADD_ATTEMPTS and added_customer_feed is None:
+ try:
+ added_customer_feed = customer_feed_service.mutate([
+ customer_feed_operation])['value'][0]
+ except errors.GoogleAdsServerFault:
+ # Wait using exponential backoff policy
+ sleep_seconds = 2 ** i
+ print('Attempt %d to add the CustomerFeed was not successful.'
+ 'Waiting %d seconds before trying again.\n' % (i, sleep_seconds))
+
+ time.sleep(sleep_seconds)
+ i += 1
+
+ if added_customer_feed is None:
+ raise errors.GoogleAdsError(
+ 'Could not create the CustomerFeed after %s attempts. Please retry the '
+ 'CustomerFeed ADD operation later.' % MAX_CUSTOMER_FEED_ADD_ATTEMPTS)
+
+ print('Added CustomerFeed for feed ID %d and placeholder type %d\n'
+ % (added_customer_feed['id'], added_customer_feed['placeholderTypes']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ # If the GMB_EMAIL_ADDRESS above is the same user you used to generate your
+ # AdWords API refresh token, leave the assignment below unchanged. Otherwise,
+ # to obtain an access token for your GMB account, you can run the
+ # generate_refresh_token.py example after manually replacing the scope with
+ # "https://www.google.com/local/add".
+ GMB_ACCESS_TOKEN = adwords_client.oauth2_client.oauth2credentials.access_token
+
+ main(adwords_client, GMB_EMAIL_ADDRESS, GMB_ACCESS_TOKEN,
+ BUSINESS_ACCOUNT_IDENTIFIER)
diff --git a/examples/adwords/v201809/extensions/add_prices.py b/examples/adwords/v201809/extensions/add_prices.py
new file mode 100755
index 00000000..fbfa40db
--- /dev/null
+++ b/examples/adwords/v201809/extensions/add_prices.py
@@ -0,0 +1,157 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+"""Adds a price extension and associates it with an account.
+
+Campaign targeting is also set usin the specified campaign ID. To get campaigns,
+run get_campaigns.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from googleads import adwords
+from googleads import errors
+
+
+CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
+MICROS_PER_DOLLAR = 1000000
+
+
+def main(client, campaign_id):
+ # Initialize appropriate service.
+ customer_extension_setting_service = client.GetService(
+ 'CustomerExtensionSettingService', 'v201809')
+
+ # To create a price extension, at least three table rows are needed.
+ table_rows = [
+ CreatePriceTableRow('Scrubs', 'Body Scrub, Salt Scrub',
+ 'https://www.example.com/scrubs',
+ 60 * MICROS_PER_DOLLAR, 'USD', 'PER_HOUR',
+ final_mobile_url='http://m.example.com/scrubs'),
+ CreatePriceTableRow('Hair Cuts', 'Once a month',
+ 'https://www.example.com/haircuts',
+ 75 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH',
+ final_mobile_url='http://m.example.com/haircuts'),
+ CreatePriceTableRow('Skin Care Package', 'Four times a month',
+ 'https://www.examples.com/skincarepackage',
+ 250 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH',
+ final_mobile_url=(
+ 'http://m.example.com/skincarepackage'))
+ ]
+
+ # Create the price extension feed item.
+ customer_extension_setting = {
+ 'extensionType': 'PRICE',
+ 'extensionSetting': {
+ 'extensions': [{
+ 'priceExtensionType': 'SERVICES',
+ 'trackingUrlTemplate': 'http://tracker.example.com/?u={lpurl}',
+ 'language': 'en',
+ 'campaignTargeting': {
+ 'TargetingCampaignId': campaign_id
+ },
+ 'scheduling': {
+ 'feedItemSchedules': [
+ {
+ 'dayOfWeek': 'SATURDAY',
+ 'startHour': 10,
+ 'startMinute': 'ZERO',
+ 'endHour': 22,
+ 'endMinute': 'ZERO'
+ },
+ {
+ 'dayOfWeek': 'SUNDAY',
+ 'startHour': 10,
+ 'startMinute': 'ZERO',
+ 'endHour': 18,
+ 'endMinute': 'ZERO'
+ }
+ ]
+ },
+ 'tableRows': table_rows,
+ # Price qualifier is optional.
+ 'priceQualifier': 'FROM',
+ 'xsi_type': 'PriceFeedItem'
+ }]
+ }
+ }
+
+ # Create an operation to add the feed.
+ operations = [{
+ 'operator': 'ADD',
+ 'operand': customer_extension_setting
+ }]
+
+ # Add the price extension.
+ response = customer_extension_setting_service.mutate(operations)
+
+ # Print the results.
+ if 'value' in response:
+ print('Extension setting with type "%s" was added to your account.'
+ % response['value'][0]['extensionType'])
+ else:
+ raise errors.GoogleAdsError('No extension settings were added.')
+
+
+def CreatePriceTableRow(header, description, final_url, price_in_micros,
+ currency_code, price_unit, final_mobile_url=None):
+ """Helper function to generate a single row of a price table.
+
+ Args:
+ header: A str containing the header text of this row.
+ description: A str description of this row in the price table.
+ final_url: A str containing the final URL after all cross domain redirects.
+ price_in_micros: An int indicating the price of the given currency in
+ micros.
+ currency_code: A str indicating the currency code being used.
+ price_unit: A str enum indicating the price unit for this row.
+ final_mobile_url: A str containing the final mobile URL after all cross
+ domain redirects.
+
+ Returns:
+ A dictionary containing the contents of the generated price table row.
+ """
+ table_row = {
+ 'header': header,
+ 'description': description,
+ 'finalUrls': {'urls': [final_url]},
+ 'price': {
+ 'money': {
+ 'microAmount': price_in_micros,
+ },
+ 'currencyCode': currency_code
+ },
+ 'priceUnit': price_unit,
+ 'xsi_type': 'PriceTableRow'
+ }
+
+ if final_mobile_url:
+ table_row['finalMobileUrls'] = {
+ 'urls': [final_mobile_url]
+ }
+
+ return table_row
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+ main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201809/extensions/add_site_links.py b/examples/adwords/v201809/extensions/add_site_links.py
new file mode 100755
index 00000000..f9b68717
--- /dev/null
+++ b/examples/adwords/v201809/extensions/add_site_links.py
@@ -0,0 +1,146 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Adds sitelinks to a campaign using the CampaignExtensionSettingService.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+from datetime import datetime
+
+from googleads import adwords
+from googleads import errors
+from pytz import timezone
+
+CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
+
+
+def main(client, campaign_id):
+ # Initialize appropriate services.
+ campaign_extension_setting_service = client.GetService(
+ 'CampaignExtensionSettingService', version='v201809')
+ customer_service = client.GetService('CustomerService', version='v201809')
+ # Find the matching customer and its time zone. The getCustomers method will
+ # return a single Customer object corresponding to the configured
+ # clientCustomerId.
+ customer = customer_service.getCustomers()[0]
+ customer_tz = timezone(customer['dateTimeZone'])
+ time_fmt = '%s %s' % ('%Y%m%d %H%M%S', customer_tz)
+
+ print('Found customer ID %d with time zone "%s".'
+ % (customer['customerId'], customer['dateTimeZone']))
+
+ # Create the sitelinks
+ sitelink1 = {
+ 'xsi_type': 'SitelinkFeedItem',
+ 'sitelinkText': 'Store Hours',
+ 'sitelinkFinalUrls': {'urls': ['http://www.example.com/storehours']}
+ }
+
+ # Show the Thanksgiving specials link only from 20 - 27 Nov.
+ sitelink2 = {
+ 'xsi_type': 'SitelinkFeedItem',
+ 'sitelinkText': 'Thanksgiving Specials',
+ 'sitelinkFinalUrls': {'urls': ['http://www.example.com/thanksgiving']},
+ # The time zone of the start and end date/times must match the time zone
+ # of the customer.
+ 'startTime': datetime(datetime.now().year, 11, 20, 0, 0, 0, 0,
+ customer_tz).strftime(time_fmt),
+ 'endTime': datetime(datetime.now().year, 11, 27, 23, 59, 59, 59,
+ customer_tz).strftime(time_fmt),
+ # Target this sitelink for United States only. For valid geolocation
+ # codes, see:
+ # https://developers.google.com/adwords/api/docs/appendix/geotargeting
+ 'geoTargeting': {'id': 2840},
+ # Restrict targeting only to people physically within the United States.
+ # Otherwise, this could also show to people interested in the United
+ # States, but not physically located there.
+ 'geoTargetingRestriction': {
+ 'geoRestriction': 'LOCATION_OF_PRESENCE'
+ }
+ }
+
+ # Show the wifi details primarily for high end mobile users.
+ sitelink3 = {
+ 'xsi_type': 'SitelinkFeedItem',
+ 'sitelinkText': 'Wifi Available',
+ 'sitelinkFinalUrls': {'urls': ['http://www.example.com/mobile/wifi']},
+ # See https://developers.google.com/adwords/api/docs/appendix/platforms
+ # for device criteria IDs.
+ 'devicePreference': {'devicePreference': '30001'},
+ # Target this sitelink only when the ad is triggered by the keyword
+ # "free wifi."
+ 'keywordTargeting': {
+ 'text': 'free wifi',
+ 'matchType': 'BROAD'
+ }
+ }
+
+ # Show the happy hours link only during Mon - Fri 6PM to 9PM.
+ sitelink4 = {
+ 'xsi_type': 'SitelinkFeedItem',
+ 'sitelinkText': 'Happy hours',
+ 'sitelinkFinalUrls': {'urls': ['http://www.example.com/happyhours']},
+ 'scheduling': {
+ 'feedItemSchedules': [
+ {
+ 'dayOfWeek': day,
+ 'startHour': '18',
+ 'startMinute': 'ZERO',
+ 'endHour': '21',
+ 'endMinute': 'ZERO'
+ } for day in ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY',
+ 'FRIDAY']
+ ]
+ }
+ }
+
+ # Create your Campaign Extension Settings. This associates the sitelinks
+ # to your campaign.
+ campaign_extension_setting = {
+ 'campaignId': campaign_id,
+ 'extensionType': 'SITELINK',
+ 'extensionSetting': {
+ 'extensions': [sitelink1, sitelink2, sitelink3, sitelink4]
+ }
+ }
+
+ operation = {
+ 'operator': 'ADD',
+ 'operand': campaign_extension_setting
+ }
+
+ # Add the extensions.
+ response = campaign_extension_setting_service.mutate([operation])
+
+ if 'value' in response:
+ print('Extension setting with type "%s" was added to campaignId "%d".' %
+ (response['value'][0]['extensionType'],
+ response['value'][0]['campaignId']))
+ else:
+ raise errors.GoogleAdsError('No extension settings were added.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201809/extensions/add_site_links_using_feeds.py b/examples/adwords/v201809/extensions/add_site_links_using_feeds.py
new file mode 100755
index 00000000..3b3a004e
--- /dev/null
+++ b/examples/adwords/v201809/extensions/add_site_links_using_feeds.py
@@ -0,0 +1,303 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example adds a sitelinks feed and associates it with a campaign.
+
+To add sitelinks using the simpler ExtensionSetting services, see:
+add_sitelinks.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import re
+import uuid
+from googleads import adwords
+from googleads import errors
+
+# See the Placeholder reference page for a list of all the placeholder types and
+# fields.
+# https://developers.google.com/adwords/api/docs/appendix/placeholders.html
+PLACEHOLDER_SITELINKS = '1'
+PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = '1'
+PLACEHOLDER_FIELD_SITELINK_FINAL_URLS = '5'
+PLACEHOLDER_FIELD_LINE_2_TEXT = '3'
+PLACEHOLDER_FIELD_LINE_3_TEXT = '4'
+
+CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
+# Optional: Ad group to restrict targeting to.
+AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
+
+
+def RestrictFeedItemToGeoTarget(client, feed_item, location_id):
+ """Restrict a feed item to a geo target location.
+
+ Args:
+ client: An AdWordsClient instance.
+ feed_item: A FeedItem.
+ location_id: The Id of the location to restrict to.
+ """
+ # Retrieve the FeedItemTargetService
+ feed_item_target_service = client.GetService(
+ 'FeedItemTargetService', version='v201809')
+
+ # Optional: Restrict the first feed item to only serve with ads for the
+ # specified geo target.
+ criterion_target = {
+ 'xsi_type': 'FeedItemCriterionTarget',
+ 'feedId': feed_item['feedId'],
+ 'feedItemId': feed_item['feedItemId'],
+ # These IDs can be found in the documentation or retrieved with the
+ # LocationCriterionService.
+ 'criterion': {
+ 'xsi_type': 'Location',
+ 'id': location_id
+ }
+ }
+
+ operation = {'operator': 'ADD', 'operand': criterion_target}
+
+ response = feed_item_target_service.mutate([operation])
+ new_location_target = response['value'][0]
+ print('Feed item target for feed ID %d and feed item ID %d was created to '
+ 'restrict serving to location ID %d.' %
+ (new_location_target['feedId'],
+ new_location_target['feedItemId'],
+ new_location_target['criterion']['id']))
+
+
+def main(client, campaign_id, ad_group_id=None):
+ # Initialize appropriate service.
+ feed_service = client.GetService('FeedService', version='v201809')
+ feed_item_service = client.GetService('FeedItemService', version='v201809')
+ feed_item_target_service = client.GetService('FeedItemTargetService',
+ version='v201809')
+ feed_mapping_service = client.GetService(
+ 'FeedMappingService', version='v201809')
+ campaign_feed_service = client.GetService(
+ 'CampaignFeedService', version='v201809')
+
+ sitelinks_data = {}
+
+ # Create site links feed first.
+ site_links_feed = {
+ 'name': 'Feed For Site Links #%s' % uuid.uuid4(),
+ 'attributes': [
+ {'type': 'STRING', 'name': 'Link Text'},
+ {'type': 'URL_LIST', 'name': 'Link Final URLs'},
+ {'type': 'STRING', 'name': 'Line 2 Description'},
+ {'type': 'STRING', 'name': 'Line 3 Description'}
+ ]
+ }
+
+ response = feed_service.mutate([
+ {'operator': 'ADD', 'operand': site_links_feed}
+ ])
+
+ if 'value' in response:
+ feed = response['value'][0]
+ link_text_feed_attribute_id = feed['attributes'][0]['id']
+ final_url_feed_attribute_id = feed['attributes'][1]['id']
+ line_2_feed_attribute_id = feed['attributes'][2]['id']
+ line_3_feed_attribute_id = feed['attributes'][3]['id']
+ print('Feed with name "%s" and ID "%d" was added with' %
+ (feed['name'], feed['id']))
+ print('\tText attribute ID "%d" and Final URL attribute ID "%d".' %
+ (link_text_feed_attribute_id, final_url_feed_attribute_id))
+ print('\tLine 2 attribute ID "%d" and Line 3 attribute ID "%d".' %
+ (line_2_feed_attribute_id, line_3_feed_attribute_id))
+ sitelinks_data['feedId'] = feed['id']
+ sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id
+ sitelinks_data['finalUrlFeedId'] = final_url_feed_attribute_id
+ sitelinks_data['line2FeedId'] = line_2_feed_attribute_id
+ sitelinks_data['line3FeedId'] = line_3_feed_attribute_id
+ else:
+ raise errors.GoogleAdsError('No feeds were added.')
+
+ # Create site links feed items.
+ items_data = [
+ {'text': 'Home', 'finalUrls': 'http://www.example.com',
+ 'line2': 'Home line 2', 'line3': 'Home line 3'},
+ {'text': 'Stores', 'finalUrls': 'http://www.example.com/stores',
+ 'line2': 'Stores line 2', 'line3': 'Stores line 3'},
+ {'text': 'On Sale', 'finalUrls': 'http://www.example.com/sale',
+ 'line2': 'On Sale line 2', 'line3': 'On Sale line 3'},
+ {'text': 'Support', 'finalUrls': 'http://www.example.com/support',
+ 'line2': 'Support line 2', 'line3': 'Support line 3'},
+ {'text': 'Products', 'finalUrls': 'http://www.example.com/products',
+ 'line2': 'Products line 2', 'line3': 'Products line 3'},
+ {'text': 'About Us', 'finalUrls': 'http://www.example.com/about',
+ 'line2': 'About line 2', 'line3': 'About line 3', 'locationTarget': True}
+ ]
+
+ feed_items = []
+ for item in items_data:
+ feed_item = {
+ 'feedId': sitelinks_data['feedId'],
+ 'attributeValues': [
+ {
+ 'feedAttributeId': sitelinks_data['linkTextFeedId'],
+ 'stringValue': item['text']
+ },
+ {
+ 'feedAttributeId': sitelinks_data['finalUrlFeedId'],
+ 'stringValues': [item['finalUrls']]
+ },
+ {
+ 'feedAttributeId': sitelinks_data['line2FeedId'],
+ 'stringValue': item['line2']
+ },
+ {
+ 'feedAttributeId': sitelinks_data['line3FeedId'],
+ 'stringValue': item['line3']
+ }
+ ],
+ # Optional: use the 'startTime' and 'endTime' keys to specify the time
+ # period for the feed to deliver. The example below will make the feed
+ # start now and stop in one month.
+ # Make sure you specify the datetime in the customer's time zone. You
+ # can retrieve this from customer['dateTimeZone'].
+ #
+ # ['startTime']: datetime.datetime.now().strftime('%Y%m%d %H%M%S')
+ # ['endTime']: (datetime.datetime.now() +
+ # relativedelta(months=1)).strftime('%Y%m%d %H%M%S')
+ }
+
+ # Optional: Restrict targeting only to people physically within
+ # the location.
+ if 'locationTarget' in item:
+ item['geoTargetingRestriction'] = {
+ 'geoRestriction': 'LOCATION_OF_PRESENCE'
+ }
+
+ feed_items.append(feed_item)
+
+ feed_items_operations = [{'operator': 'ADD', 'operand': item} for item
+ in feed_items]
+
+ response = feed_item_service.mutate(feed_items_operations)
+ if 'value' in response:
+ sitelinks_data['feedItemIds'] = []
+ for feed_item in response['value']:
+ print('Feed item with ID %d was added.' % feed_item['feedItemId'])
+ sitelinks_data['feedItemIds'].append(feed_item['feedItemId'])
+ else:
+ raise errors.GoogleAdsError('No feed items were added.')
+
+ # Target the "aboutUs" sitelink to geographically target California.
+ # See https://developers.google.com/adwords/api/docs/appendix/geotargeting for
+ # location criteria for supported locations.
+ RestrictFeedItemToGeoTarget(client, response['value'][5], 21137)
+
+ # Create site links feed mapping.
+
+ feed_mapping = {
+ 'placeholderType': PLACEHOLDER_SITELINKS,
+ 'feedId': sitelinks_data['feedId'],
+ 'attributeFieldMappings': [
+ {
+ 'feedAttributeId': sitelinks_data['linkTextFeedId'],
+ 'fieldId': PLACEHOLDER_FIELD_SITELINK_LINK_TEXT
+ },
+ {
+ 'feedAttributeId': sitelinks_data['finalUrlFeedId'],
+ 'fieldId': PLACEHOLDER_FIELD_SITELINK_FINAL_URLS
+ },
+ {
+ 'feedAttributeId': sitelinks_data['line2FeedId'],
+ 'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT
+ },
+ {
+ 'feedAttributeId': sitelinks_data['line3FeedId'],
+ 'fieldId': PLACEHOLDER_FIELD_LINE_3_TEXT
+ }
+ ]
+ }
+
+ response = feed_mapping_service.mutate([
+ {'operator': 'ADD', 'operand': feed_mapping}
+ ])
+ if 'value' in response:
+ feed_mapping = response['value'][0]
+ print('Feed mapping with ID %d and placeholder type %s was saved for feed'
+ ' with ID %d.' %
+ (feed_mapping['feedMappingId'], feed_mapping['placeholderType'],
+ feed_mapping['feedId']))
+ else:
+ raise errors.GoogleAdsError('No feed mappings were added.')
+
+ # Construct a matching function that associates the sitelink feeditems to the
+ # campaign, and set the device preference to Mobile. For more details, see the
+ # matching function guide:
+ # https://developers.google.com/adwords/api/docs/guides/feed-matching-functions
+ matching_function_string = (
+ 'AND(IN(FEED_ITEM_ID, {%s}), EQUALS(CONTEXT.DEVICE, \'Mobile\'))' %
+ re.sub(r'\[|\]|L', '', str(sitelinks_data['feedItemIds'])))
+
+ campaign_feed = {
+ 'feedId': sitelinks_data['feedId'],
+ 'campaignId': campaign_id,
+ 'matchingFunction': {'functionString': matching_function_string},
+ # Specifying placeholder types on the CampaignFeed allows the same feed
+ # to be used for different placeholders in different Campaigns.
+ 'placeholderTypes': [PLACEHOLDER_SITELINKS]
+ }
+
+ response = campaign_feed_service.mutate([
+ {'operator': 'ADD', 'operand': campaign_feed}
+ ])
+ if 'value' in response:
+ campaign_feed = response['value'][0]
+ print('Campaign with ID %d was associated with feed with ID %d.' %
+ (campaign_feed['campaignId'], campaign_feed['feedId']))
+ else:
+ raise errors.GoogleAdsError('No campaign feeds were added.')
+
+ # Optional: Restrict the first feed item to only serve with ads for the
+ # specified ad group ID.
+ if ad_group_id:
+ feed_item_target = {
+ 'xsi_type': 'FeedItemAdGroupTarget',
+ 'feedId': sitelinks_data['feedId'],
+ 'feedItemId': sitelinks_data['feedItemIds'][0],
+ 'adGroupId': ad_group_id
+ }
+
+ operations = [{
+ 'operator': 'ADD',
+ 'operand': feed_item_target
+ }]
+
+ response = feed_item_target_service.mutate(operations)
+
+ if 'value' in response:
+ print('Feed item target for feed ID "%d" and feed item ID "%d" was '
+ 'created to restrict serving to ad group ID "%d".'
+ % (feed_item_target['feedId'], feed_item_target['feedItemId'],
+ feed_item_target['adGroupId']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ if AD_GROUP_ID == 'INSERT_AD_GROUP_ID_HERE':
+ main(adwords_client, CAMPAIGN_ID)
+ else:
+ main(adwords_client, CAMPAIGN_ID, ad_group_id=AD_GROUP_ID)
diff --git a/examples/adwords/v201809/migration/__init__.py b/examples/adwords/v201809/migration/__init__.py
new file mode 100644
index 00000000..09996b99
--- /dev/null
+++ b/examples/adwords/v201809/migration/__init__.py
@@ -0,0 +1,15 @@
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Migration examples."""
diff --git a/examples/adwords/v201809/migration/migrate_to_extension_settings.py b/examples/adwords/v201809/migration/migrate_to_extension_settings.py
new file mode 100755
index 00000000..59b87e48
--- /dev/null
+++ b/examples/adwords/v201809/migration/migrate_to_extension_settings.py
@@ -0,0 +1,526 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Migrates Feed-based sitelinks at Campaign level to use extension settings.
+
+To learn more about extensionsettings, see:
+https://developers.google.com/adwords/api/docs/guides/extension-settings.
+
+To learn more about migrating Feed-based extensions to extension settings, see:
+https://developers.google.com/adwords/api/docs/guides/migrate-to-extension-settings
+
+This code example doesn't migrate scheduling or feeditem-level campaign,
+adgroup, keyword, or geo targeting settings.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+from googleads import adwords
+
+
+# The placeholder type for sitelinks. For the list of all supported placeholder
+# types, see:
+# https://developers.google.com/adwords/api/docs/appendix/placeholders
+PLACEHOLDER_TYPE_SITELINKS = 1
+
+
+# The placeholder field IDs for sitelinks. For the list of all supported
+# placeholder types, see:
+# https://developers.google.com/adwords/api/docs/appendix/placeholders
+SITE_LINK_FIELDS = {
+ 'TEXT': 1,
+ 'URL': 2,
+ 'LINE2': 3,
+ 'LINE3': 4,
+ 'FINAL_URLS': 5,
+ 'FINAL_MOBILE_URLS': 6,
+ 'TRACKING_URL_TEMPLATE': 7
+}
+
+PAGE_SIZE = 500
+
+
+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 Campaign Feed.
+ feed_item_ids: the Ids of the feed items for which extension settings should
+ be created.
+ platform_restrictions: an optional Platform Restriction for the Feed items.
+ """
+ campaign_extension_setting_service = client.GetService(
+ 'CampaignExtensionSettingService', 'v201809')
+
+ extension_feed_items = [{
+ CreateSitelinkFeedItem(feed_items, feed_item_id)
+ } for feed_item_id in feed_item_ids]
+
+ extension_setting = {
+ 'extensions': extension_feed_items
+ }
+
+ if platform_restrictions:
+ extension_setting['platformRestrictions'] = platform_restrictions
+
+ campaign_extension_setting = {
+ 'campaignId': campaign_feed['campaignId'],
+ 'extensionType': 'SITELINK',
+ 'extensionSetting': extension_setting
+ }
+
+ operation = {
+ 'operand': campaign_extension_setting,
+ 'operator': 'ADD'
+ }
+
+ campaign_extension_setting_service.mutate([operation])
+
+
+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 = feed_items[feed_item_id]
+ site_link_feed_item = {
+ 'sitelinkText': site_link_from_feed['text'],
+ 'sitelinkLine2': site_link_from_feed['line2'],
+ 'sitelinkLine3': site_link_from_feed['line3'],
+ }
+
+ if 'finalUrls' in site_link_from_feed and site_link_from_feed['finalUrls']:
+ site_link_feed_item['sitelinkFinalUrls'] = {
+ 'urls': site_link_from_feed['finalUrls']
+ }
+
+ if 'finalMobileUrls' in site_link_from_feed:
+ site_link_feed_item['sitelinkFinalMobileUrls'] = {
+ 'urls': site_link_from_feed['finalMobileUrls']
+ }
+
+ site_link_feed_item['sitelinkTrackingUrlTemplate'] = (
+ site_link_from_feed['trackingUrlTemplate'])
+ else:
+ site_link_feed_item['sitelinkUrl'] = site_link_from_feed['url']
+
+ return site_link_feed_item
+
+
+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,
+ 'operator': 'REMOVE'
+ }
+
+ campaign_feed_service.mutate([operation])
+
+
+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
+
+ feed_item_service = client.GetService('FeedItemService', 'v201809')
+
+ operations = [{
+ 'operator': 'REMOVE',
+ 'operand': {
+ 'feedId': feed['id'],
+ 'feedItemId': feed_item_id
+ }
+ } for feed_item_id in feed_item_ids]
+
+ feed_item_service.mutate(operations)
+
+
+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_service = client.GetService('CampaignFeedService', 'v201809')
+
+ campaign_feeds = []
+ more_pages = True
+
+ selector = {
+ 'fields': ['CampaignId', 'MatchingFunction', 'PlaceholderTypes'],
+ 'predicates': [
+ {
+ 'field': 'Status',
+ 'operator': 'EQUALS',
+ 'values': ['ENABLED']
+ },
+ {
+ 'field': 'FeedId',
+ 'operator': 'EQUALS',
+ 'values': [feed['id']]
+ },
+ {
+ 'field': 'PlaceholderTypes',
+ 'operator': 'CONTAINS_ANY',
+ 'values': [placeholder_type]
+ }
+ ],
+ 'paging': {
+ 'startIndex': 0,
+ 'numberResults': PAGE_SIZE
+ }
+ }
+
+ while more_pages:
+ page = campaign_feed_service.get(selector)
+
+ if 'entries' in page:
+ campaign_feeds.extend(page['entries'])
+
+ selector['paging']['startIndex'] += PAGE_SIZE
+ more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries'])
+
+ return campaign_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', 'Attributes'],
+ 'predicates': [
+ {
+ 'field': 'Origin',
+ 'operator': 'EQUALS',
+ 'values': ['USER']
+ },
+ {
+ 'field': 'FeedStatus',
+ 'operator': 'EQUALS',
+ 'values': ['ENABLED']
+ }
+ ],
+ 'paging': {
+ 'startIndex': 0,
+ 'numberResults': PAGE_SIZE
+ }
+ }
+
+ while more_pages:
+ page = feed_service.get(selector)
+
+ if 'entries' in page:
+ feeds.extend(page['entries'])
+
+ selector['paging']['startIndex'] += PAGE_SIZE
+ more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries'])
+
+ return feeds
+
+
+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')
+
+ feed_items = []
+ more_pages = True
+
+ selector = {
+ 'fields': ['FeedItemId', 'AttributeValues'],
+ 'predicates': [
+ {
+ 'field': 'Status',
+ 'operator': 'EQUALS',
+ 'values': ['ENABLED']
+ },
+ {
+ 'field': 'FeedId',
+ 'operator': 'EQUALS',
+ 'values': [feed['id']]
+ }
+ ],
+ 'paging': {
+ 'startIndex': 0,
+ 'numberResults': PAGE_SIZE
+ }
+ }
+
+ while more_pages:
+ page = feed_item_service.get(selector)
+
+ if 'entries' in page:
+ feed_items.extend(page['entries'])
+
+ selector['paging']['startIndex'] += PAGE_SIZE
+ more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries'])
+
+ return feed_items
+
+
+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['matchingFunction']['lhsOperand']
+ except KeyError:
+ lhs_operand = None
+
+ if (lhs_operand and lhs_operand[0]['FunctionArgumentOperand.Type'] ==
+ 'RequestContextOperand'):
+ request_context_operand = lhs_operand[0]
+
+ if (request_context_operand['contextType'] == 'FEED_ITEM_ID' and
+ campaign_feed['matchingFunction']['operator'] == 'IN'):
+ for argument in campaign_feed['matchingFunction']['rhsOperand']:
+ if argument['xsi_type'] == 'ConstantOperand':
+ feed_item_ids.add(argument['longValue'])
+
+ return feed_item_ids
+
+
+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 Mapping.
+ """
+ feed_mapping_service = client.GetService('FeedMappingService', 'v201809')
+
+ attribute_mappings = {}
+ more_pages = True
+
+ selector = {
+ 'fields': ['FeedMappingId', 'AttributeFieldMappings'],
+ 'predicates': [
+ {
+ 'field': 'FeedId',
+ 'operator': 'EQUALS',
+ 'values': [feed['id']]
+ },
+ {
+ 'field': 'PlaceholderType',
+ 'operator': 'EQUALS',
+ 'values': [placeholder_type]
+ }
+ ],
+ 'paging': {
+ 'startIndex': 0,
+ 'numberResults': PAGE_SIZE
+ }
+ }
+
+ while more_pages:
+ page = feed_mapping_service.get(selector)
+
+ if 'entries' in page:
+ # Normally, a feed attribute is mapped only to one field. However, you may
+ # map it to more than one field if needed.
+ for feed_mapping in page['entries']:
+ for attribute_mapping in feed_mapping['attributeFieldMappings']:
+ # Since attribute mappings can have multiple values for each key,
+ # we use a list to store the values.
+ if attribute_mapping['feedAttributeId'] in attribute_mappings:
+ attribute_mappings[attribute_mapping['feedAttributeId']].append(
+ attribute_mapping['fieldId'])
+ else:
+ attribute_mappings[attribute_mapping['feedAttributeId']] = [
+ attribute_mapping['fieldId']]
+
+ selector['paging']['startIndex'] += PAGE_SIZE
+ more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries'])
+
+ return attribute_mappings
+
+
+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['matchingFunction']['operator'] == 'AND':
+ for argument in campaign_feed['matchingFunction']['lhsOperand']:
+ # Check if matchingFunction is EQUALS(CONTEXT.DEVICE, 'Mobile')
+ if argument['value']['operator'] == 'EQUALS':
+ request_context_operand = argument['value']['lhsOperand'][0]
+
+ if (request_context_operand and
+ request_context_operand == 'DEVICE_PLATFORM'):
+ # This needs to be capitalized for ExtensionSettingPlatform.
+ platform_restrictions = argument['value']['rhsOperand'][0].upper()
+
+ return platform_restrictions
+
+
+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 = GetFeedMapping(client, feed, PLACEHOLDER_TYPE_SITELINKS)
+
+ feed_items = {}
+
+ for feed_item in GetFeedItems(client, feed):
+ site_link_from_feed = {}
+
+ for attribute_value in feed_item['attributeValues']:
+ if attribute_value['feedAttributeId'] in feed_mappings:
+ for field_id in feed_mappings[attribute_value['feedAttributeId']]:
+ if field_id == SITE_LINK_FIELDS['TEXT']:
+ site_link_from_feed['text'] = attribute_value['stringValue']
+ elif field_id == SITE_LINK_FIELDS['URL']:
+ site_link_from_feed['url'] = attribute_value['stringValue']
+ elif field_id == SITE_LINK_FIELDS['FINAL_URLS']:
+ site_link_from_feed['finalUrls'] = attribute_value['stringValues']
+ elif field_id == SITE_LINK_FIELDS['FINAL_MOBILE_URLS']:
+ site_link_from_feed['finalMobileUrls'] = attribute_value[
+ 'stringValues']
+ elif field_id == SITE_LINK_FIELDS['TRACKING_URL_TEMPLATE']:
+ site_link_from_feed['trackingUrlTemplate'] = attribute_value[
+ 'stringValue']
+ elif field_id == SITE_LINK_FIELDS['LINE2']:
+ site_link_from_feed['line2'] = attribute_value['stringValue']
+ elif field_id == SITE_LINK_FIELDS['LINE3']:
+ site_link_from_feed['line3'] = attribute_value['stringValue']
+ else:
+ print('No applicable Site Link Field found for Id: %s' % field_id)
+
+ feed_items[feed_item['feedItemId']] = site_link_from_feed
+
+ return feed_items
+
+
+def main(client):
+ # Get all of the feeds for the current user.
+ feeds = GetFeeds(client)
+
+ for feed in feeds:
+ # Retrieve all the sitelinks from the current feed.
+ feed_items = GetSitelinksFromFeed(client, feed)
+
+ # Get all the instances where a sitelink from this feed has been added to a
+ # campaign.
+ campaign_feeds = GetCampaignFeeds(client, feed, PLACEHOLDER_TYPE_SITELINKS)
+
+ all_feed_items_to_delete = []
+ for campaign_feed in campaign_feeds:
+ # Retrieve the sitelinks that have been associated with this Campaign.
+ feed_item_ids = GetFeedItemIdsForCampaign(campaign_feed)
+
+ if feed_item_ids == 0:
+ print('Migration skipped for campaign feed with campaign ID %d '
+ 'and feed ID %d because no mapped feed item IDs were found in '
+ 'the campaign feed\'s matching function.'
+ % (campaign_feed['campaign_id'], campaign_feed['feed_id']))
+ continue
+
+ platform_restrictions = GetPlatformRestrictions(campaign_feed)
+
+ # Delete the campaign feed that associates the sitelinks from the feed to
+ # the Campaign.
+ DeleteCampaignFeed(client, campaign_feed)
+
+ # Create extension settings instead of sitelinks.
+ CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids,
+ platform_restrictions)
+
+ # Mark the sitelinks from the feed for deletion.
+ all_feed_items_to_delete.extend(feed_item_ids)
+
+ # Delete all the sitelinks from the feed.
+ DeleteOldFeedItems(client, all_feed_items_to_delete, feed)
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client)
diff --git a/examples/adwords/v201809/misc/__init__.py b/examples/adwords/v201809/misc/__init__.py
new file mode 100644
index 00000000..1c53bcd3
--- /dev/null
+++ b/examples/adwords/v201809/misc/__init__.py
@@ -0,0 +1,15 @@
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Miscellaneous examples."""
diff --git a/examples/adwords/v201809/misc/get_all_image_assets.py b/examples/adwords/v201809/misc/get_all_image_assets.py
new file mode 100755
index 00000000..32881373
--- /dev/null
+++ b/examples/adwords/v201809/misc/get_all_image_assets.py
@@ -0,0 +1,78 @@
+#!/usr/bin/env python
+#
+# Copyright 2018 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all image assets.
+
+To upload an image asset, run upload_image_asset.py
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from googleads import adwords
+
+
+PAGE_SIZE = 500
+
+
+def main(client):
+ # Initialize appropriate service.
+ asset_service = client.GetService('AssetService', version='v201809')
+
+ # Construct selector and get all images.
+ offset = 0
+ selector = {
+ 'fields': ['AssetName', 'AssetStatus', 'ImageFileSize', 'ImageWidth',
+ 'ImageHeight', 'ImageFullSizeUrl'],
+ 'predicates': [{
+ 'field': 'AssetSubtype',
+ 'operator': 'IN',
+ 'values': ['IMAGE']
+ }],
+ 'paging': {
+ 'startIndex': str(offset),
+ 'numberResults': str(PAGE_SIZE)
+ }
+ }
+ more_pages = True
+ while more_pages:
+ page = asset_service.get(selector)
+
+ # Display results.
+ if 'entries' in page:
+ for image in page['entries']:
+ print('Image asset with id %s, name "%s", and status %s was found.\n'
+ '\tSize is %sx%s and asset URL is %s.' %
+ (image['assetId'], image['assetName'], image['assetStatus'],
+ image['fullSizeInfo']['imageWidth'],
+ image['fullSizeInfo']['imageHeight'],
+ image['fullSizeInfo']['imageUrl']))
+ else:
+ print('No images/videos were found.')
+ offset += PAGE_SIZE
+ selector['paging']['startIndex'] = str(offset)
+ more_pages = offset < int(page['totalNumEntries'])
+
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client)
diff --git a/examples/adwords/v201809/misc/get_all_images_and_videos.py b/examples/adwords/v201809/misc/get_all_images_and_videos.py
new file mode 100755
index 00000000..dcafecb8
--- /dev/null
+++ b/examples/adwords/v201809/misc/get_all_images_and_videos.py
@@ -0,0 +1,85 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all images and videos.
+
+To upload an image, run upload_image.py. Use the Google Ads website to upload
+new videos.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from googleads import adwords
+
+
+PAGE_SIZE = 500
+
+
+def main(client):
+ # Initialize appropriate service.
+ media_service = client.GetService('MediaService', version='v201809')
+
+ # Construct selector and get all images.
+ offset = 0
+ selector = {
+ 'fields': ['MediaId', 'Type', 'Width', 'Height', 'MimeType'],
+ 'predicates': [{
+ 'field': 'Type',
+ 'operator': 'IN',
+ 'values': ['IMAGE', 'VIDEO']
+ }],
+ 'paging': {
+ 'startIndex': str(offset),
+ 'numberResults': str(PAGE_SIZE)
+ }
+ }
+ more_pages = True
+ while more_pages:
+ page = media_service.get(selector)
+
+ # Display results.
+ if 'entries' in page:
+ for image in page['entries']:
+ try:
+ dimensions = dict([(entry['key'], entry['value'])
+ for entry in image['dimensions']])
+ except AttributeError:
+ dimensions = {'FULL': {'height': 0, 'width': 0}}
+ if image['type'] == 'IMAGE':
+ print('%s with id "%s", dimensions \'%sx%s\', and MimeType "%s"'
+ ' was found.' % (image['type'], image['mediaId'],
+ dimensions['FULL']['height'],
+ dimensions['FULL']['width'],
+ image['mimeType']))
+ elif image['type'] == 'VIDEO':
+ print('%s with id "%s" was found.' % (image['type'],
+ image['mediaId']))
+ else:
+ print('No images/videos were found.')
+ offset += PAGE_SIZE
+ selector['paging']['startIndex'] = str(offset)
+ more_pages = offset < int(page['totalNumEntries'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client)
diff --git a/examples/adwords/v201809/misc/upload_image.py b/examples/adwords/v201809/misc/upload_image.py
new file mode 100755
index 00000000..efa8991e
--- /dev/null
+++ b/examples/adwords/v201809/misc/upload_image.py
@@ -0,0 +1,65 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example uploads an image.
+
+To get images, run get_all_images.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+from googleads import adwords
+
+
+IMAGE_FILENAME = 'INSERT_IMAGE_PATH_HERE'
+
+
+def main(client, image_filename):
+ # Initialize appropriate service.
+ media_service = client.GetService('MediaService', version='v201809')
+
+ with open(image_filename, 'rb') as image_handle:
+ image_data = image_handle.read().decode('utf-8')
+
+ # Construct media and upload image.
+ media = [{
+ 'xsi_type': 'Image',
+ 'data': image_data,
+ 'type': 'IMAGE'
+ }]
+ media = media_service.upload(media)[0]
+
+ # Display results.
+ if media:
+ dimensions = dict([(entry['key'], entry['value'])
+ for entry in media['dimensions']])
+ print('Image with id "%s", dimensions \'%sx%s\', and MimeType "%s" was'
+ ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'],
+ dimensions['FULL']['width'], media['mimeType']))
+ else:
+ print('No images were uploaded.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, IMAGE_FILENAME)
diff --git a/examples/adwords/v201809/misc/upload_image_asset.py b/examples/adwords/v201809/misc/upload_image_asset.py
new file mode 100755
index 00000000..f3bd0b2f
--- /dev/null
+++ b/examples/adwords/v201809/misc/upload_image_asset.py
@@ -0,0 +1,71 @@
+#!/usr/bin/env python
+#
+# Copyright 2018 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example uploads an image asset.
+
+To get image assets, run get_all_image_assets.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from googleads import adwords
+import requests
+
+
+def main(client):
+ # Initialize appropriate service.
+ asset_service = client.GetService('AssetService', version='v201809')
+
+ image_request = requests.get('https://goo.gl/3b9Wfh')
+ image_data = image_request.content
+
+ # Construct media and upload image asset.
+ image_asset = {
+ 'xsi_type': 'ImageAsset',
+ # Optional: Provide a unique friendly name to identify your asset. If you
+ # specify the assetName field, then both the asset name and the image
+ # being uploaded should be unique, and should not match another ACTIVE
+ # asset in this customer account.
+ # 'assetName': 'Jupiter Trip #' + str(uuid.uuid4())[:8],
+ 'imageData': image_data,
+
+ }
+
+ operation = {'operator': 'ADD', 'operand': image_asset}
+
+ asset = asset_service.mutate([operation])['value'][0]
+
+ # Display results.
+ if asset:
+ print('Image asset with id %s, name "%s", and status %s was created.\n'
+ '\tSize is %sx%s and asset URL is %s.' %
+ (asset['assetId'], asset['assetName'], asset['assetStatus'],
+ asset['fullSizeInfo']['imageWidth'],
+ asset['fullSizeInfo']['imageHeight'],
+ asset['fullSizeInfo']['imageUrl']))
+ else:
+ print('No images were uploaded.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client)
diff --git a/examples/adwords/v201809/misc/upload_media_bundle.py b/examples/adwords/v201809/misc/upload_media_bundle.py
new file mode 100755
index 00000000..e0bb8fe3
--- /dev/null
+++ b/examples/adwords/v201809/misc/upload_media_bundle.py
@@ -0,0 +1,59 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example uploads an HTML5 zip file.
+
+"""
+
+from urllib.request import urlopen
+
+from googleads import adwords
+
+
+def main(client):
+ # Initialize appropriate service.
+ media_service = client.GetService('MediaService', version='v201809')
+ # Create HTML5 media.
+ html5_zip = GetHTML5ZipFromUrl('https://goo.gl/9Y7qI2')
+ # Create a media bundle containing the zip file with all the HTML5 components.
+ media = [{
+ 'xsi_type': 'MediaBundle',
+ 'data': html5_zip,
+ 'type': 'MEDIA_BUNDLE'
+ }]
+ # Upload HTML5 zip.
+ response = media_service.upload(media)
+
+ if response:
+ for media in response:
+ print(
+ 'HTML5 media with ID %d, dimensions %dx%d, and MIME type "%s" '
+ 'uploaded successfully.' %
+ (media['mediaId'], media['dimensions'][0]['value']['width'],
+ media['dimensions'][0]['value']['height'], media['mimeType']))
+
+
+def GetHTML5ZipFromUrl(url):
+ """Retrieve zip file from the given URL."""
+ response = urlopen(url)
+ # Note: The utf-8 decode is for 2to3 Python 3 compatibility.
+ return response.read().decode('utf-8')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+ main(adwords_client)
diff --git a/examples/adwords/v201809/optimization/__init__.py b/examples/adwords/v201809/optimization/__init__.py
new file mode 100644
index 00000000..34ee7f4b
--- /dev/null
+++ b/examples/adwords/v201809/optimization/__init__.py
@@ -0,0 +1,15 @@
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Optimization examples."""
diff --git a/examples/adwords/v201809/optimization/estimate_keyword_traffic.py b/examples/adwords/v201809/optimization/estimate_keyword_traffic.py
new file mode 100755
index 00000000..81cff0cb
--- /dev/null
+++ b/examples/adwords/v201809/optimization/estimate_keyword_traffic.py
@@ -0,0 +1,182 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example retrieves keyword traffic estimates.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from googleads import adwords
+
+
+def main(client):
+ # Initialize appropriate service.
+ traffic_estimator_service = client.GetService(
+ 'TrafficEstimatorService', version='v201809')
+
+ # Construct selector object and retrieve traffic estimates.
+ keywords = [
+ {'text': 'mars cruise', 'matchType': 'BROAD'},
+ {'text': 'cheap cruise', 'matchType': 'PHRASE'},
+ {'text': 'cruise', 'matchType': 'EXACT'}
+ ]
+ negative_keywords = [
+ {'text': 'moon walk', 'matchType': 'BROAD'}
+ ]
+ keyword_estimate_requests = []
+ for keyword in keywords:
+ keyword_estimate_requests.append({
+ 'keyword': {
+ 'xsi_type': 'Keyword',
+ 'matchType': keyword['matchType'],
+ 'text': keyword['text']
+ }
+ })
+
+ for keyword in negative_keywords:
+ keyword_estimate_requests.append({
+ 'keyword': {
+ 'xsi_type': 'Keyword',
+ 'matchType': keyword['matchType'],
+ 'text': keyword['text']
+ },
+ 'isNegative': 'true'
+ })
+
+ # Create ad group estimate requests.
+ adgroup_estimate_requests = [{
+ 'keywordEstimateRequests': keyword_estimate_requests,
+ 'maxCpc': {
+ 'xsi_type': 'Money',
+ 'microAmount': '1000000'
+ }
+ }]
+
+ # Create campaign estimate requests.
+ campaign_estimate_requests = [{
+ 'adGroupEstimateRequests': adgroup_estimate_requests,
+ 'criteria': [
+ {
+ 'xsi_type': 'Location',
+ 'id': '2840' # United States.
+ },
+ {
+ 'xsi_type': 'Language',
+ 'id': '1000' # English.
+ }
+ ],
+ }]
+
+ # Create the selector.
+ selector = {
+ 'campaignEstimateRequests': campaign_estimate_requests,
+ }
+
+ # Optional: Request a list of campaign-level estimates segmented by
+ # platform.
+ selector['platformEstimateRequested'] = True
+
+ # Get traffic estimates.
+ estimates = traffic_estimator_service.get(selector)
+
+ campaign_estimate = estimates['campaignEstimates'][0]
+
+ # Display the campaign level estimates segmented by platform.
+ if 'platformEstimates' in campaign_estimate:
+ platform_template = ('Results for the platform with ID: "%d" and name: '
+ '"%s".')
+ for platform_estimate in campaign_estimate['platformEstimates']:
+ platform = platform_estimate['platform']
+ DisplayEstimate(platform_template % (platform['id'],
+ platform['platformName']),
+ platform_estimate['minEstimate'],
+ platform_estimate['maxEstimate'])
+
+ # Display the keyword estimates.
+ if 'adGroupEstimates' in campaign_estimate:
+ ad_group_estimate = campaign_estimate['adGroupEstimates'][0]
+ if 'keywordEstimates' in ad_group_estimate:
+ keyword_estimates = ad_group_estimate['keywordEstimates']
+ keyword_template = ('Results for the keyword with text "%s" and match '
+ 'type "%s":')
+
+ keyword_estimates_and_requests = zip(keyword_estimates,
+ keyword_estimate_requests)
+
+ for keyword_tuple in keyword_estimates_and_requests:
+ if keyword_tuple[1].get('isNegative', False):
+ continue
+ keyword = keyword_tuple[1]['keyword']
+ keyword_estimate = keyword_tuple[0]
+ DisplayEstimate(keyword_template % (keyword['text'],
+ keyword['matchType']),
+ keyword_estimate['min'], keyword_estimate['max'])
+
+
+def _CalculateMean(min_est, max_est):
+ if min_est and max_est:
+ return (float(min_est) + float(max_est)) / 2.0
+ else:
+ return None
+
+
+def _FormatMean(mean):
+ if mean:
+ return '%.2f' % mean
+ else:
+ return 'N/A'
+
+
+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: zeep.objects.StatsEstimate containing a minimum estimate from the
+ TrafficEstimatorService response.
+ max_estimate: zeep.objects.StatsEstimate containing a maximum estimate from the
+ TrafficEstimatorService response.
+ """
+ # Find the mean of the min and max values.
+ mean_avg_cpc = (_CalculateMean(min_estimate['averageCpc']['microAmount'],
+ max_estimate['averageCpc']['microAmount'])
+ if 'averageCpc' in min_estimate
+ and min_estimate['averageCpc'] else None)
+ mean_avg_pos = (_CalculateMean(min_estimate['averagePosition'],
+ max_estimate['averagePosition'])
+ if 'averagePosition' in min_estimate
+ and min_estimate['averagePosition'] else None)
+ mean_clicks = _CalculateMean(min_estimate['clicksPerDay'],
+ max_estimate['clicksPerDay'])
+ mean_total_cost = _CalculateMean(min_estimate['totalCost']['microAmount'],
+ max_estimate['totalCost']['microAmount'])
+
+ print(message)
+ print(' Estimated average CPC: %s' % _FormatMean(mean_avg_cpc))
+ print(' Estimated ad position: %s' % _FormatMean(mean_avg_pos))
+ print(' Estimated daily clicks: %s' % _FormatMean(mean_clicks))
+ print(' Estimated daily cost: %s' % _FormatMean(mean_total_cost))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client)
diff --git a/examples/adwords/v201809/optimization/get_campaign_criterion_bid_modifier_simulations.py b/examples/adwords/v201809/optimization/get_campaign_criterion_bid_modifier_simulations.py
new file mode 100755
index 00000000..b8ae8328
--- /dev/null
+++ b/examples/adwords/v201809/optimization/get_campaign_criterion_bid_modifier_simulations.py
@@ -0,0 +1,97 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Gets all available campaign criterion bid modifier landscapes for a campaign.
+
+To get campaigns, run basic_operations/get_campaigns.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from googleads import adwords
+
+
+CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
+PAGE_SIZE = 100
+
+
+def main(client, campaign_id):
+ # Initialize appropriate service.
+ data_service = client.GetService('DataService', version='v201809')
+
+ # Get all the campaigns for this account.
+ selector = {
+ 'fields': ['CampaignId', 'CriterionId', 'StartDate', 'EndDate',
+ 'BidModifier', 'LocalClicks', 'LocalCost', 'LocalImpressions',
+ 'TotalLocalClicks', 'TotalLocalCost', 'TotalLocalImpressions',
+ 'RequiredBudget'],
+ 'paging': {
+ 'startIndex': 0,
+ 'numberResults': PAGE_SIZE
+ },
+ 'predicates': [{
+ 'field': 'CampaignId', 'operator': 'IN', 'values': [campaign_id]
+ }]
+ }
+
+ # Set initial values.
+ offset = 0
+ more_pages = True
+
+ while more_pages is True:
+ num_landscape_points = 0
+ page = data_service.getCampaignCriterionBidLandscape(selector)
+
+ # Display results.
+ if 'entries' in page:
+ for bid_modifier_landscape in page['entries']:
+ num_landscape_points = 0
+ print('Found campaign-level criterion bid modifier landscapes for '
+ 'criterion with ID "%d", start date "%s", end date "%s", and '
+ 'landscape points:') % (bid_modifier_landscape['criterionId'],
+ bid_modifier_landscape['startDate'],
+ bid_modifier_landscape['endDate'])
+ for landscape_point in bid_modifier_landscape['landscapePoints']:
+ num_landscape_points += 1
+ print('\tbid modifier: %f, clicks: %d, cost: %d, impressions: %d, '
+ 'total clicks: %d, total cost: %d, total impressions: %d, '
+ 'and required budget: %f') % (
+ landscape_point['bidModifier'], landscape_point['clicks'],
+ landscape_point['cost']['microAmount'],
+ landscape_point['impressions'],
+ landscape_point['totalLocalClicks'],
+ landscape_point['totalLocalCost']['microAmount'],
+ landscape_point['totalLocalImpressions'],
+ landscape_point['requiredBudget']['microAmount'])
+ else:
+ print('No bid modifier landscapes found.')
+
+ # Need to increment by the total # of landscape points within the page,
+ # NOT the number of entries (bid landscapes) in the page.
+ offset += num_landscape_points
+ selector['paging']['startIndex'] = str(offset)
+ more_pages = num_landscape_points >= PAGE_SIZE
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201809/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201809/optimization/get_keyword_bid_simulations.py
new file mode 100755
index 00000000..a61f7e97
--- /dev/null
+++ b/examples/adwords/v201809/optimization/get_keyword_bid_simulations.py
@@ -0,0 +1,85 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets a bid landscape for an ad group and a criterion.
+
+To get ad groups, run get_ad_groups.py. To get criteria, run get_keywords.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from googleads import adwords
+
+
+AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
+CRITERION_ID = 'INSERT_CRITERION_ID_HERE'
+PAGE_SIZE = 100
+
+
+def main(client, ad_group_id, criterion_id):
+ # Initialize appropriate service.
+ data_service = client.GetService('DataService', version='v201809')
+
+ # Create a query to select all keyword bid simulations for the specified
+ # ad group and criterion ID.
+ query = (adwords.ServiceQueryBuilder()
+ .Select(
+ 'AdGroupId', 'CriterionId', 'StartDate', 'EndDate', 'Bid',
+ 'BiddableConversions', 'BiddableConversionsValue', 'LocalClicks',
+ 'LocalCost', 'LocalImpressions')
+ .Where('AdGroupId').EqualTo(ad_group_id)
+ .Where('CriterionId').EqualTo(criterion_id)
+ .Limit(0, PAGE_SIZE)
+ .Build())
+
+ while True:
+ page = data_service.queryCriterionBidLandscape(query)
+
+ if page and 'entries' in page:
+ entries = page['entries']
+ print('Bid landscape(s) retrieved: %d.' % len(entries))
+
+ for bid_landscape in entries:
+ print('Retrieved keyword bid landscape with ad group ID "%d", '
+ 'keyword ID "%d", start date "%s", end date "%s", '
+ 'with landscape points:' % (
+ bid_landscape['adGroupId'], bid_landscape['criterionId'],
+ bid_landscape['startDate'], bid_landscape['endDate']))
+ for bid_landscape_point in bid_landscape['landscapePoints']:
+ print(' bid: %s => clicks: %s, cost: %s, impressions: %s, '
+ 'biddable conversions: %.2f, '
+ 'biddable conversions value: %.2f'
+ % (bid_landscape_point['bid']['microAmount'],
+ bid_landscape_point['clicks'],
+ bid_landscape_point['cost']['microAmount'],
+ bid_landscape_point['impressions'],
+ bid_landscape_point['biddableConversions'],
+ bid_landscape_point['biddableConversionsValue']))
+
+ if not query.HasNext(page):
+ break
+ query.NextPage()
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, AD_GROUP_ID, CRITERION_ID)
diff --git a/examples/adwords/v201809/optimization/get_keyword_ideas.py b/examples/adwords/v201809/optimization/get_keyword_ideas.py
new file mode 100755
index 00000000..a2294a3b
--- /dev/null
+++ b/examples/adwords/v201809/optimization/get_keyword_ideas.py
@@ -0,0 +1,113 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example retrieves keywords that are related to a given keyword.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from googleads import adwords
+
+
+# Optional AdGroup ID used to set a SearchAdGroupIdSearchParameter.
+AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
+PAGE_SIZE = 100
+
+
+def main(client, ad_group_id=None):
+ # Initialize appropriate service.
+ targeting_idea_service = client.GetService(
+ 'TargetingIdeaService', version='v201809')
+
+ # Construct selector object and retrieve related keywords.
+ selector = {
+ 'ideaType': 'KEYWORD',
+ 'requestType': 'IDEAS'
+ }
+
+ selector['requestedAttributeTypes'] = [
+ 'KEYWORD_TEXT', 'SEARCH_VOLUME', 'CATEGORY_PRODUCTS_AND_SERVICES']
+
+ offset = 0
+ selector['paging'] = {
+ 'startIndex': str(offset),
+ 'numberResults': str(PAGE_SIZE)
+ }
+
+ selector['searchParameters'] = [{
+ 'xsi_type': 'RelatedToQuerySearchParameter',
+ 'queries': ['space cruise']
+ }]
+
+ # Language setting (optional).
+ selector['searchParameters'].append({
+ # The ID can be found in the documentation:
+ # https://developers.google.com/adwords/api/docs/appendix/languagecodes
+ 'xsi_type': 'LanguageSearchParameter',
+ 'languages': [{'id': '1000'}]
+ })
+
+ # Network search parameter (optional)
+ selector['searchParameters'].append({
+ 'xsi_type': 'NetworkSearchParameter',
+ 'networkSetting': {
+ 'targetGoogleSearch': True,
+ 'targetSearchNetwork': False,
+ 'targetContentNetwork': False,
+ 'targetPartnerSearchNetwork': False
+ }
+ })
+
+ # Use an existing ad group to generate ideas (optional)
+ if ad_group_id is not None:
+ selector['searchParameters'].append({
+ 'xsi_type': 'SeedAdGroupIdSearchParameter',
+ 'adGroupId': ad_group_id
+ })
+
+ more_pages = True
+ while more_pages:
+ page = targeting_idea_service.get(selector)
+
+ # Display results.
+ if 'entries' in page:
+ for result in page['entries']:
+ attributes = {}
+ for attribute in result['data']:
+ attributes[attribute['key']] = getattr(
+ attribute['value'], 'value', '0')
+ print('Keyword with "%s" text and average monthly search volume '
+ '"%s" was found with Products and Services categories: %s.'
+ % (attributes['KEYWORD_TEXT'],
+ attributes['SEARCH_VOLUME'],
+ attributes['CATEGORY_PRODUCTS_AND_SERVICES']))
+ print
+ else:
+ print('No related keywords were found.')
+ offset += PAGE_SIZE
+ selector['paging']['startIndex'] = str(offset)
+ more_pages = offset < int(page['totalNumEntries'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, int(AD_GROUP_ID) if AD_GROUP_ID.isdigit() else None)
diff --git a/examples/adwords/v201809/remarketing/__init__.py b/examples/adwords/v201809/remarketing/__init__.py
new file mode 100644
index 00000000..c4912fc8
--- /dev/null
+++ b/examples/adwords/v201809/remarketing/__init__.py
@@ -0,0 +1,15 @@
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Remarketing examples."""
diff --git a/examples/adwords/v201809/remarketing/add_audience.py b/examples/adwords/v201809/remarketing/add_audience.py
new file mode 100755
index 00000000..df986e15
--- /dev/null
+++ b/examples/adwords/v201809/remarketing/add_audience.py
@@ -0,0 +1,104 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example adds a remarketing user list (a.k.a. audience).
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import uuid
+from googleads import adwords
+
+
+PAGE_SIZE = 100
+
+
+def main(client):
+ # Initialize appropriate service.
+ user_list_service = client.GetService(
+ 'AdwordsUserListService', version='v201809')
+ conversion_tracker_service = client.GetService(
+ 'ConversionTrackerService', version='v201809')
+
+ # Construct operations and add a user list.
+ operations = [
+ {
+ 'operator': 'ADD',
+ 'operand': {
+ 'xsi_type': 'BasicUserList',
+ 'name': 'Mars cruise customers #%s' % uuid.uuid4(),
+ 'description': 'A list of mars cruise customers in the last year',
+ 'membershipLifeSpan': '365',
+ 'conversionTypes': [
+ {
+ 'name': ('Mars cruise customers #%s'
+ % uuid.uuid4())
+ }
+ ],
+ # Optional field.
+ 'status': 'OPEN',
+ }
+ }
+ ]
+ user_list_result = user_list_service.mutate(operations)
+
+ # Capture the ID(s) of the conversion.
+ if 'value' in user_list_result:
+ conversion_ids = []
+ for user_list in user_list_result['value']:
+ if user_list['conversionTypes']:
+ for conversion_type in user_list['conversionTypes']:
+ conversion_ids.append(conversion_type['id'])
+
+ # Create query.
+ query = (adwords.ServiceQueryBuilder()
+ .Select('Id', 'GoogleGlobalSiteTag', 'GoogleEventSnippet')
+ .Where('Id').In(*conversion_ids)
+ .Limit(0, PAGE_SIZE)
+ .Build())
+
+ conversions_map = {}
+
+ # Get all conversion trackers.
+ for page in query.Pager(conversion_tracker_service):
+ if 'entries' in page:
+ for conversion_tracker in page['entries']:
+ conversions_map[conversion_tracker['id']] = conversion_tracker
+
+ for user_list in user_list_result['value']:
+ print('User list with name "%s" and ID "%s" was added.'
+ % (user_list['name'], user_list['id']))
+ if user_list['conversionTypes']:
+ for conversion_type in user_list['conversionTypes']:
+ conversion_tracker = conversions_map[conversion_type['id']]
+ print('Google global site tag:\n%s\n\n'
+ % conversion_tracker['googleGlobalSiteTag'])
+ print('Google event snippet:\n%s\n\n'
+ % conversion_tracker['googleEventSnippet'])
+ else:
+ print('No user lists were added.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client)
diff --git a/examples/adwords/v201809/remarketing/add_conversion_tracker.py b/examples/adwords/v201809/remarketing/add_conversion_tracker.py
new file mode 100755
index 00000000..5dd177b0
--- /dev/null
+++ b/examples/adwords/v201809/remarketing/add_conversion_tracker.py
@@ -0,0 +1,66 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the 'License');
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an 'AS IS' BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example adds an AdWords conversion.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import uuid
+from googleads import adwords
+
+
+def main(client):
+ # Initialize appropriate service.
+ conversion_tracker_service = client.GetService(
+ 'ConversionTrackerService', version='v201809')
+
+ # Construct operations and add conversion_tracker.
+ operations = [
+ {
+ 'operator': 'ADD',
+ 'operand': {
+ 'xsi_type': 'AdWordsConversionTracker',
+ 'name': 'Mars cruise customers #%s' % uuid.uuid4(),
+ 'category': 'DEFAULT',
+ # Optional fields.
+ 'status': 'ENABLED',
+ 'viewthroughLookbackWindow': '15',
+ 'defaultRevenueValue': '23.41',
+ 'alwaysUseDefaultRevenueValue': 'true'
+ }
+ }
+ ]
+ conversion_trackers = conversion_tracker_service.mutate(operations)
+
+ # Display results.
+ for conversion_tracker in conversion_trackers['value']:
+ print('Conversion tracker with id "%s", name "%s", status "%s" '
+ 'and category "%s" was added.\n' %
+ (conversion_tracker['id'], conversion_tracker['name'],
+ conversion_tracker['status'], conversion_tracker['category']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client)
diff --git a/examples/adwords/v201809/remarketing/add_conversion_trackers.py b/examples/adwords/v201809/remarketing/add_conversion_trackers.py
new file mode 100755
index 00000000..892de60d
--- /dev/null
+++ b/examples/adwords/v201809/remarketing/add_conversion_trackers.py
@@ -0,0 +1,101 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the 'License');
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an 'AS IS' BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example adds AdWords conversion trackers.
+
+Adds an AdWords conversion tracker and an upload conversion tracker.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import uuid
+from googleads import adwords
+
+
+def main(client):
+ # Initialize appropriate service.
+ conversion_tracker_service = client.GetService(
+ 'ConversionTrackerService', version='v201809')
+
+ # Create an AdWords conversion tracker.
+ adwords_conversion_tracker = {
+ 'xsi_type': 'AdWordsConversionTracker',
+ 'name': 'Earth to Mars Cruises Conversion #%s' % uuid.uuid4(),
+ 'category': 'DEFAULT',
+ # Optional fields.
+ 'status': 'ENABLED',
+ 'viewthroughLookbackWindow': '15',
+ 'defaultRevenueValue': '23.41',
+ 'alwaysUseDefaultRevenueValue': 'true'
+ }
+
+ upload_conversion = {
+ 'xsi_type': 'UploadConversion',
+ 'name': 'Upload Conversion #%s' % uuid.uuid4(),
+ # Optional fields.
+ # Set an appropriate category. This will be set to DEFAULT if not
+ # specified.
+ 'category': 'LEAD',
+ 'viewthroughLookbackWindow': '30',
+ 'ctcLookbackWindow': '90',
+ # Set the default currency code to use for conversions that do
+ # not specify a conversion currency. This must be an ISO 4217 3-character
+ # code such as "EUR" or "USD".
+ # If this field is not set, AdWords will use the account's currency.
+ 'defaultRevenueCurrencyCode': 'EUR',
+ # Set the default revenue value to use for conversions that do not specify
+ # a converison value. Note that this value should NOT be in micros.
+ 'defaultRevenueValue': '2.50',
+ # To upload fractional conversion credits, mark the upload conversion as
+ # externally attributed. To learn more about importing externally
+ # attributed conversions, see:
+ # https://developers.google.com/adwords/api/docs/guides/conversion-tracking#importing_externally_attributed_conversions
+ # 'isExternallyAttributed': 'true'
+ }
+
+ # Construct operations.
+ operations = [{
+ 'operator': 'ADD',
+ 'operand': conversion_tracker
+ } for conversion_tracker in [adwords_conversion_tracker, upload_conversion]]
+
+ # Add the conversions.
+ conversion_trackers = conversion_tracker_service.mutate(operations)
+
+ # Display results.
+ for conversion_tracker in conversion_trackers['value']:
+ print('Conversion with ID "%d", name "%s", status "%s", and category '
+ '"%s" was added.'
+ % (conversion_tracker['id'], conversion_tracker['name'],
+ conversion_tracker['status'], conversion_tracker['category']))
+ if (conversion_tracker['ConversionTracker.Type']
+ == 'AdWordsConversionTracker'):
+ print('Google global site tag:\n%s\n\n'
+ % conversion_tracker['googleGlobalSiteTag'])
+ print('Google event snippet:\n%s\n\n'
+ % conversion_tracker['googleEventSnippet'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client)
diff --git a/examples/adwords/v201809/remarketing/add_crm_based_user_list.py b/examples/adwords/v201809/remarketing/add_crm_based_user_list.py
new file mode 100755
index 00000000..69ff41ae
--- /dev/null
+++ b/examples/adwords/v201809/remarketing/add_crm_based_user_list.py
@@ -0,0 +1,104 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+"""Adds a user list and populates it with hashed email addresses.
+
+Note: It may take several hours for the list to be populated with members. Email
+addresses must be associated with a Google account. For privacy purposes, the
+user list size will show as zero until the list has at least 1000 members. After
+that, the size will be rounded to the two most significant digits.
+"""
+
+
+import hashlib
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import adwords
+
+
+def main(client):
+ # Initialize appropriate services.
+ user_list_service = client.GetService('AdwordsUserListService', 'v201809')
+
+ user_list = {
+ 'xsi_type': 'CrmBasedUserList',
+ 'name': 'Customer relationship management list #%d' % uuid.uuid4(),
+ 'description': 'A list of customers that originated from email addresses',
+ # CRM-based user lists can use a membershipLifeSpan of 10000 to indicate
+ # unlimited; otherwise normal values apply.
+ 'membershipLifeSpan': 30,
+ 'uploadKeyType': 'CONTACT_INFO'
+ }
+
+ # Create an operation to add the user list.
+ operations = [{
+ 'operator': 'ADD',
+ 'operand': user_list
+ }]
+
+ result = user_list_service.mutate(operations)
+ user_list_id = result['value'][0]['id']
+
+ emails = ['customer1@example.com', 'customer2@example.com',
+ ' Customer3@example.com ']
+ members = [{'hashedEmail': NormalizeAndSHA256(email)} for email in emails]
+
+ # Add address info.
+ members.append({
+ 'addressInfo': {
+ # First and last name must be normalized and hashed.
+ 'hashedFirstName': NormalizeAndSHA256('John'),
+ 'hashedLastName': NormalizeAndSHA256('Doe'),
+ # Country code and zip code are sent in plaintext.
+ 'countryCode': 'US',
+ 'zipCode': '10001'
+ }
+ })
+
+ mutate_members_operation = {
+ 'operand': {
+ 'userListId': user_list_id,
+ 'membersList': members
+ },
+ 'operator': 'ADD'
+ }
+
+ response = user_list_service.mutateMembers([mutate_members_operation])
+
+ if 'userLists' in response:
+ for user_list in response['userLists']:
+ print('User list with name "%s" and ID "%d" was added.'
+ % (user_list['name'], user_list['id']))
+
+
+def NormalizeAndSHA256(s):
+ """Normalizes (lowercase, remove whitespace) and hashes a string with SHA-256.
+
+ Args:
+ s: The string to perform this operation on.
+
+ Returns:
+ A normalized and SHA-256 hashed string.
+ """
+ return hashlib.sha256(s.strip().lower()).hexdigest()
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+ main(adwords_client)
diff --git a/examples/adwords/v201809/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201809/remarketing/add_rule_based_user_lists.py
new file mode 100755
index 00000000..3de34401
--- /dev/null
+++ b/examples/adwords/v201809/remarketing/add_rule_based_user_lists.py
@@ -0,0 +1,235 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the 'License');
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an 'AS IS' BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example adds two rule-based remarketing user lists.
+
+Adds two rule-based remarketing user lists; one with no site visit date
+restrictions and another that will only include users who visit your site in
+the next six months.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import calendar
+from datetime import date
+from datetime import datetime
+from datetime import timedelta
+from googleads import adwords
+
+
+def main(client):
+ # Initialize appropriate service.
+ adwords_user_list_service = client.GetService(
+ 'AdwordsUserListService', version='v201809')
+
+ # First rule item group - users who visited the checkout page and had more
+ # than one item in their shopping cart.
+ checkout_rule_item = {
+ 'StringRuleItem': {
+ 'key': {
+ 'name': 'ecomm_pagetype'
+ },
+ 'op': 'EQUALS',
+ 'value': 'checkout'
+ }
+ }
+
+ cart_size_rule_item = {
+ 'NumberRuleItem': {
+ 'key': {
+ 'name': 'cartsize'
+ },
+ 'op': 'GREATER_THAN',
+ 'value': '1.0'
+ }
+ }
+
+ # Combine the two rule items into a RuleItemGroup so AdWords will logically
+ # AND the rules together.
+ checkout_multiple_item_group = {
+ 'items': [checkout_rule_item, cart_size_rule_item]
+ }
+
+ # Second rule item group - users who checked out within the next 3 months.
+ today = date.today()
+ start_date_rule_item = {
+ 'DateRuleItem': {
+ 'key': {
+ 'name': 'checkoutdate'
+ },
+ 'op': 'AFTER',
+ 'value': today.strftime('%Y%m%d')
+ }
+ }
+
+ three_months_later = AddMonths(today, 3)
+
+ three_months_later_rule_item = {
+ 'DateRuleItem': {
+ 'key': {
+ 'name': 'checkoutdate'
+ },
+ 'op': 'BEFORE',
+ 'value': three_months_later.strftime('%Y%m%d')
+ }
+ }
+
+ # Combine the date rule items into a RuleItemGroup
+ checked_out_date_range_item_group = {
+ 'items': [start_date_rule_item, three_months_later_rule_item]
+ }
+
+ # Combine the rule item groups into a Rule so AdWords knows how to apply the
+ # rules.
+ rule = {
+ 'groups': [
+ checkout_multiple_item_group,
+ checked_out_date_range_item_group
+ ],
+ # ExpressionRuleUserLists can use either CNF or DNF for matching. CNF
+ # means 'at least one item in each rule item group must match', and DNF
+ # means 'at least one entire rule item group must match'.
+ # DateSpecificRuleUserList only supports DNF. You can also omit the rule
+ # type altogether to default to DNF.
+ 'ruleType': 'DNF'
+ }
+
+ # Third and fourth rule item groups.
+ # Visitors of a page who visited another page.
+ site1_rule_item = {
+ 'StringRuleItem': {
+ 'key': {'name': 'url__'},
+ 'op': 'EQUALS',
+ 'value': 'example.com/example1'
+ }
+ }
+ site2_rule_item = {
+ 'StringRuleItem': {
+ 'key': {'name': 'url__'},
+ 'op': 'EQUALS',
+ 'value': 'example.com/example2'
+ }
+ }
+
+ # Create two rules to show that a visitor browsed two sites.
+ user_visited_site1_rule = {
+ 'groups': [{
+ 'items': [site1_rule_item]
+ }]
+ }
+
+ user_visited_site2_rule = {
+ 'groups': [{
+ 'items': [site2_rule_item]
+ }]
+ }
+
+ # Create the user list with no restrictions on site visit date.
+ expression_user_list = {
+ 'xsi_type': 'ExpressionRuleUserList',
+ 'name': 'Expression-based user list created at %s'
+ % datetime.today().strftime('%Y%m%d %H:%M:%S'),
+ 'description': 'Users who checked out in three month window OR visited'
+ ' the checkout page with more than one item in their'
+ ' cart.',
+ 'rule': rule,
+ # Optional: Set the populationStatus to REQUESTED to include past users in
+ # the user list.
+ 'prepopulationStatus': 'REQUESTED'
+ }
+
+ # Create the user list restricted to users who visit your site within the next
+ # six months.
+ end_date = AddMonths(today, 6)
+
+ date_user_list = {
+ 'xsi_type': 'DateSpecificRuleUserList',
+ 'name': 'Date rule user list created at %s'
+ % datetime.today().strftime('%Y%m%d %H:%M:%S'),
+ 'description': 'Users who visited the site between %s and %s and checked'
+ ' out in three month window OR visited the checkout page'
+ ' with more than one item in their cart.'
+ % (today.strftime('%Y%m%d'), end_date.strftime('%Y%m%d')),
+ 'rule': rule,
+ 'startDate': today.strftime('%Y%m%d'),
+ 'endDate': end_date.strftime('%Y%m%d')
+ }
+
+ # Create the user list for "Visitors of a page who did visit another page".
+ # To create a user list for "Visitors of a page who did not visit another
+ # page", change the ruleOperator from AND to AND_NOT.
+ combined_user_list = {
+ 'xsi_type': 'CombinedRuleUserList',
+ 'name': 'Combined rule user lst create at ${creation_time}',
+ 'description': 'Users who visited two sites.',
+ 'leftOperand': user_visited_site1_rule,
+ 'rightOperand': user_visited_site2_rule,
+ 'ruleOperator': 'AND'
+ }
+
+ # Create operations to add the user lists.
+ operations = [
+ {
+ 'operand': user_list,
+ 'operator': 'ADD',
+ } for user_list in [expression_user_list, date_user_list,
+ combined_user_list]
+ ]
+
+ # Submit the operations.
+ user_lists = adwords_user_list_service.mutate(operations)
+
+ # Display results.
+ for user_list in user_lists['value']:
+ print(('User list added with ID %d, name "%s", status "%s", list type'
+ ' "%s", accountUserListStatus "%s", description "%s".') %
+ (user_list['id'], user_list['name'],
+ user_list['status'], user_list['listType'],
+ user_list['accountUserListStatus'], user_list['description']))
+
+
+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 number of months to add.
+
+ Returns:
+ A date equal to the start date incremented by the given number of months.
+ """
+ current_date = start_date
+ i = 0
+ while i < months:
+ month_days = calendar.monthrange(current_date.year, current_date.month)[1]
+ current_date += timedelta(days=month_days)
+ i += 1
+ return current_date
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client)
diff --git a/examples/adwords/v201809/remarketing/upload_conversion_adjustments.py b/examples/adwords/v201809/remarketing/upload_conversion_adjustments.py
new file mode 100755
index 00000000..90200f70
--- /dev/null
+++ b/examples/adwords/v201809/remarketing/upload_conversion_adjustments.py
@@ -0,0 +1,73 @@
+#!/usr/bin/env python
+#
+# Copyright 2018 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Imports conversion adjustments for conversions that already exist.
+
+To set up a conversion tracker, run the add_conversion_tracker.py example.
+
+"""
+
+from googleads import adwords
+
+
+CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE'
+
+GCLID = 'INSERT_GCLID_HERE'
+
+ADJUSTMENT_TYPE = 'INSERT_ADJUSTMENT_TYPE_HERE'
+
+CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE'
+
+ADJUSTMENT_TIME = 'INSERT_ADJUSTMENT_TIME_HERE'
+
+ADJUSTED_VALUE = 'INSERT_ADJUST_VALUE_HERE'
+
+
+def main(client, conversion_name, gclid, adjustment_type, conversion_time,
+ adjustment_time, adjusted_value):
+ # Initialize appropriate services.
+ offline_conversion_service = client.GetService(
+ 'OfflineConversionAdjustmentFeedService', version='v201809')
+
+ # Associate conversion adjustments with the existing named conversion tracker.
+ # The GCLID should have been uploaded before with a conversion.
+ feed = {
+ 'xsi_type': 'GclidOfflineConversionAdjustmentFeed',
+ 'conversionName': conversion_name,
+ 'googleClickId': gclid,
+ 'conversionTime': conversion_time,
+ 'adjustmentType': adjustment_type,
+ 'adjustmentTime': adjustment_time,
+ 'adjustedValue': adjusted_value
+ }
+
+ offline_conversion_operation = {'operator': 'ADD', 'operand': feed}
+
+ offline_conversion_response = offline_conversion_service.mutate(
+ [offline_conversion_operation])
+
+ new_feed = offline_conversion_response['value'][0]
+
+ print('Uploaded offline conversion adjustment value of "%s" for Google '
+ 'Click ID "%s"' % (new_feed['adjustedValue'],
+ new_feed['googleClickId']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, CONVERSION_NAME, GCLID, ADJUSTMENT_TYPE, CONVERSION_TIME,
+ ADJUSTMENT_TIME, ADJUSTED_VALUE)
diff --git a/examples/adwords/v201809/remarketing/upload_offline_call_conversions.py b/examples/adwords/v201809/remarketing/upload_offline_call_conversions.py
new file mode 100755
index 00000000..695f91f8
--- /dev/null
+++ b/examples/adwords/v201809/remarketing/upload_offline_call_conversions.py
@@ -0,0 +1,77 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Imports offline conversion values for calls related to ads in your account.
+
+To set up a conversion tracker, run the add_conversion_trackers.py example.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from googleads import adwords
+
+
+CALLER_ID = 'INSERT_CALLER_ID_HERE'
+# For times use the format yyyyMMdd HHmmss tz. For more details on formats, see:
+# https://developers.google.com/adwords/api/docs/appendix/codes-formats#date-and-time-formats
+# For time zones, see:
+# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids
+CALL_START_TIME = 'INSERT_CALL_START_TIME'
+CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' # Name of conversion tracker.
+CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE'
+CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE'
+
+
+def main(client, caller_id, call_start_time, conversion_name, conversion_time,
+ conversion_value):
+ # Initialize appropriate services.
+ occ_feed_service = client.GetService(
+ 'OfflineCallConversionFeedService', version='v201809')
+
+ # Associate offline call conversions with the existing named conversion
+ # tracker. If this tracker was newly created, it may be a few hours before it
+ # can accept conversions.
+ feed = {
+ 'callerId': caller_id,
+ 'callStartTime': call_start_time,
+ 'conversionName': conversion_name,
+ 'conversionTime': conversion_time,
+ 'conversionValue': conversion_value,
+ }
+
+ occ_operations = [{'operator': 'ADD', 'operand': feed}]
+
+ occ_response = occ_feed_service.mutate(occ_operations)
+ values = occ_response['value']
+
+ if values:
+ for occ_feed in values:
+ print('Uploaded offline call conversion value of "%s" for caller ID '
+ '"%s".\n' % (occ_feed['conversionName'], occ_feed['callerId']))
+ else:
+ print('No offline call conversions were added.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, CALLER_ID, CALL_START_TIME, CONVERSION_NAME,
+ CONVERSION_TIME, CONVERSION_VALUE)
diff --git a/examples/adwords/v201809/remarketing/upload_offline_conversions.py b/examples/adwords/v201809/remarketing/upload_offline_conversions.py
new file mode 100755
index 00000000..cb12d45b
--- /dev/null
+++ b/examples/adwords/v201809/remarketing/upload_offline_conversions.py
@@ -0,0 +1,82 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Imports offline conversion values for specific clicks into your account.
+
+To get the Google Click ID for a click, run a CLICK_PERFORMANCE_REPORT. To set
+up a conversion tracker, run the add_conversion_trackers.py example.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from googleads import adwords
+
+# Name of the conversion tracker to upload to.
+CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE'
+# Your click ID must be less than 30 days old.
+CLICK_ID = 'INSERT_GOOGLE_CLICK_ID_HERE'
+# The conversion time must be more recent than the time of the click.
+CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE'
+CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE'
+
+
+def main(client, conversion_name, click_id, conversion_time, conversion_value):
+ # Initialize appropriate services.
+ offline_conversion_feed_service = client.GetService(
+ 'OfflineConversionFeedService', version='v201809')
+
+ # Associate offline conversions with the existing named conversion tracker. If
+ # this tracker was newly created, it may be a few hours before it can accept
+ # conversions.
+ feed = {
+ 'conversionName': conversion_name,
+ 'conversionTime': conversion_time,
+ 'conversionValue': conversion_value,
+ 'googleClickId': click_id,
+ # Optional: To upload fractional conversion credits, set the external
+ # attribution model and credit. To use this feature, your conversion
+ # tracker should be marked as externally attributed. To learn more about
+ # importing externally attributed conversins, see:
+ # https://developers.google.com/adwords/api/docs/guides/conversion-tracking#importing_externally_attributed_conversions
+ # 'externalAttributionCredit': 0.3,
+ # 'externalAttributionModel': 'Linear'
+ }
+
+ offline_conversion_operation = {
+ 'operator': 'ADD',
+ 'operand': feed
+ }
+
+ offline_conversion_response = offline_conversion_feed_service.mutate(
+ [offline_conversion_operation])
+ new_feed = offline_conversion_response['value']
+
+ print('Uploaded offline conversion value of "%s" for Google Click ID '
+ '"%s" to "%s".' % (new_feed['conversionValue'],
+ new_feed['googleClickId'],
+ new_feed['conversionName']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, CONVERSION_NAME, CLICK_ID, CONVERSION_TIME,
+ CONVERSION_VALUE)
diff --git a/examples/adwords/v201809/remarketing/upload_offline_data.py b/examples/adwords/v201809/remarketing/upload_offline_data.py
new file mode 100755
index 00000000..ad8522d0
--- /dev/null
+++ b/examples/adwords/v201809/remarketing/upload_offline_data.py
@@ -0,0 +1,259 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example shows how to upload offline data for store sales transactions.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+import datetime
+import hashlib
+
+from googleads import adwords
+import pytz
+
+
+_DT_FORMAT = '%Y%m%d %H%M%S'
+# User identifier types whose values must be hashed.
+_HASHED_IDENTIFIER_TYPES = ('HASHED_EMAIL', 'HASHED_FIRST_NAME',
+ 'HASHED_LAST_NAME', 'HASHED_PHONE')
+# The timezone to be used in this example. For valid timezone IDs, see:
+# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids
+_TIMEZONE = pytz.timezone('America/New_York')
+# Name of the conversion tracker to upload to.
+CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE'
+# Insert email addresses below for creating user identifiers.
+EMAIL_ADDRESSES = ['EMAIL_ADDRESS_1', 'EMAIL_ADDRESS_2']
+# The external upload ID can be any number that you use to keep track of your
+# uploads.
+EXTERNAL_UPLOAD_ID = 'INSERT_EXTERNAL_UPLOAD_ID'
+# Store sales upload common metadata types
+METADATA_TYPE_1P = 'FirstPartyUploadMetadata'
+METADATA_TYPE_3P = 'ThirdPartyUploadMetadata'
+# Set the below constant to METADATA_TYPE_3P if uploading third-party data.
+STORE_SALES_UPLOAD_COMMON_METADATA_TYPE = METADATA_TYPE_1P
+# The three constants below are needed when uploading third-party data. They
+# are not used when uploading first-party data.
+# Advertiser upload time to partner.
+# For times, use the format yyyyMMdd HHmmss tz. For more details on formats,
+# see:
+# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids
+ADVERTISER_UPLOAD_TIME = 'INSERT_ADVERTISER_UPLOAD_TIME_HERE'
+# Indicates the version of the bridge map.
+BRIDGE_MAP_VERSION_ID = 'INSERT_BRIDGE_MAP_VERSION_ID_HERE'
+# The ID of the third party uploading the transaction feed.
+PARTNER_ID = 'INSERT_PARTNER_ID_HERE'
+
+
+def main(client, conversion_name, external_upload_id,
+ store_sales_upload_common_metadata_type, email_addresses,
+ advertiser_upload_time=None, bridge_map_version_id=None,
+ partner_id=None):
+ # Set partial failure to True since this example demonstrates how to handle
+ # partial errors.
+ client.partial_failure = True
+ # Initialize appropriate services.
+ offline_data_upload_service = client.GetService(
+ 'OfflineDataUploadService', version='v201809')
+
+ # Create the first offline data for upload.
+ # This transaction occurred 7 days ago with an amount of $200 USD.
+ transaction_time_1 = (datetime.datetime.now(tz=_TIMEZONE) -
+ datetime.timedelta(days=7))
+ offline_data_1 = {
+ 'StoreSalesTransaction': {
+ 'userIdentifiers': [
+ _CreateUserIdentifier(identifier_type='HASHED_EMAIL',
+ value=email_addresses[0]),
+ _CreateUserIdentifier(identifier_type='STATE', value='New York')
+ ],
+ 'transactionTime': _GetFormattedDateTime(transaction_time_1),
+ 'transactionAmount': {
+ 'currencyCode': 'USD',
+ 'money': {
+ 'microAmount': 200000000
+ }
+ },
+ 'conversionName': conversion_name
+ }
+ }
+
+ # Create the second offline data for upload.
+ # This transaction occurred 14 days ago with amount of 450 EUR.
+ transaction_time_2 = (datetime.datetime.now(tz=_TIMEZONE) -
+ datetime.timedelta(days=14))
+ offline_data_2 = {
+ 'StoreSalesTransaction': {
+ 'userIdentifiers': [
+ _CreateUserIdentifier(identifier_type='HASHED_EMAIL',
+ value=email_addresses[1]),
+ _CreateUserIdentifier(identifier_type='STATE', value='California')
+ ],
+ 'transactionTime': _GetFormattedDateTime(transaction_time_2),
+ 'transactionAmount': {
+ 'currencyCode': 'EUR',
+ 'money': {
+ 'microAmount': 450000000
+ }
+ },
+ 'conversionName': conversion_name
+ }
+ }
+
+ # Set the type and metadata of this upload.
+ upload_metadata = {
+ 'StoreSalesUploadCommonMetadata': {
+ 'xsi_type': store_sales_upload_common_metadata_type,
+ 'loyaltyRate': 1.0,
+ 'transactionUploadRate': 1.0,
+ }
+ }
+
+ if store_sales_upload_common_metadata_type == METADATA_TYPE_1P:
+ upload_type = 'STORE_SALES_UPLOAD_FIRST_PARTY'
+ elif store_sales_upload_common_metadata_type == METADATA_TYPE_3P:
+ upload_type = 'STORE_SALES_UPLOAD_THIRD_PARTY'
+ upload_metadata['StoreSalesUploadCommonMetadata'].update({
+ 'advertiserUploadTime': advertiser_upload_time,
+ 'validTransactionRate': 1.0,
+ 'partnerMatchRate': 1.0,
+ 'partnerUploadRate': 1.0,
+ 'bridgeMapVersionId': bridge_map_version_id,
+ 'partnerId': partner_id
+ })
+ else:
+ raise ValueError('Unknown metadata type.')
+
+ # Create offline data upload
+ offline_data_upload = {
+ 'externalUploadId': external_upload_id,
+ 'offlineDataList': [offline_data_1, offline_data_2],
+ # Set the type of this upload.
+ 'uploadType': upload_type,
+ 'uploadMetadata': upload_metadata
+ }
+
+ # Create an offline data upload operation.
+ operations = [{
+ 'operator': 'ADD',
+ 'operand': offline_data_upload
+ }]
+
+ # Upload offline data on the server and print(the result.)
+ result = offline_data_upload_service.mutate(operations)
+ offline_data_upload = result['value'][0]
+
+ print('Uploaded offline data with external upload ID "%d" and upload status '
+ '"%s".' % (offline_data_upload['externalUploadId'],
+ offline_data_upload['uploadStatus']))
+
+ # Print any partial data errors from the response.
+ if result['partialFailureErrors']:
+ for api_error in result['partialFailureErrors']:
+ # Get the index of the failed operation from the error's field path
+ # elements.
+ operation_index = _GetFieldPathElementIndex(api_error, 'operations')
+
+ if operation_index:
+ failed_offline_data_upload = operations[operation_index]['operand']
+ # Get the index of the entry in the offline data list from the error's
+ # field path elements.
+ offline_data_list_index = _GetFieldPathElementIndex(
+ api_error, 'offlineDataList')
+ print('Offline data list entry "%d" in operation "%d" with external '
+ 'upload ID "%d" and type "%s" has triggered failure for the '
+ 'following reason: "%s"' % (
+ offline_data_list_index, operation_index,
+ failed_offline_data_upload['externalUploadId'],
+ failed_offline_data_upload['uploadType'],
+ api_error['errorString']))
+ else:
+ print('A failure has occurred for the following reason: "%s".' % (
+ api_error['errorString']))
+
+
+def _CreateUserIdentifier(identifier_type=None, value=None):
+ """Creates a user identifier from the specified type and value.
+
+ Args:
+ identifier_type: a str specifying the type of user identifier.
+ value: a str value of the identifier; to be hashed using SHA-256 if needed.
+
+ Returns:
+ A dict specifying a user identifier, with a value hashed using SHA-256 if
+ needed.
+ """
+ if identifier_type in _HASHED_IDENTIFIER_TYPES:
+ # If the user identifier type is a hashed type, normalize and hash the
+ # value.
+ value = hashlib.sha256(value.strip().lower()).hexdigest()
+
+ user_identifier = {
+ 'userIdentifierType': identifier_type,
+ 'value': value
+ }
+
+ return user_identifier
+
+
+def _GetFieldPathElementIndex(api_error, field):
+ """Retrieve the index of a given field in the api_error's fieldPathElements.
+
+ Args:
+ api_error: a dict containing a partialFailureError returned from the AdWords
+ API.
+ field: a str field for which this determines the index in the api_error's
+ fieldPathElements.
+
+ Returns:
+ An int index of the field path element, or None if the specified field can't
+ be found in the api_error.
+ """
+ field_path_elements = api_error['fieldPathElements']
+
+ if field_path_elements:
+ found_index = [field_path_element['index']
+ for field_path_element in field_path_elements
+ if field_path_element['field'] == field]
+ if found_index:
+ return found_index
+
+ return None
+
+
+def _GetFormattedDateTime(dt):
+ """Formats the given datetime and timezone for use with AdWords.
+
+ Args:
+ dt: a datetime instance.
+
+ Returns:
+ A str representation of the datetime in the correct format for AdWords.
+ """
+ return '%s %s' % (datetime.datetime.strftime(dt, _DT_FORMAT), _TIMEZONE.zone)
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, CONVERSION_NAME, EXTERNAL_UPLOAD_ID,
+ STORE_SALES_UPLOAD_COMMON_METADATA_TYPE, EMAIL_ADDRESSES,
+ ADVERTISER_UPLOAD_TIME, BRIDGE_MAP_VERSION_ID, PARTNER_ID)
diff --git a/examples/adwords/v201809/reporting/__init__.py b/examples/adwords/v201809/reporting/__init__.py
new file mode 100644
index 00000000..8f94f28b
--- /dev/null
+++ b/examples/adwords/v201809/reporting/__init__.py
@@ -0,0 +1,15 @@
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Reporting examples."""
diff --git a/examples/adwords/v201809/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201809/reporting/download_criteria_report_as_stream_with_awql.py
new file mode 100755
index 00000000..55848c9d
--- /dev/null
+++ b/examples/adwords/v201809/reporting/download_criteria_report_as_stream_with_awql.py
@@ -0,0 +1,79 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example downloads a criteria performance report as a stream with AWQL.
+
+To get report fields, run get_report_fields.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import StringIO
+import sys
+
+from googleads import adwords
+
+# Specify where to download the file here.
+PATH = '/tmp/report_download.csv'
+# The chunk size used for the report download.
+CHUNK_SIZE = 16 * 1024
+
+
+def main(client):
+ # Initialize appropriate service.
+ report_downloader = client.GetReportDownloader(version='v201809')
+
+ # Create report query.
+ report_query = (adwords.ReportQueryBuilder()
+ .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria',
+ 'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks',
+ 'Cost')
+ .From('CRITERIA_PERFORMANCE_REPORT')
+ .Where('Status').In('ENABLED', 'PAUSED')
+ .During('LAST_7_DAYS')
+ .Build())
+
+ print(report_downloader.DownloadReportAsStringWithAwql(
+ report_query, 'CSV', skip_report_header=False, skip_column_header=False,
+ skip_report_summary=False, include_zero_impressions=True))
+
+ # Retrieve the report stream and print(it out)
+ report_data = StringIO.StringIO()
+ stream_data = report_downloader.DownloadReportAsStreamWithAwql(report_query,
+ 'CSV')
+
+ try:
+ while True:
+ chunk = stream_data.read(CHUNK_SIZE)
+ if not chunk: break
+ report_data.write(chunk.decode() if sys.version_info[0] == 3
+ and getattr(report_data, 'mode', 'w') == 'w' else chunk)
+ print(report_data.getvalue())
+ finally:
+ report_data.close()
+ stream_data.close()
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client)
diff --git a/examples/adwords/v201809/reporting/download_criteria_report_as_stream_with_selector.py b/examples/adwords/v201809/reporting/download_criteria_report_as_stream_with_selector.py
new file mode 100755
index 00000000..a68b931c
--- /dev/null
+++ b/examples/adwords/v201809/reporting/download_criteria_report_as_stream_with_selector.py
@@ -0,0 +1,72 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example retrieves the report download stream.
+
+To get report fields, run get_report_fields.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import StringIO
+import sys
+from googleads import adwords
+
+# The chunk size used for the report download.
+CHUNK_SIZE = 16 * 1024
+
+
+def main(client):
+ report_downloader = client.GetReportDownloader(version='v201809')
+
+ # Create report definition.
+ report = {
+ 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT',
+ 'dateRangeType': 'LAST_7_DAYS',
+ 'reportType': 'CRITERIA_PERFORMANCE_REPORT',
+ 'downloadFormat': 'CSV',
+ 'selector': {
+ 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType',
+ 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost']
+ }
+ }
+
+ # Retrieve the report stream and print(it out)
+ report_data = StringIO.StringIO()
+ stream_data = report_downloader.DownloadReportAsStream(
+ report, skip_report_header=False, skip_column_header=False,
+ skip_report_summary=False, include_zero_impressions=True)
+
+ try:
+ while True:
+ chunk = stream_data.read(CHUNK_SIZE)
+ if not chunk: break
+ report_data.write(chunk.decode() if sys.version_info[0] == 3
+ and getattr(report_data, 'mode', 'w') == 'w' else chunk)
+ print(report_data.getvalue())
+ finally:
+ report_data.close()
+ stream_data.close()
+
+
+if __name__ == '__main__':
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+ main(adwords_client)
diff --git a/examples/adwords/v201809/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201809/reporting/download_criteria_report_as_string_with_awql.py
new file mode 100755
index 00000000..d32508db
--- /dev/null
+++ b/examples/adwords/v201809/reporting/download_criteria_report_as_string_with_awql.py
@@ -0,0 +1,58 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example downloads a criteria performance report as a string with AWQL.
+
+To get report fields, run get_report_fields.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from googleads import adwords
+
+
+# Specify where to download the file here.
+PATH = '/tmp/report_download.csv'
+
+
+def main(client):
+ # Initialize appropriate service.
+ report_downloader = client.GetReportDownloader(version='v201809')
+
+ # Create report query.
+ report_query = (adwords.ReportQueryBuilder()
+ .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria',
+ 'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks',
+ 'Cost')
+ .From('CRITERIA_PERFORMANCE_REPORT')
+ .Where('Status').In('ENABLED', 'PAUSED')
+ .During('LAST_7_DAYS')
+ .Build())
+
+ print(report_downloader.DownloadReportAsStringWithAwql(
+ report_query, 'CSV', skip_report_header=False, skip_column_header=False,
+ skip_report_summary=False, include_zero_impressions=True))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client)
diff --git a/examples/adwords/v201809/reporting/download_criteria_report_as_string_with_selector.py b/examples/adwords/v201809/reporting/download_criteria_report_as_string_with_selector.py
new file mode 100755
index 00000000..8a23d63a
--- /dev/null
+++ b/examples/adwords/v201809/reporting/download_criteria_report_as_string_with_selector.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example downloads a criteria performance report as a string.
+
+To get report fields, run get_report_fields.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+from googleads import adwords
+
+
+def main(client):
+ report_downloader = client.GetReportDownloader(version='v201809')
+
+ # Create report definition.
+ report = {
+ 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT',
+ 'dateRangeType': 'LAST_7_DAYS',
+ 'reportType': 'CRITERIA_PERFORMANCE_REPORT',
+ 'downloadFormat': 'CSV',
+ 'selector': {
+ 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType',
+ 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost']
+ }
+ }
+
+ # Print out the report as a string
+ print(report_downloader.DownloadReportAsString(
+ report, skip_report_header=False, skip_column_header=False,
+ skip_report_summary=False, include_zero_impressions=True))
+
+
+if __name__ == '__main__':
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+ main(adwords_client)
diff --git a/examples/adwords/v201809/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201809/reporting/download_criteria_report_with_awql.py
new file mode 100755
index 00000000..7e2ca12f
--- /dev/null
+++ b/examples/adwords/v201809/reporting/download_criteria_report_with_awql.py
@@ -0,0 +1,58 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example downloads a criteria performance report with AWQL.
+
+To get report fields, run get_report_fields.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+import sys
+from googleads import adwords
+
+
+def main(client):
+ # Initialize appropriate service.
+ report_downloader = client.GetReportDownloader(version='v201809')
+
+ # Create report query.
+ report_query = (adwords.ReportQueryBuilder()
+ .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria',
+ 'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks',
+ 'Cost')
+ .From('CRITERIA_PERFORMANCE_REPORT')
+ .Where('Status').In('ENABLED', 'PAUSED')
+ .During('LAST_7_DAYS')
+ .Build())
+
+ # You can provide a file object to write the output to. For this
+ # demonstration we use sys.stdout to write the report to the screen.
+ report_downloader.DownloadReportWithAwql(
+ report_query, 'CSV', sys.stdout, skip_report_header=False,
+ skip_column_header=False, skip_report_summary=False,
+ include_zero_impressions=True)
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client)
diff --git a/examples/adwords/v201809/reporting/download_criteria_report_with_selector.py b/examples/adwords/v201809/reporting/download_criteria_report_with_selector.py
new file mode 100755
index 00000000..5027e841
--- /dev/null
+++ b/examples/adwords/v201809/reporting/download_criteria_report_with_selector.py
@@ -0,0 +1,56 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example downloads a criteria performance report.
+
+To get report fields, run get_report_fields.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import sys
+from googleads import adwords
+
+
+def main(client):
+ report_downloader = client.GetReportDownloader(version='v201809')
+
+ report = {
+ 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT',
+ 'dateRangeType': 'LAST_7_DAYS',
+ 'reportType': 'CRITERIA_PERFORMANCE_REPORT',
+ 'downloadFormat': 'CSV',
+ 'selector': {
+ 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType',
+ 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost']
+ }
+ }
+
+ # You can provide a file object to write the output to. For this demonstration
+ # we use sys.stdout to write the report to the screen.
+ report_downloader.DownloadReport(
+ report, sys.stdout, skip_report_header=False, skip_column_header=False,
+ skip_report_summary=False, include_zero_impressions=True)
+
+
+if __name__ == '__main__':
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+ main(adwords_client)
diff --git a/examples/adwords/v201809/reporting/get_report_fields.py b/examples/adwords/v201809/reporting/get_report_fields.py
new file mode 100755
index 00000000..2356af46
--- /dev/null
+++ b/examples/adwords/v201809/reporting/get_report_fields.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets report fields.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from googleads import adwords
+
+
+REPORT_TYPE = 'INSERT_REPORT_TYPE_HERE'
+
+
+def main(client, report_type):
+ # Initialize appropriate service.
+ report_definition_service = client.GetService(
+ 'ReportDefinitionService', version='v201809')
+
+ # Get report fields.
+ fields = report_definition_service.getReportFields(report_type)
+
+ # Display results.
+ print('Report type "%s" contains the following fields:' % report_type)
+ for field in fields:
+ print(' - %s (%s)' % (field['fieldName'], field['fieldType']))
+ if 'enumValues' in field:
+ print(' := [%s]' % ', '.join(field['enumValues']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, REPORT_TYPE)
diff --git a/examples/adwords/v201809/reporting/parallel_report_download.py b/examples/adwords/v201809/reporting/parallel_report_download.py
new file mode 100755
index 00000000..4b28e930
--- /dev/null
+++ b/examples/adwords/v201809/reporting/parallel_report_download.py
@@ -0,0 +1,244 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example downloads an adgroup performance report for all child accounts.
+
+To get report fields, run get_report_fields.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+"""
+
+import multiprocessing
+import os
+from Queue import Empty
+import time
+
+import googleads.adwords
+import googleads.errors
+
+# Timeout between retries in seconds.
+BACKOFF_FACTOR = 5
+# Maximum number of processes to spawn.
+MAX_PROCESSES = multiprocessing.cpu_count()
+# Maximum number of retries for 500 errors.
+MAX_RETRIES = 5
+# Maximum number of items to be sent in a single API response.
+PAGE_SIZE = 100
+# Directory to download the reports to.
+REPORT_DOWNLOAD_DIRECTORY = 'INSERT_REPORT_DOWNLOAD_DIRECTORY'
+
+
+def _DownloadReport(process_id, report_download_directory, customer_id,
+ report_definition):
+ """Helper function used by ReportWorker to download customer report.
+
+ Note that multiprocessing differs between Windows / Unix environments. A
+ Process or its subclasses in Windows must be serializable with pickle, but
+ that is not possible for AdWordsClient or ReportDownloader. This top-level
+ function is used as a work-around for Windows support.
+
+ Args:
+ process_id: The PID of the process downloading the report.
+ report_download_directory: A string indicating the directory where you
+ would like to download the reports.
+ customer_id: A str AdWords customer ID for which the report is being
+ downloaded.
+ report_definition: A dict containing the report definition to be used.
+
+ Returns:
+ A tuple indicating a boolean success/failure status, and dict request
+ context.
+ """
+ report_downloader = (googleads.adwords.AdWordsClient.LoadFromStorage()
+ .GetReportDownloader())
+
+ filepath = os.path.join(report_download_directory,
+ 'adgroup_%d.csv' % customer_id)
+ retry_count = 0
+
+ while True:
+ print('[%d/%d] Loading report for customer ID "%s" into "%s"...'
+ % (process_id, retry_count, customer_id, filepath))
+ try:
+ with open(filepath, 'wb') as handler:
+ report_downloader.DownloadReport(
+ report_definition, output=handler,
+ client_customer_id=customer_id)
+ return (True, {'customerId': customer_id})
+ except googleads.errors.AdWordsReportError as e:
+ if e.code == 500 and retry_count < MAX_RETRIES:
+ time.sleep(retry_count * BACKOFF_FACTOR)
+ else:
+ print('Report failed for customer ID "%s" with code "%d" after "%d" '
+ 'retries.' % (customer_id, e.code, retry_count+1))
+ return (False, {'customerId': customer_id, 'code': e.code,
+ 'message': e.message})
+
+
+class ReportWorker(multiprocessing.Process):
+ """A worker Process used to download reports for a set of customer IDs."""
+
+ def __init__(self, report_download_directory, report_definition,
+ input_queue, success_queue, failure_queue):
+ """Initializes a ReportWorker.
+
+ Args:
+ report_download_directory: A string indicating the directory where you
+ would like to download the reports.
+ report_definition: A dict containing the report definition that you would
+ like to run against all customer IDs in the input_queue.
+ input_queue: A Queue instance containing all of the customer IDs that
+ the report_definition will be run against.
+ success_queue: A Queue instance that the details of successful report
+ downloads will be saved to.
+ failure_queue: A Queue instance that the details of failed report
+ downloads will be saved to.
+ """
+ super(ReportWorker, self).__init__()
+ self.report_download_directory = report_download_directory
+ self.report_definition = report_definition
+ self.input_queue = input_queue
+ self.success_queue = success_queue
+ self.failure_queue = failure_queue
+
+ def run(self):
+ while True:
+ try:
+ customer_id = self.input_queue.get(timeout=0.01)
+ except Empty:
+ break
+ result = _DownloadReport(self.ident, self.report_download_directory,
+ customer_id, self.report_definition)
+ (self.success_queue if result[0] else self.failure_queue).put(result[1])
+
+
+def GetCustomerIDs(client):
+ """Retrieves all CustomerIds in the account hierarchy.
+
+ Note that your configuration file must specify a client_customer_id belonging
+ to an AdWords manager account.
+
+ Args:
+ client: an AdWordsClient instance.
+ Raises:
+ Exception: if no CustomerIds could be found.
+ Returns:
+ A Queue instance containing all CustomerIds in the account hierarchy.
+ """
+ # For this example, we will use ManagedCustomerService to get all IDs in
+ # hierarchy that do not belong to MCC accounts.
+ managed_customer_service = client.GetService('ManagedCustomerService',
+ version='v201809')
+
+ offset = 0
+
+ # Get the account hierarchy for this account.
+ selector = {
+ 'fields': ['CustomerId'],
+ 'predicates': [{
+ 'field': 'CanManageClients',
+ 'operator': 'EQUALS',
+ 'values': [False]
+ }],
+ 'paging': {
+ 'startIndex': str(offset),
+ 'numberResults': str(PAGE_SIZE)
+ }
+ }
+
+ # Using Queue to balance load between processes.
+ queue = multiprocessing.Queue()
+ more_pages = True
+
+ while more_pages:
+ page = managed_customer_service.get(selector)
+
+ if page and 'entries' in page and page['entries']:
+ for entry in page['entries']:
+ queue.put(entry['customerId'])
+ else:
+ raise Exception('Can\'t retrieve any customer ID.')
+ offset += PAGE_SIZE
+ selector['paging']['startIndex'] = str(offset)
+ more_pages = offset < int(page['totalNumEntries'])
+
+ return queue
+
+
+def main(client, report_download_directory):
+ # Determine list of customer IDs to retrieve report for.
+ input_queue = GetCustomerIDs(client)
+ reports_succeeded = multiprocessing.Queue()
+ reports_failed = multiprocessing.Queue()
+
+ # Create report definition.
+ report_definition = {
+ 'reportName': 'Custom ADGROUP_PERFORMANCE_REPORT',
+ 'dateRangeType': 'LAST_7_DAYS',
+ 'reportType': 'ADGROUP_PERFORMANCE_REPORT',
+ 'downloadFormat': 'CSV',
+ 'selector': {
+ 'fields': ['CampaignId', 'AdGroupId', 'Impressions', 'Clicks',
+ 'Cost'],
+ # Predicates are optional.
+ 'predicates': {
+ 'field': 'AdGroupStatus',
+ 'operator': 'IN',
+ 'values': ['ENABLED', 'PAUSED']
+ }
+ },
+ }
+
+ queue_size = input_queue.qsize()
+ num_processes = min(queue_size, MAX_PROCESSES)
+ print('Retrieving %d reports with %d processes:' % (queue_size, num_processes))
+
+ # Start all the processes.
+ processes = [ReportWorker(report_download_directory,
+ report_definition, input_queue, reports_succeeded,
+ reports_failed)
+ for _ in range(num_processes)]
+
+ for process in processes:
+ process.start()
+
+ for process in processes:
+ process.join()
+
+ print('Finished downloading reports with the following results:')
+ while True:
+ try:
+ success = reports_succeeded.get(timeout=0.01)
+ except Empty:
+ break
+ print('\tReport for CustomerId "%d" succeeded.' % success['customerId'])
+
+ while True:
+ try:
+ failure = reports_failed.get(timeout=0.01)
+ except Empty:
+ break
+ print('\tReport for CustomerId "%d" failed with error code "%s" and '
+ 'message: %s.' % (failure['customerId'], failure['code'],
+ failure['message']))
+
+
+if __name__ == '__main__':
+ adwords_client = googleads.adwords.AdWordsClient.LoadFromStorage()
+ main(adwords_client, REPORT_DOWNLOAD_DIRECTORY)
diff --git a/examples/adwords/v201809/reporting/stream_criteria_report_results.py b/examples/adwords/v201809/reporting/stream_criteria_report_results.py
new file mode 100755
index 00000000..a6186b10
--- /dev/null
+++ b/examples/adwords/v201809/reporting/stream_criteria_report_results.py
@@ -0,0 +1,70 @@
+#!/usr/bin/env python
+#
+# Copyright 2018 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example streams the results of an ad hoc report.
+
+Collects total impressions by campaign from each line. Demonstrates how you can
+extract data from a large report without holding the entire result set in
+memory or using files.
+"""
+
+import collections
+
+from googleads import adwords
+
+
+def main(client):
+ # Initialize appropriate service.
+ report_downloader = client.GetReportDownloader(version='v201809')
+
+ # Create report query.
+ report_query = (adwords.ReportQueryBuilder()
+ .Select('Id', 'AdNetworkType1', 'Impressions')
+ .From('CRITERIA_PERFORMANCE_REPORT')
+ .Where('Status').In('ENABLED', 'PAUSED')
+ .During('LAST_7_DAYS')
+ .Build())
+
+ # Retrieve the report stream.
+ stream = report_downloader.DownloadReportAsStreamWithAwql(
+ report_query, 'CSV', skip_report_header=True, skip_column_header=True,
+ skip_report_summary=True, include_zero_impressions=True)
+
+ ad_network_map = collections.defaultdict(int)
+
+ try:
+ while True:
+ line = stream.readline()
+ if not line: break
+ process_line(line, ad_network_map=ad_network_map)
+ finally:
+ stream.close()
+
+ print('Total impressions by ad network type 1:')
+ for ad_network_type, impressions in sorted(ad_network_map.iteritems()):
+ print('%s: %s' % (ad_network_type, impressions))
+
+
+def process_line(line, ad_network_map):
+ _, ad_network_type_1, impressions = line.split(',')
+ ad_network_map[ad_network_type_1] += int(impressions)
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client)
diff --git a/examples/adwords/v201809/shopping/__init__.py b/examples/adwords/v201809/shopping/__init__.py
new file mode 100644
index 00000000..be510830
--- /dev/null
+++ b/examples/adwords/v201809/shopping/__init__.py
@@ -0,0 +1,15 @@
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Shopping examples."""
diff --git a/examples/adwords/v201809/shopping/add_product_partition_tree.py b/examples/adwords/v201809/shopping/add_product_partition_tree.py
new file mode 100755
index 00000000..f377911f
--- /dev/null
+++ b/examples/adwords/v201809/shopping/add_product_partition_tree.py
@@ -0,0 +1,279 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example creates a ProductPartition tree.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import adwords
+
+ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
+
+
+class ProductPartitionHelper(object):
+ """A helper for creating ProductPartition trees."""
+
+ def __init__(self, adgroup_id):
+ """Initializer.
+
+ Args:
+ adgroup_id: The ID of the AdGroup that we wish to attach the partition
+ tree to.
+ """
+ # The next temporary criterion ID to be used.
+ # When creating our tree we need to specify the parent-child relationships
+ # between nodes. However, until a criterion has been created on the server
+ # we do not have a criterion ID with which to refer to it.
+ # Instead we can specify temporary IDs that are specific to a single mutate
+ # request. Once the criteria have been created they are assigned an ID as
+ # normal and the temporary ID will no longer refer to it.
+ # A valid temporary ID is any negative integer.
+ self.next_id = -1
+ # The set of mutate operations needed to create the current tree.
+ self.operations = []
+ self.adgroup_id = adgroup_id
+
+ 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',
+ 'partitionType': 'SUBDIVISION',
+ 'id': str(self.next_id)
+ }
+
+ # The root has neither a parent nor a value.
+ if parent is not None:
+ division['parentCriterionId'] = parent['id']
+ division['caseValue'] = value
+
+ adgroup_criterion = {
+ 'xsi_type': 'BiddableAdGroupCriterion',
+ 'adGroupId': self.adgroup_id,
+ 'criterion': division
+ }
+
+ self.CreateAddOperation(adgroup_criterion)
+ self.next_id -= 1
+
+ return division
+
+ 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.
+ """
+ unit = {
+ 'xsi_type': 'ProductPartition',
+ 'partitionType': 'UNIT'
+ }
+
+ # The root node has neither a parent nor a value.
+ if parent is not None:
+ unit['parentCriterionId'] = parent['id']
+ unit['caseValue'] = value
+
+ if bid_amount is not None and bid_amount > 0:
+ bidding_strategy_configuration = {
+ 'bids': [{
+ 'xsi_type': 'CpcBid',
+ 'bid': {
+ 'xsi_type': 'Money',
+ 'microAmount': str(bid_amount)
+ }
+ }]
+ }
+
+ adgroup_criterion = {
+ 'xsi_type': 'BiddableAdGroupCriterion',
+ 'biddingStrategyConfiguration': bidding_strategy_configuration
+ }
+ else:
+ adgroup_criterion = {
+ 'xsi_type': 'NegativeAdGroupCriterion'
+ }
+
+ adgroup_criterion['adGroupId'] = self.adgroup_id
+ adgroup_criterion['criterion'] = unit
+
+ self.CreateAddOperation(adgroup_criterion)
+
+ return unit
+
+ def GetOperations(self):
+ """Returns the set of mutate operations needed to create the current tree.
+
+ Returns:
+ The set of operations
+ """
+ return self.operations
+
+ def CreateAddOperation(self, criterion):
+ """Creates an AdGroupCriterionOperation for the given criterion.
+
+ Args:
+ criterion: The criterion we want to add.
+ """
+ operation = {
+ 'operator': 'ADD',
+ 'operand': criterion
+ }
+
+ self.operations.append(operation)
+
+
+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)
+
+ root = helper.CreateSubdivision()
+
+ new_product_canonical_condition = {
+ 'xsi_type': 'ProductCanonicalCondition',
+ 'condition': 'NEW'
+ }
+
+ used_product_canonical_condition = {
+ 'xsi_type': 'ProductCanonicalCondition',
+ 'condition': 'USED'
+ }
+
+ other_product_canonical_condition = {
+ 'xsi_type': 'ProductCanonicalCondition',
+ }
+
+ helper.CreateUnit(root, new_product_canonical_condition, 200000)
+ helper.CreateUnit(root, used_product_canonical_condition, 100000)
+ other_condition = helper.CreateSubdivision(
+ root, other_product_canonical_condition)
+
+ cool_product_brand = {
+ 'xsi_type': 'ProductBrand',
+ 'value': 'CoolBrand'
+ }
+
+ cheap_product_brand = {
+ 'xsi_type': 'ProductBrand',
+ 'value': 'CheapBrand'
+ }
+
+ other_product_brand = {
+ 'xsi_type': 'ProductBrand',
+ }
+
+ helper.CreateUnit(other_condition, cool_product_brand, 900000)
+ helper.CreateUnit(other_condition, cheap_product_brand, 10000)
+ other_brand = helper.CreateSubdivision(other_condition, other_product_brand)
+
+ # The value for the bidding category is a fixed ID for the 'Luggage & Bags'
+ # category. You can retrieve IDs for categories from the ConstantDataService.
+ # See the 'GetProductTaxonomy' example for more details.
+ luggage_category = {
+ 'xsi_type': 'ProductBiddingCategory',
+ 'type': 'BIDDING_CATEGORY_L1',
+ 'value': '-5914235892932915235'
+ }
+
+ generic_category = {
+ 'xsi_type': 'ProductBiddingCategory',
+ 'type': 'BIDDING_CATEGORY_L1',
+ }
+
+ helper.CreateUnit(other_brand, luggage_category, 750000)
+ helper.CreateUnit(other_brand, generic_category, 110000)
+
+ # Make the mutate request
+ result = adgroup_criterion_service.mutate(helper.GetOperations())
+
+ children = {}
+
+ root_node = None
+
+ # For each criterion, make an array containing each of its children.
+ # We always create the parent before the child, so we can rely on that here.
+ for adgroup_criterion in result['value']:
+ children[adgroup_criterion['criterion']['id']] = []
+
+ if 'parentCriterionId' in adgroup_criterion['criterion']:
+ children[adgroup_criterion['criterion']['parentCriterionId']].append(
+ adgroup_criterion['criterion'])
+ else:
+ root_node = adgroup_criterion['criterion']
+
+ # Show the tree
+ DisplayTree(root_node, 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_value = node['caseValue']
+ node_type = case_value['ProductDimension.Type']
+
+ if node_type == 'ProductCanonicalCondition':
+ value = (case_value['condition'] if 'condition' in case_value
+ else 'OTHER')
+ elif node_type == 'ProductBiddingCategory':
+ value = '%s(%s)' % (case_value['type'], case_value['value']
+ if 'value' in case_value else 'OTHER')
+ else:
+ value = (case_value['value'] if 'value' in case_value else 'OTHER')
+
+ print('%sid: %s, node_type: %s, value: %s\n'
+ % (' ' * level, node['id'], node_type, value))
+
+ for child_node in children[node['id']]:
+ DisplayTree(child_node, children, level + 1)
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, ADGROUP_ID)
diff --git a/examples/adwords/v201809/shopping/add_product_scope.py b/examples/adwords/v201809/shopping/add_product_scope.py
new file mode 100755
index 00000000..fb496782
--- /dev/null
+++ b/examples/adwords/v201809/shopping/add_product_scope.py
@@ -0,0 +1,104 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Restricts products that will be included in a campaign with a ProductScope.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import adwords
+
+CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
+
+
+def main(client, campaign_id):
+ campaign_criterion_service = client.GetService(
+ 'CampaignCriterionService', version='v201809')
+
+ product_scope = {
+ 'xsi_type': 'ProductScope',
+ # This set of dimensions is for demonstration purposes only. It would be
+ # extremely unlikely that you want to include so many dimensions in your
+ # product scope.
+ 'dimensions': [
+ {
+ 'xsi_type': 'ProductBrand',
+ 'value': 'Nexus'
+ },
+ {
+ 'xsi_type': 'ProductCanonicalCondition',
+ 'condition': 'NEW'
+ },
+ {
+ 'xsi_type': 'ProductCustomAttribute',
+ 'type': 'CUSTOM_ATTRIBUTE_0',
+ 'value': 'my attribute value'
+ },
+ {
+ 'xsi_type': 'ProductOfferId',
+ 'value': 'book1'
+ },
+ {
+ 'xsi_type': 'ProductType',
+ 'type': 'PRODUCT_TYPE_L1',
+ 'value': 'Media'
+ },
+ {
+ 'xsi_type': 'ProductType',
+ 'type': 'PRODUCT_TYPE_L2',
+ 'value': 'Books'
+ },
+ # The value for the bidding category is a fixed ID for the "Luggage
+ # & Bags" category. You can retrieve IDs for categories from the
+ # ConstantDataService. See the "GetProductCategoryTaxonomy" example
+ # for more details.
+ {
+ 'xsi_type': 'ProductBiddingCategory',
+ 'type': 'BIDDING_CATEGORY_L1',
+ 'value': '-5914235892932915235'
+ }
+ ]
+ }
+
+ campaign_criterion = {
+ 'campaignId': campaign_id,
+ 'criterion': product_scope
+ }
+
+ operations = [{
+ 'operator': 'ADD',
+ 'operand': campaign_criterion
+ }]
+
+ # Make the request
+ result = campaign_criterion_service.mutate(operations)
+
+ for criterion in result['value']:
+ print('Created a ProductScope criterion with Id: %s'
+ % criterion['criterion']['id'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adwords/v201809/shopping/add_shopping_campaign.py b/examples/adwords/v201809/shopping/add_shopping_campaign.py
new file mode 100755
index 00000000..eb01867c
--- /dev/null
+++ b/examples/adwords/v201809/shopping/add_shopping_campaign.py
@@ -0,0 +1,172 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example adds a Shopping campaign.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import adwords
+
+BUDGET_ID = 'INSERT_BUDGET_ID_HERE'
+# If set to true, a default partition will be created. If running the
+# add_product_partition_tree.py example right after this example, make
+# sure this stays set to false.
+CREATE_DEFAULT_PARTITION = False
+MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE'
+
+
+def main(client, budget_id, merchant_id, create_default_partition):
+ campaign_service = client.GetService('CampaignService', version='v201809')
+ ad_group_service = client.GetService('AdGroupService', version='v201809')
+ ad_group_ad_service = client.GetService('AdGroupAdService', version='v201809')
+
+ # Create campaign
+ campaign = {
+ 'name': 'Shopping campaign #%s' % uuid.uuid4(),
+ # The advertisingChannelType is what makes this a shopping campaign
+ 'advertisingChannelType': 'SHOPPING',
+ # Recommendation: Set the campaign to PAUSED when creating it to stop the
+ # ads from immediately serving. Set to ENABLED once you've added targeting
+ # and the ads are ready to serve.
+ 'status': 'PAUSED',
+ # Set portfolio budget (required)
+ 'budget': {
+ 'budgetId': budget_id
+ },
+ 'biddingStrategyConfiguration': {
+ 'biddingStrategyType': 'MANUAL_CPC'
+ },
+ 'settings': [
+ # All shopping campaigns need a ShoppingSetting
+ {
+ 'xsi_type': 'ShoppingSetting',
+ 'salesCountry': 'US',
+ 'campaignPriority': '0',
+ 'merchantId': merchant_id,
+ # Set to "True" to enable Local Inventory Ads in your campaign.
+ 'enableLocal': True
+ }
+ ]
+ }
+
+ campaign_operations = [{
+ 'operator': 'ADD',
+ 'operand': campaign
+ }]
+
+ result = campaign_service.mutate(campaign_operations)
+
+ for campaign in result['value']:
+ print('Campaign with name "%s" and ID "%s" was added.'
+ % (campaign['name'], campaign['id']))
+
+ # Create the AdGroup
+ ad_group = {
+ 'campaignId': campaign['id'],
+ 'name': 'AdGroup #%s' % uuid.uuid4()
+ }
+
+ adgroup_operations = {
+ 'operator': 'ADD',
+ 'operand': ad_group
+ }
+
+ # Make the mutate request to add the AdGroup to the Shopping Campaign
+ ad_group = ad_group_service.mutate(adgroup_operations)['value'][0]
+ ad_group_id = ad_group['id']
+
+ print('AdGroup with name "%s" and ID "%s" was added.'
+ % (ad_group['name'], ad_group_id))
+
+ # Create an AdGroup Ad
+ adgroup_ad = {
+ 'adGroupId': ad_group_id,
+ # Create ProductAd
+ 'ad': {
+ 'xsi_type': 'ProductAd',
+ 'Ad.Type': 'ProductAd'
+ }
+ }
+
+ ad_operation = {
+ 'operator': 'ADD',
+ 'operand': adgroup_ad
+ }
+
+ # Make the mutate request to add the ProductAd to the AdGroup
+ ad_result = ad_group_ad_service.mutate([ad_operation])
+
+ for adgroup_ad in ad_result['value']:
+ print('ProductAd with ID "%s" was added.' % adgroup_ad['ad']['id'])
+
+ if create_default_partition:
+ CreateDefaultPartition(client, ad_group_id)
+
+
+def CreateDefaultPartition(client, ad_group_id):
+ """Creates a default partition.
+
+ Args:
+ client: an AdWordsClient instance.
+ ad_group_id: an integer ID for an ad group.
+ """
+ ad_group_criterion_service = client.GetService('AdGroupCriterionService',
+ version='v201809')
+
+ operations = [{
+ 'operator': 'ADD',
+ 'operand': {
+ 'xsi_type': 'BiddableAdGroupCriterion',
+ 'adGroupId': ad_group_id,
+ # Make sure that caseValue and parentCriterionId are left unspecified.
+ # This makes this partition as generic as possible to use as a
+ # fallback when others don't match.
+ 'criterion': {
+ 'xsi_type': 'ProductPartition',
+ 'partitionType': 'UNIT'
+ },
+ 'biddingStrategyConfiguration': {
+ 'bids': [{
+ 'xsi_type': 'CpcBid',
+ 'bid': {
+ 'microAmount': 500000
+ }
+ }]
+ }
+ }
+ }]
+
+ ad_group_criterion = ad_group_criterion_service.mutate(operations)['value'][0]
+
+ print('Ad group criterion with ID "%d" in ad group with ID "%d" was added.'
+ % (ad_group_criterion['criterion']['id'],
+ ad_group_criterion['adGroupId']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, BUDGET_ID, MERCHANT_ID, CREATE_DEFAULT_PARTITION)
diff --git a/examples/adwords/v201809/shopping/add_smart_shopping_ad.py b/examples/adwords/v201809/shopping/add_smart_shopping_ad.py
new file mode 100755
index 00000000..ee740c77
--- /dev/null
+++ b/examples/adwords/v201809/shopping/add_smart_shopping_ad.py
@@ -0,0 +1,230 @@
+#!/usr/bin/env python
+#
+# Copyright 2018 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example adds a Smart Shopping campaign with an ad group and ad group ad.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+"""
+
+
+import uuid
+
+# Import appropriate modules from the client library.
+from googleads import adwords
+
+# If set to true, a default partition will be created.
+# Set it to false if you plan to run the add_product_partition_tree.py
+# example right after this example.
+CREATE_DEFAULT_PARTITION = False
+MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE'
+
+
+def main(client, merchant_id, create_default_partition):
+ budget_id = CreateBudget(client)
+ campaign_id = CreateSmartCampaign(client, budget_id, merchant_id)
+ ad_group_id = CreateSmartShoppingAdGroup(client, campaign_id)
+ CreateSmartShoppingAd(client, ad_group_id)
+
+ if create_default_partition:
+ CreateDefaultPartition(client, ad_group_id)
+
+
+def CreateBudget(client):
+ """Adds a new budget.
+
+ Args:
+ client: an AdWordsClient instance.
+ Returns:
+ A budget ID.
+ """
+ budget_service = client.GetService('BudgetService', version='v201809')
+
+ budget = {
+ 'name': 'Interplanetary budget #%s' % uuid.uuid4(),
+ 'amount': {
+ 'microAmount': '50000000'
+ },
+ 'deliveryMethod': 'STANDARD',
+ # Non-shared budgets are required for Smart Shopping campaigns.
+ 'isExplicitlyShared': False
+ }
+
+ budget_operations = [{
+ 'operator': 'ADD',
+ 'operand': budget
+ }]
+
+ # Add the budget.
+ budget_id = budget_service.mutate(budget_operations)['value'][0][
+ 'budgetId']
+
+ return budget_id
+
+
+def CreateSmartCampaign(client, budget_id, merchant_id):
+ """Adds a new Smart Shopping campaign.
+
+ 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 account to be associated with the
+ Shopping campaign.
+ Returns:
+ A campaign ID.
+ """
+ campaign_service = client.GetService('CampaignService', version='v201809')
+ # Create campaign with required and optional settings.
+ campaign = {
+ 'name': 'Shopping campaign #%s' % uuid.uuid4(),
+ # The advertisingChannelType is what makes this a Shopping campaign.
+ 'advertisingChannelType': 'SHOPPING',
+ # Sets the advertisingChannelSubType to SHOPPING_GOAL_OPTIMIZED_ADS to
+ # make this a Smart Shopping campaign.
+ 'advertisingChannelSubType': 'SHOPPING_GOAL_OPTIMIZED_ADS',
+ # Recommendation: Set the campaign to PAUSED when creating it to stop the
+ # ads from immediately serving. Set to ENABLED once you've added targeting
+ # and the ads are ready to serve.
+ 'status': 'PAUSED',
+ # Set portfolio budget (required).
+ 'budget': {'budgetId': budget_id},
+ # Set a bidding strategy. Only MAXIMIZE_CONVERSION_VALUE is supported.
+ 'biddingStrategyConfiguration': {
+ 'biddingStrategyType': 'MAXIMIZE_CONVERSION_VALUE'
+ },
+ 'settings': [{
+ # All Shopping campaigns need a ShoppingSetting.
+ 'xsi_type': 'ShoppingSetting',
+ 'salesCountry': 'US',
+ 'merchantId': merchant_id
+ }]
+ }
+
+ campaign_operations = [{
+ 'operator': 'ADD',
+ 'operand': campaign
+ }]
+
+ result = campaign_service.mutate(campaign_operations)['value'][0]
+
+ print('Smart Shopping campaign with name "%s" and ID "%s" was added.'
+ % (result['name'], result['id']))
+
+ return result['id']
+
+
+def CreateSmartShoppingAdGroup(client, campaign_id):
+ """Adds a new Smart Shopping ad group.
+
+ Args:
+ client: an AdWordsClient instance.
+ campaign_id: the str ID of a Smart Shopping campaign.
+ Returns:
+ An ad group ID.
+ """
+ ad_group_service = client.GetService('AdGroupService', version='v201809')
+ # Create the ad group.
+ ad_group = {
+ 'campaignId': campaign_id,
+ 'name': 'Smart Shopping ad group #%s' % uuid.uuid4(),
+ # Set the ad group type to SHOPPING_GOAL_OPTIMIZED_ADS.
+ 'adGroupType': 'SHOPPING_GOAL_OPTIMIZED_ADS'
+ }
+
+ adgroup_operations = {
+ 'operator': 'ADD',
+ 'operand': ad_group
+ }
+
+ # Make the mutate request to add the AdGroup to the Smart Shopping campaign.
+ ad_group = ad_group_service.mutate(adgroup_operations)['value'][0]
+ ad_group_id = ad_group['id']
+
+ print('AdGroup with name "%s" and ID "%s" was added.'
+ % (ad_group['name'], ad_group_id))
+
+ return ad_group_id
+
+
+def CreateSmartShoppingAd(client, ad_group_id):
+ """Adds a new Smart Shopping ad.
+
+ Args:
+ client: an AdWordsClient instance.
+ ad_group_id: an integer ID for an ad group.
+ """
+ ad_group_ad_service = client.GetService('AdGroupAdService', version='v201809')
+ # Create an AdGroup Ad.
+ adgroup_ad = {
+ 'adGroupId': ad_group_id,
+ # Create a Smart Shopping ad (Goal-optimized Shopping ad).
+ 'ad': {
+ 'xsi_type': 'GoalOptimizedShoppingAd'
+ }
+ }
+
+ ad_operation = {
+ 'operator': 'ADD',
+ 'operand': adgroup_ad
+ }
+
+ # Make the mutate request to add the Smart Shopping ad to the AdGroup.
+ ad_result = ad_group_ad_service.mutate([ad_operation])
+
+ for adgroup_ad in ad_result['value']:
+ print('Smart Shopping ad with ID "%s" was added.' % adgroup_ad['ad']['id'])
+
+
+def CreateDefaultPartition(client, ad_group_id):
+ """Creates a default partition.
+
+ Args:
+ client: an AdWordsClient instance.
+ ad_group_id: an integer ID for an ad group.
+ """
+ ad_group_criterion_service = client.GetService('AdGroupCriterionService',
+ version='v201809')
+
+ operations = [{
+ 'operator': 'ADD',
+ 'operand': {
+ 'xsi_type': 'BiddableAdGroupCriterion',
+ 'adGroupId': ad_group_id,
+ # Make sure that caseValue and parentCriterionId are left unspecified.
+ # This makes this partition as generic as possible to use as a
+ # fallback when others don't match.
+ 'criterion': {
+ 'xsi_type': 'ProductPartition',
+ 'partitionType': 'UNIT'
+ }
+ }
+ }]
+
+ ad_group_criterion = ad_group_criterion_service.mutate(operations)['value'][0]
+
+ print('Ad group criterion with ID "%d" in ad group with ID "%d" was added.'
+ % (ad_group_criterion['criterion']['id'],
+ ad_group_criterion['adGroupId']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, MERCHANT_ID, CREATE_DEFAULT_PARTITION)
diff --git a/examples/adwords/v201809/shopping/get_product_category_taxonomy.py b/examples/adwords/v201809/shopping/get_product_category_taxonomy.py
new file mode 100755
index 00000000..72269e34
--- /dev/null
+++ b/examples/adwords/v201809/shopping/get_product_category_taxonomy.py
@@ -0,0 +1,96 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example fetches the set of valid ProductBiddingCategories.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+
+# Import appropriate modules from the client library.
+from googleads import adwords
+
+
+def main(client):
+ service = client.GetService('ConstantDataService', version='v201809')
+
+ selector = {
+ 'predicates': [
+ {
+ 'field': 'Country',
+ 'operator': 'IN',
+ 'values': ['US']
+ }
+ ]
+ }
+
+ result = service.getProductBiddingCategoryData(selector)
+
+ bidding_categories = {}
+ root_categories = []
+
+ for product_bidding_category in result:
+ category_id = product_bidding_category['dimensionValue']['value']
+ parent_id = None
+ name = product_bidding_category['displayValue'][0]['value']
+
+ # Note: There may be cases where there isn't a value.
+ if ('parentDimensionValue' in product_bidding_category and
+ 'value' in product_bidding_category['parentDimensionValue']):
+ parent_id = product_bidding_category['parentDimensionValue']['value']
+
+ if category_id not in bidding_categories:
+ bidding_categories[category_id] = {}
+
+ category = bidding_categories[category_id]
+
+ if parent_id is not None:
+ if parent_id not in bidding_categories:
+ bidding_categories[parent_id] = {}
+
+ parent = bidding_categories[parent_id]
+
+ if 'children' not in parent:
+ parent['children'] = []
+
+ parent['children'].append(category)
+ else:
+ root_categories.append(category)
+
+ category['id'] = category_id
+ category['name'] = name
+
+ DisplayCategories(root_categories)
+
+
+def DisplayCategories(categories, prefix=''):
+ for category in categories:
+ print('%s%s [%s]' % (prefix, category['name'], category['id']))
+
+ if 'children' in category:
+ DisplayCategories(category['children'], '%s%s > ' % (prefix,
+ category['name']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client)
diff --git a/examples/adwords/v201809/targeting/__init__.py b/examples/adwords/v201809/targeting/__init__.py
new file mode 100644
index 00000000..f5595299
--- /dev/null
+++ b/examples/adwords/v201809/targeting/__init__.py
@@ -0,0 +1,15 @@
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Targeting examples."""
diff --git a/examples/adwords/v201809/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201809/targeting/add_campaign_targeting_criteria.py
new file mode 100755
index 00000000..1a6bf2ae
--- /dev/null
+++ b/examples/adwords/v201809/targeting/add_campaign_targeting_criteria.py
@@ -0,0 +1,126 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example adds various types of targeting criteria to a given campaign.
+
+To get campaigns, run get_campaigns.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from googleads import adwords
+
+
+CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
+# Replace the value below with the ID of a feed that has been configured for
+# location targeting, meaning it has an ENABLED FeedMapping with criterionType
+# of 77. Feeds linked to a GMB account automatically have this FeedMapping.
+# If you don't have such a feed, set this value to None.
+LOCATION_FEED_ID = 'INSERT_LOCATION_FEED_ID_HERE'
+
+
+def main(client, campaign_id, location_feed_id=None):
+ # Initialize appropriate service.
+ campaign_criterion_service = client.GetService(
+ 'CampaignCriterionService', version='v201809')
+
+ # Create locations. The IDs can be found in the documentation or retrieved
+ # with the LocationCriterionService.
+ california = {
+ 'xsi_type': 'Location',
+ 'id': '21137'
+ }
+ mexico = {
+ 'xsi_type': 'Location',
+ 'id': '2484'
+ }
+
+ # Create languages. The IDs can be found in the documentation or retrieved
+ # with the ConstantDataService.
+ english = {
+ 'xsi_type': 'Language',
+ 'id': '1000'
+ }
+ spanish = {
+ 'xsi_type': 'Language',
+ 'id': '1003'
+ }
+
+ # Create a negative campaign criterion operation.
+ negative_campaign_criterion_operand = {
+ 'xsi_type': 'NegativeCampaignCriterion',
+ 'campaignId': campaign_id,
+ 'criterion': {
+ 'xsi_type': 'Keyword',
+ 'matchType': 'BROAD',
+ 'text': 'jupiter cruise'
+ }
+ }
+ criteria = [california, mexico, english, spanish]
+ if location_feed_id:
+ # Distance targeting. Area of 10 miles around targets above.
+ criteria.append({
+ 'xsi_type': 'LocationGroups',
+ 'feedId': location_feed_id,
+ 'matchingFunction': {
+ 'operator': 'IDENTITY',
+ 'lhsOperand': [{
+ 'xsi_type': 'LocationExtensionOperand',
+ 'radius': {
+ 'xsi_type': 'ConstantOperand',
+ 'type': 'DOUBLE',
+ 'unit': 'MILES',
+ 'doubleValue': 10
+ }
+ }]
+ }
+ })
+ # Create operations
+ operations = []
+ for criterion in criteria:
+ operations.append({
+ 'operator': 'ADD',
+ 'operand': {
+ 'campaignId': campaign_id,
+ 'criterion': criterion
+ }
+ })
+ # Add the negative campaign criterion.
+ operations.append({
+ 'operator': 'ADD',
+ 'operand': negative_campaign_criterion_operand
+ })
+
+ # Make the mutate request.
+ result = campaign_criterion_service.mutate(operations)
+
+ # Display the resulting campaign criteria.
+ for campaign_criterion in result['value']:
+ print('Campaign criterion with campaign id "%s", criterion id "%s", '
+ 'and type "%s" was added.'
+ % (campaign_criterion['campaignId'],
+ campaign_criterion['criterion']['id'],
+ campaign_criterion['criterion']['type']))
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, CAMPAIGN_ID, LOCATION_FEED_ID)
diff --git a/examples/adwords/v201809/targeting/add_customer_negative_criteria.py b/examples/adwords/v201809/targeting/add_customer_negative_criteria.py
new file mode 100755
index 00000000..b69d71c8
--- /dev/null
+++ b/examples/adwords/v201809/targeting/add_customer_negative_criteria.py
@@ -0,0 +1,74 @@
+#!/usr/bin/env python
+#
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example adds various types of negative criteria to a customer.
+
+These criteria will be applied to all campaigns for the customer.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from googleads import adwords
+
+
+def main(client):
+ # Initialize appropriate service.
+ customer_negative_criterion_service = client.GetService(
+ 'CustomerNegativeCriterionService', version='v201809')
+
+ criteria = [
+ # Exclude tragedy & conflict content.
+ {
+ 'xsi_type': 'ContentLabel',
+ 'contentLabelType': 'TRAGEDY'
+ },
+ # Exclude a specific placement.
+ {
+ 'xsi_type': 'Placement',
+ 'url': 'http://www.example.com'
+ }
+ # Additional criteria types are available for this service. See the types
+ # listed under Criterion here:
+ # https://developers.google.com/adwords/api/docs/reference/latest/CustomerNegativeCriterionService.Criterion
+ ]
+
+ # Create operations to add each of the criteria above.
+ operations = [{
+ 'operator': 'ADD',
+ 'operand': {
+ 'criterion': criterion
+ }
+ } for criterion in criteria]
+
+ # Make the mutate request.
+ result = customer_negative_criterion_service.mutate(operations)
+
+ # Display the resulting campaign criteria.
+ for negative_criterion in result['value']:
+ print('Customer negative criterion with criterion ID "%s", and type "%s" '
+ 'was added.' % (negative_criterion['criterion']['id'],
+ negative_criterion['criterion']['type']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client)
diff --git a/examples/adwords/v201809/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201809/targeting/add_demographic_targeting_criteria.py
new file mode 100755
index 00000000..101495e7
--- /dev/null
+++ b/examples/adwords/v201809/targeting/add_demographic_targeting_criteria.py
@@ -0,0 +1,96 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example adds demographic criteria to an ad group.
+
+To get a list of ad groups, run get_ad_groups.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from googleads import adwords
+
+
+GENDER_MALE = '10'
+AGE_RANGE_UNDETERMINED = '503999'
+
+AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
+
+
+def main(client, ad_group_id):
+ # Initialize appropriate service.
+ ad_group_criterion_service = client.GetService(
+ 'AdGroupCriterionService', version='v201809')
+
+ # Create the ad group criteria.
+ ad_group_criteria = [
+ # Targeting criterion.
+ {
+ 'xsi_type': 'BiddableAdGroupCriterion',
+ 'adGroupId': ad_group_id,
+ 'criterion': {
+ 'xsi_type': 'Gender',
+ # Create gender criteria. The IDs can be found in the
+ # documentation:
+ # https://developers.google.com/adwords/api/docs/appendix/genders.
+ 'id': GENDER_MALE
+ }
+ },
+ # Exclusion criterion.
+ {
+ 'xsi_type': 'NegativeAdGroupCriterion',
+ 'adGroupId': ad_group_id,
+ 'criterion': {
+ 'xsi_type': 'AgeRange',
+ # Create age range criteria. The IDs can be found in the
+ # documentation:
+ # https://developers.google.com/adwords/api/docs/appendix/ages.
+ 'id': AGE_RANGE_UNDETERMINED
+ }
+ }
+ ]
+
+ # Create operations.
+ operations = []
+ for criterion in ad_group_criteria:
+ operations.append({
+ 'operator': 'ADD',
+ 'operand': criterion
+ })
+
+ response = ad_group_criterion_service.mutate(operations)
+
+ if response and response['value']:
+ criteria = response['value']
+ for ad_group_criterion in criteria:
+ criterion = ad_group_criterion['criterion']
+ print('Ad group criterion with ad group ID %s, criterion ID %s and '
+ 'type "%s" was added.' %
+ (ad_group_criterion['adGroupId'], criterion['id'],
+ criterion['type']))
+ else:
+ print('No criteria were returned.')
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adwords/v201809/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201809/targeting/get_campaign_targeting_criteria.py
new file mode 100755
index 00000000..0e80b412
--- /dev/null
+++ b/examples/adwords/v201809/targeting/get_campaign_targeting_criteria.py
@@ -0,0 +1,85 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example illustrates how to retrieve all the campaign targets.
+
+To set campaign targets, run add_campaign_targeting_criteria.py.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from googleads import adwords
+
+
+PAGE_SIZE = 500
+
+
+def main(client):
+ # Initialize appropriate service.
+ campaign_criterion_service = client.GetService(
+ 'CampaignCriterionService', version='v201809')
+
+ # Construct selector and get all campaign targets.
+ offset = 0
+ selector = {
+ 'fields': ['CampaignId', 'Id', 'CriteriaType', 'PlatformName',
+ 'LanguageName', 'LocationName', 'KeywordText'],
+ 'predicates': [{
+ 'field': 'CriteriaType',
+ 'operator': 'IN',
+ 'values': ['KEYWORD', 'LANGUAGE', 'LOCATION', 'PLATFORM']
+ }],
+ 'paging': {
+ 'startIndex': str(offset),
+ 'numberResults': str(PAGE_SIZE)
+ }
+ }
+ more_pages = True
+ while more_pages:
+ page = campaign_criterion_service.get(selector)
+
+ # Display results.
+ if 'entries' in page:
+ for campaign_criterion in page['entries']:
+ negative = ''
+ if (campaign_criterion['CampaignCriterion.Type']
+ == 'NegativeCampaignCriterion'):
+ negative = 'Negative '
+ criterion = campaign_criterion['criterion']
+ criteria = (criterion['text'] if 'text' in criterion else
+ criterion['platformName'] if 'platformName' in criterion
+ else criterion['name'] if 'name' in criterion else
+ criterion['locationName'] if 'locationName' in criterion
+ else None)
+ print('%sCampaign Criterion found for Campaign ID %s with type %s and '
+ 'criteria "%s".' % (negative, campaign_criterion['campaignId'],
+ criterion['type'], criteria))
+ else:
+ print('No campaign targets were found.')
+ offset += PAGE_SIZE
+ selector['paging']['startIndex'] = str(offset)
+ more_pages = offset < int(page['totalNumEntries'])
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client)
diff --git a/examples/adwords/v201809/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201809/targeting/get_targetable_languages_and_carriers.py
new file mode 100755
index 00000000..f5f7c519
--- /dev/null
+++ b/examples/adwords/v201809/targeting/get_targetable_languages_and_carriers.py
@@ -0,0 +1,57 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Retrieves all languages and carriers available for targeting.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from googleads import adwords
+
+
+def main(client):
+ # Initialize appropriate service.
+ constant_data_service = client.GetService(
+ 'ConstantDataService', version='v201809')
+
+ # Get all languages.
+ languages = constant_data_service.getLanguageCriterion()
+
+ # Display results.
+ for language in languages:
+ print('Language with name "%s" and ID "%s" was found.'
+ % (language['name'], language['id']))
+
+ # Get all carriers.
+ carriers = constant_data_service.getCarrierCriterion()
+
+ # Display results.
+ for carrier in carriers:
+ print('Carrier with name "%s", ID "%s", and country code "%s" was '
+ 'found.' % (
+ carrier['name'], carrier['id'],
+ getattr(carrier, 'countryCode', 'N/A')))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client)
diff --git a/examples/adwords/v201809/targeting/lookup_location.py b/examples/adwords/v201809/targeting/lookup_location.py
new file mode 100755
index 00000000..0270526d
--- /dev/null
+++ b/examples/adwords/v201809/targeting/lookup_location.py
@@ -0,0 +1,82 @@
+#!/usr/bin/env python
+#
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This example gets all LocationCriterion.
+
+The LoadFromStorage method is pulling credentials and properties from a
+"googleads.yaml" file. By default, it looks for this file in your home
+directory. For more information, see the "Caching authentication information"
+section of our README.
+
+"""
+
+from googleads import adwords
+
+
+def GetLocationString(location):
+ return '%s (%s)' % (location['locationName'], location['displayType']
+ if 'displayType' in location else None)
+
+
+def main(client):
+ # Initialize appropriate service.
+ location_criterion_service = client.GetService(
+ 'LocationCriterionService', version='v201809')
+
+ location_names = ['Paris', 'Quebec', 'Spain', 'Deutschland']
+
+ # Create the selector.
+ selector = {
+ 'fields': ['Id', 'LocationName', 'DisplayType', 'CanonicalName',
+ 'ParentLocations', 'Reach', 'TargetingStatus'],
+ 'predicates': [{
+ 'field': 'LocationName',
+ 'operator': 'IN',
+ 'values': location_names
+ }, {
+ 'field': 'Locale',
+ 'operator': 'EQUALS',
+ 'values': ['en']
+ }]
+ }
+
+ # Make the get request.
+ location_criteria = location_criterion_service.get(selector)
+
+ # Display the resulting location criteria.
+ for location_criterion in location_criteria:
+ parent_string = ''
+ if ('parentLocations' in location_criterion['location']
+ and location_criterion['location']['parentLocations']):
+ parent_string = ', '.join([GetLocationString(parent)for parent in
+ location_criterion['location']
+ ['parentLocations']])
+ print('The search term "%s" returned the location "%s" of type "%s"'
+ ' with parent locations "%s", reach "%s" and id "%s" (%s)'
+ % (location_criterion['searchTerm'],
+ location_criterion['location']['locationName'],
+ location_criterion['location']['displayType'], parent_string,
+ location_criterion['reach']
+ if 'reach' in location_criterion else None,
+ location_criterion['location']['id'],
+ location_criterion['location']['targetingStatus']))
+
+
+if __name__ == '__main__':
+ # Initialize client object.
+ adwords_client = adwords.AdWordsClient.LoadFromStorage()
+
+ main(adwords_client)
diff --git a/examples/adxbuyer/v201406/__init__.py b/examples/adxbuyer/v201406/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/examples/adxbuyer/v201406/basic_operations/__init__.py b/examples/adxbuyer/v201406/basic_operations/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/examples/adxbuyer/v201406/basic_operations/add_ad_groups.py b/examples/adxbuyer/v201406/basic_operations/add_ad_groups.py
deleted file mode 100755
index fa9da495..00000000
--- a/examples/adxbuyer/v201406/basic_operations/add_ad_groups.py
+++ /dev/null
@@ -1,91 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2013 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds ad groups to a given campaign.
-
-To get ad groups, run get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupService.mutate
-"""
-
-__author__ = 'api.kwinter@gmail.com (Kevin Winter)'
-
-import uuid
-
-from googleads import adwords
-
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-
-
-def main(client, campaign_id):
- # Initialize appropriate service.
- ad_group_service = client.GetService('AdGroupService', version='v201406')
-
- # Construct operations and add ad groups.
- operations = [{
- 'operator': 'ADD',
- 'operand': {
- 'campaignId': campaign_id,
- 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(),
- 'status': 'ENABLED',
- 'biddingStrategyConfiguration': {
- 'bids': [
- {
- 'xsi_type': 'CpmBid',
- 'bid': {
- 'microAmount': '1000000'
- },
- }
- ]
- }
- }
- }, {
- 'operator': 'ADD',
- 'operand': {
- 'campaignId': campaign_id,
- 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(),
- 'status': 'ENABLED',
- 'biddingStrategyConfiguration': {
- 'bids': [
- {
- 'xsi_type': 'CpmBid',
- 'bid': {
- 'microAmount': '1000000'
- },
- }
- ]
- }
- }
- }]
- ad_groups = ad_group_service.mutate(operations)
-
- # Display results.
- for ad_group in ad_groups['value']:
- print ('Ad group with name \'%s\' and id \'%s\' was added.'
- % (ad_group['name'], ad_group['id']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adxbuyer/v201406/basic_operations/add_campaigns.py b/examples/adxbuyer/v201406/basic_operations/add_campaigns.py
deleted file mode 100755
index 566c05cc..00000000
--- a/examples/adxbuyer/v201406/basic_operations/add_campaigns.py
+++ /dev/null
@@ -1,129 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2013 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds campaigns. To get campaigns, run get_campaigns.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignService.mutate
-Tags: BudgetService.mutate
-"""
-
-__author__ = 'api.kwinter@gmail.com (Kevin Winter)'
-
-import datetime
-import uuid
-
-from googleads import adwords
-
-
-def main(client):
- # Initialize appropriate service.
- campaign_service = client.GetService('CampaignService', version='v201406')
- budget_service = client.GetService('BudgetService', version='v201406')
-
- # Create a budget, which can be shared by multiple campaigns.
- budget = {
- 'name': 'Interplanetary budget #%s' % uuid.uuid4(),
- 'amount': {
- 'microAmount': '50000000'
- },
- 'deliveryMethod': 'STANDARD',
- 'period': 'DAILY'
- }
-
- budget_operations = [{
- 'operator': 'ADD',
- 'operand': budget
- }]
-
- # Add the budget.
- budget_id = budget_service.mutate(budget_operations)['value'][0][
- 'budgetId']
-
- # Construct operations and add campaigns.
- operations = [{
- 'operator': 'ADD',
- 'operand': {
- 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(),
- 'status': 'PAUSED',
- 'advertisingChannelType': 'DISPLAY',
- 'biddingStrategyConfiguration': {
- 'biddingStrategyType': 'MANUAL_CPM',
- },
- 'endDate': (datetime.datetime.now() +
- datetime.timedelta(365)).strftime('%Y%m%d'),
- # Note that only the budgetId is required
- 'budget': {
- 'budgetId': budget_id
- },
- 'settings': [{
- 'xsi_type': 'RealTimeBiddingSetting',
- 'optIn': 'true'
- }, {
- 'xsi_type': 'KeywordMatchSetting',
- 'optIn': 'false'
- }],
- # Optional fields
- 'startDate': (datetime.datetime.now() +
- datetime.timedelta(1)).strftime('%Y%m%d'),
- 'adServingOptimizationStatus': 'ROTATE',
- 'frequencyCap': {
- 'impressions': '5',
- 'timeUnit': 'DAY',
- 'level': 'ADGROUP'
- }
- }
- }, {
- 'operator': 'ADD',
- 'operand': {
- 'name': 'Interplanetary Cruise Banners #%s' % uuid.uuid4(),
- 'status': 'PAUSED',
- 'advertisingChannelType': 'DISPLAY',
- 'biddingStrategyConfiguration': {
- 'biddingStrategyType': 'MANUAL_CPM',
- },
- 'endDate': (datetime.datetime.now() +
- datetime.timedelta(365)).strftime('%Y%m%d'),
- # Note that only the budgetId is required
- 'budget': {
- 'budgetId': budget_id
- },
- 'settings': [{
- 'xsi_type': 'RealTimeBiddingSetting',
- 'optIn': 'true'
- }, {
- 'xsi_type': 'KeywordMatchSetting',
- 'optIn': 'false'
- }],
- }
- }]
- campaigns = campaign_service.mutate(operations)
-
- # Display results.
- for campaign in campaigns['value']:
- print ('Campaign with name \'%s\' and id \'%s\' was added.'
- % (campaign['name'], campaign['id']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adxbuyer/v201406/basic_operations/add_placements.py b/examples/adxbuyer/v201406/basic_operations/add_placements.py
deleted file mode 100755
index 0f3f7bc0..00000000
--- a/examples/adxbuyer/v201406/basic_operations/add_placements.py
+++ /dev/null
@@ -1,90 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2013 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds ad group criteria to an ad group.
-
-To get ad groups, run get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupCriterionService.mutate
-"""
-
-__author__ = 'api.kwinter@gmail.com (Kevin Winter)'
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Initialize appropriate service.
- ad_group_criterion_service = client.GetService(
- 'AdGroupCriterionService', version='v201406')
-
- # Construct keyword ad group criterion object.
- placement1 = {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Placement',
- 'url': 'http://mars.google.com'
- },
- # These fields are optional.
- 'userStatus': 'PAUSED',
- 'destinationUrl': 'http://example.com/mars'
- }
-
- placement2 = {
- 'xsi_type': 'NegativeAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Placement',
- 'url': 'http://example.com/pluto'
- },
- }
-
- # Construct operations and add ad group criteria.
- operations = [
- {
- 'operator': 'ADD',
- 'operand': placement1
- },
- {
- 'operator': 'ADD',
- 'operand': placement2
- }
- ]
- ad_group_criteria = ad_group_criterion_service.mutate(
- operations)['value']
-
- # Display results.
- for criterion in ad_group_criteria:
- print ('Placement ad group criterion with ad group id \'%s\', criterion '
- 'id \'%s\', and url \'%s\' was added.'
- % (criterion['adGroupId'], criterion['criterion']['id'],
- criterion['criterion']['url']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adxbuyer/v201406/basic_operations/add_third_party_redirect_ad.py b/examples/adxbuyer/v201406/basic_operations/add_third_party_redirect_ad.py
deleted file mode 100755
index e9f55258..00000000
--- a/examples/adxbuyer/v201406/basic_operations/add_third_party_redirect_ad.py
+++ /dev/null
@@ -1,102 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2013 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds several third party ads to a given ad group.
-
-To get an ad_group_id, run get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupAdService.mutate
-"""
-
-__author__ = 'api.kwinter@gmail.com (Kevin Winter)'
-
-import uuid
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Initialize appropriate service.
- ad_group_ad_service = client.GetService('AdGroupAdService', version='v201406')
-
- # Construct operations and add ads.
- operations = [
- {
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'AdGroupAd',
- 'adGroupId': ad_group_id,
- 'ad': {
- 'xsi_type': 'ThirdPartyRedirectAd',
- 'name': 'Example third party ad #%s' % uuid.uuid4(),
- 'url': 'http://www.example.com',
- 'dimensions': {
- 'width': '300',
- 'height': '250'
- },
- # This field normally contains the javascript ad tag.
- 'snippet': (''),
- 'certifiedVendorFormatId': '232',
- 'isCookieTargeted': 'false',
- 'isUserInterestTargeted': 'false',
- 'isTagged': 'false',
- 'richMediaAdType': 'STANDARD',
- 'expandingDirections': ['EXPANDING_UP', 'EXPANDING_DOWN'],
- 'adAttributes': ['ROLL_OVER_TO_EXPAND']
- }
- }
- },
- {
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'AdGroupAd',
- 'adGroupId': ad_group_id,
- 'ad': {
- 'xsi_type': 'ThirdPartyRedirectAd',
- 'name': 'Example third party ad #%s' % uuid.uuid4(),
- 'url': 'http://www.example.com',
- 'adDuration': '15000',
- 'sourceUrl': ('http://ad.doubleclick.net/pfadx/N270.126913.'
- '6102203221521/B3876671.21;dcadv=2215309;'
- 'sz=0x0;ord=%5btimestamp%5d;dcmt=text/xml'),
- 'certifiedVendorFormatId': '303',
- 'richMediaAdType': 'IN_STREAM_VIDEO'
- }
- }
- }
- ]
- ads = ad_group_ad_service.mutate(operations)
-
- # Display results.
- for ad in ads['value']:
- print ('Ad with ID \'%s\' and of type \'%s\' was added.'
- % (ad['ad']['id'], ad['ad']['Ad.Type']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adxbuyer/v201406/basic_operations/get_placements.py b/examples/adxbuyer/v201406/basic_operations/get_placements.py
deleted file mode 100755
index 2d4c4bd4..00000000
--- a/examples/adxbuyer/v201406/basic_operations/get_placements.py
+++ /dev/null
@@ -1,78 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2013 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all ad group criteria in an account.
-
-To add placements, run add_placements.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupCriterionService.get
-"""
-
-__author__ = 'api.kwinter@gmail.com (Kevin Winter)'
-
-from googleads import adwords
-
-
-PAGE_SIZE = 500
-
-
-def main(client):
- # Initialize appropriate service.
- ad_group_criterion_service = client.GetService(
- 'AdGroupCriterionService', version='v201406')
-
- # Construct selector and get all ad group criteria.
- offset = 0
- selector = {
- 'fields': ['AdGroupId', 'Id', 'PlacementUrl'],
- 'predicates': [{
- 'field': 'CriteriaType',
- 'operator': 'EQUALS',
- 'values': ['PLACEMENT']
- }],
- 'paging': {
- 'startIndex': str(offset),
- 'numberResults': str(PAGE_SIZE)
- }
- }
- more_pages = True
- while more_pages:
- page = ad_group_criterion_service.get(selector)
-
- # Display results.
- if 'entries' in page:
- for criterion in page['entries']:
- print ('Placement ad group criterion with ad group id \'%s\', '
- 'criterion id \'%s\' and url \'%s\'.'
- % (criterion['adGroupId'], criterion['criterion']['id'],
- criterion['criterion']['url']))
- else:
- print 'No placements were found.'
- offset += PAGE_SIZE
- selector['paging']['startIndex'] = str(offset)
- more_pages = offset < int(page['totalNumEntries'])
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adxbuyer/v201406/basic_operations/get_third_party_redirect_ads.py b/examples/adxbuyer/v201406/basic_operations/get_third_party_redirect_ads.py
deleted file mode 100755
index 1d865860..00000000
--- a/examples/adxbuyer/v201406/basic_operations/get_third_party_redirect_ads.py
+++ /dev/null
@@ -1,83 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2013 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all third party ads for a given ad group.
-
-To add a third party ad, add_third_party_redirect_ad.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupAdService.get
-"""
-
-__author__ = 'api.kwinter@gmail.com (Kevin Winter)'
-
-from googleads import adwords
-
-
-PAGE_SIZE = 500
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Initialize appropriate service.
- ad_group_ad_service = client.GetService('AdGroupAdService', version='v201406')
-
- # Construct selector and get all ads for a given ad group.
- offset = 0
- selector = {
- 'fields': ['Id', 'AdGroupId', 'Status'],
- 'predicates': [
- {
- 'field': 'AdGroupId',
- 'operator': 'EQUALS',
- 'values': [ad_group_id]
- },
- {
- 'field': 'AdType',
- 'operator': 'EQUALS',
- 'values': ['THIRD_PARTY_REDIRECT_AD']
- }
- ],
- 'paging': {
- 'startIndex': str(offset),
- 'numberResults': str(PAGE_SIZE)
- }
- }
- more_pages = True
- while more_pages:
- page = ad_group_ad_service.get(selector)
-
- # Display results.
- if 'entries' in page:
- for ad in page['entries']:
- print ('Ad with id \'%s\', status \'%s\', and of type \'%s\' was found.'
- % (ad['ad']['id'], ad['status'], ad['ad']['Ad.Type']))
- else:
- print 'No ads were found.'
- offset += PAGE_SIZE
- selector['paging']['startIndex'] = str(offset)
- more_pages = offset < int(page['totalNumEntries'])
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adxbuyer/v201406/basic_operations/remove_placement.py b/examples/adxbuyer/v201406/basic_operations/remove_placement.py
deleted file mode 100755
index 2d9cd989..00000000
--- a/examples/adxbuyer/v201406/basic_operations/remove_placement.py
+++ /dev/null
@@ -1,71 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2013 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example deletes an ad group criterion using the 'REMOVE' operator.
-
-To get ad group criteria, run get_placements.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupCriterionService.mutate
-"""
-
-__author__ = 'api.kwinter@gmail.com (Kevin Winter)'
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-CRITERION_ID = 'INSERT_CRITERION_ID_HERE'
-
-
-def main(client, ad_group_id, criterion_id):
- # Initialize appropriate service.
- ad_group_criterion_service = client.GetService(
- 'AdGroupCriterionService', version='v201406')
-
- # Construct operations and delete ad group criteria.
- operations = [
- {
- 'operator': 'REMOVE',
- 'operand': {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Placement',
- 'id': criterion_id
- }
- }
- }
- ]
- result = ad_group_criterion_service.mutate(operations)
-
- # Display results.
- for criterion in result['value']:
- print ('Ad group criterion with ad group id \'%s\', criterion id \'%s\', '
- 'and type \'%s\' was deleted.'
- % (criterion['adGroupId'], criterion['criterion']['id'],
- criterion['criterion']['Criterion.Type']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID, CRITERION_ID)
diff --git a/examples/adxbuyer/v201406/basic_operations/update_placement.py b/examples/adxbuyer/v201406/basic_operations/update_placement.py
deleted file mode 100755
index 3cfd2935..00000000
--- a/examples/adxbuyer/v201406/basic_operations/update_placement.py
+++ /dev/null
@@ -1,83 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2013 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates the bid of a placement.
-
-To add a placement, run add_placements.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupCriterionService.mutate
-"""
-
-__author__ = 'api.kwinter@gmail.com (Kevin Winter)'
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-CRITERION_ID = 'INSERT_PLACEMENT_CRITERION_ID_HERE'
-
-
-def main(client, ad_group_id, criterion_id):
- # Initialize appropriate service.
- ad_group_criterion_service = client.GetService(
- 'AdGroupCriterionService', version='v201406')
-
- # Construct operations and update bids.
- operations = [{
- 'operator': 'SET',
- 'operand': {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Placement',
- 'id': criterion_id,
- },
- 'biddingStrategyConfiguration': {
- 'bids': [
- {
- 'xsi_type': 'CpmBid',
- 'bid': {
- 'microAmount': '1000000'
- },
- }
- ]
- }
- }
- }]
- ad_group_criteria = ad_group_criterion_service.mutate(operations)
-
- # Display results.
- if 'value' in ad_group_criteria:
- for criterion in ad_group_criteria['value']:
- if criterion['criterion']['Criterion.Type'] == 'Keyword':
- print ('Ad group criterion with ad group id \'%s\' and criterion id '
- '\'%s\' had its bid set to \'%s\'.'
- % (criterion['adGroupId'], criterion['criterion']['id'],
- criterion['bids']['maxCpc']['amount']['microAmount']))
- else:
- print 'No ad group criteria were updated.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID, CRITERION_ID)
diff --git a/examples/adxbuyer/v201406/campaign_management/__init__.py b/examples/adxbuyer/v201406/campaign_management/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/examples/adxbuyer/v201406/campaign_management/add_placements_in_bulk.py b/examples/adxbuyer/v201406/campaign_management/add_placements_in_bulk.py
deleted file mode 100755
index eff4095d..00000000
--- a/examples/adxbuyer/v201406/campaign_management/add_placements_in_bulk.py
+++ /dev/null
@@ -1,138 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2013 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Illustrates how to perform asynchronous requests using the MutateJobService.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: MutateJobService.mutate
-Tags: MutateJobService.get
-Tags: MutateJobService.getResult
-"""
-
-__author__ = 'api.kwinter@gmail.com (Kevin Winter)'
-
-import random
-import re
-import time
-
-from googleads import adwords
-from googleads import errors
-
-
-RETRY_INTERVAL = 10
-RETRIES_COUNT = 30
-PLACEMENT_NUMBER = 100
-INDEX_REGEX = r'operations\[(\d+)\].operand'
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Initialize appropriate service.
- mutate_job_service = client.GetService('MutateJobService', version='v201406')
-
- # Create list of all operations for the job.
- operations = []
-
- # Create AdGroupCriterionOperations to add placements.
- for i in range(PLACEMENT_NUMBER):
- url = 'www.example.com/mars%d' % i
- if random.randint(1, 10) == 1:
- url = 'NOT_@_URL'
- operations.append({
- 'xsi_type': 'AdGroupCriterionOperation',
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Placement',
- 'url': url
- }
- }
- })
-
- # You can specify up to 3 job IDs that must successfully complete before
- # this job can be processed.
- policy = {
- 'prerequisiteJobIds': []
- }
-
- # Call mutate to create a new job.
- response = mutate_job_service.mutate(operations, policy)
-
- if not response:
- raise errors.GoogleAdsError('Failed to submit a job; aborting.')
-
- job_id = response['id']
- print 'Job with ID %s was successfully created.' % job_id
-
- # Create selector to retrieve job status and wait for it to complete.
- selector = {
- 'xsi_type': 'BulkMutateJobSelector',
- 'jobIds': [job_id]
- }
-
- time.sleep(RETRY_INTERVAL)
- # Poll for job status until it's finished.
- print 'Retrieving job status...'
- for i in range(RETRIES_COUNT):
- job_status_response = mutate_job_service.get(selector)
- status = job_status_response[0]['status']
- if status in ('COMPLETED', 'FAILED'):
- break
- print ('[%d] Current status is \'%s\', waiting %d seconds to retry...' %
- (i, status, RETRY_INTERVAL))
- time.sleep(RETRY_INTERVAL)
-
- if status == 'FAILED':
- raise errors.GoogleAdsError('Job failed with reason: \'%s\'' %
- job_status_response[0]['failure_reason'])
- if status in ('PROCESSING', 'PENDING'):
- raise errors.GoogleAdsError('Job did not complete within %d seconds' %
- (RETRY_INTERVAL * (RETRIES_COUNT - 1)))
-
- # Status must be COMPLETED.
- # Get the job result. Here we re-use the same selector.
- result_response = mutate_job_service.getResult(selector)
-
- # Output results.
- index = 0
- for result in result_response['SimpleMutateResult']['results']:
- if 'PlaceHolder' in result:
- print 'Operation [%d] - FAILED' % index
- else:
- print 'Operation [%d] - SUCCEEDED' % index
- index += 1
-
- # Output errors
- for error in result_response['SimpleMutateResult']['errors']:
- index = int(re.search(INDEX_REGEX, error['fieldPath']).group(1))
- reason = error['reason']
- url = operations[index]['operand']['criterion']['url']
- print ('ERROR - placement \'%s\' failed due to \'%s\'' %
- (url, reason))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adxbuyer/v201406/error_handling/__init__.py b/examples/adxbuyer/v201406/error_handling/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/examples/adxbuyer/v201406/error_handling/handle_partial_failures.py b/examples/adxbuyer/v201406/error_handling/handle_partial_failures.py
deleted file mode 100755
index 7fd16a96..00000000
--- a/examples/adxbuyer/v201406/error_handling/handle_partial_failures.py
+++ /dev/null
@@ -1,117 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2013 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example demonstrates how to handle partial failures.
-
-To get ad groups, run get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupCriterionService.mutate
-"""
-
-__author__ = 'api.kwinter@gmail.com (Kevin Winter)'
-
-import re
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Enable partial failure.
- client.partial_failure = True
-
- # Initialize appropriate service.
- ad_group_criterion_service = client.GetService(
- 'AdGroupCriterionService', version='v201406')
-
- # Construct placement ad group criteria objects.
- placements = [
- {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Placement',
- 'url': 'www.example.com/something'
- }
- },
- {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Placement',
- 'url': 'INVALID!!_URL'
- }
- },
- {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Placement',
- 'url': 'www.example.com/somethingelse'
- }
- },
- {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Placement',
- 'url': 'BAD!!_URL'
- }
- }
- ]
-
- # Construct operations and add ad group criteria.
- operations = []
- for placement in placements:
- operations.append(
- {
- 'operator': 'ADD',
- 'operand': placement
- })
- result = ad_group_criterion_service.mutate(operations)
-
- # Display results.
- for criterion in result['value']:
- if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion':
- print ('Added placement ad group criterion with ad group id \'%s\', '
- 'criterion id \'%s\' and url \'%s\''
- % (criterion['adGroupId'], criterion['criterion']['id'],
- criterion['criterion']['url']))
-
- for error in result['partialFailureErrors']:
- index = re.findall(r'operations\[(.*)\]\.', error['fieldPath'])
- if index:
- print ('Placement ad group criterion with ad group id \'%s\' and url '
- '\'%s\' triggered a failure for the following reason: \'%s\'.'
- % (placements[int(index[0])]['adGroupId'],
- placements[int(index[0])]['criterion']['url'],
- error['errorString']))
- else:
- print 'The following failure has occurred: \'%s\'.' % error['errorString']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adxbuyer/v201406/optimization/__init__.py b/examples/adxbuyer/v201406/optimization/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/examples/adxbuyer/v201406/optimization/get_placement_ideas.py b/examples/adxbuyer/v201406/optimization/get_placement_ideas.py
deleted file mode 100755
index 6ee5ff13..00000000
--- a/examples/adxbuyer/v201406/optimization/get_placement_ideas.py
+++ /dev/null
@@ -1,80 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2013 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example retrieves placements that are related to a given placement.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: TargetingIdeaService.get
-"""
-
-__author__ = 'api.kwinter@gmail.com (Kevin Winter)'
-
-from googleads import adwords
-
-
-PAGE_SIZE = 100
-
-
-def main(client):
- # Initialize appropriate service.
- targeting_idea_service = client.GetService(
- 'TargetingIdeaService', version='v201406')
-
- # Construct selector object and retrieve related placements.
- offset = 0
- url = 'mars.google.com'
- selector = {
- 'searchParameters': [{
- 'xsi_type': 'RelatedToUrlSearchParameter',
- 'urls': [url]
- }],
- 'ideaType': 'PLACEMENT',
- 'requestType': 'IDEAS',
- 'requestedAttributeTypes': ['CRITERION'],
- 'paging': {
- 'startIndex': str(offset),
- 'numberResults': str(PAGE_SIZE)
- }
- }
- more_pages = True
- while more_pages:
- page = targeting_idea_service.get(selector)
-
- # Display results.
- if 'entries' in page:
- for result in page['entries']:
- result = result['data'][0]['value']
- print ('Placement with url \'%s\' was found.'
- % (result['value']['url']))
- print
- print ('Total placements found related to \'%s\': %s'
- % (url, page['totalNumEntries']))
- else:
- print 'No placements found related to \'%s\'.' % url
- offset += PAGE_SIZE
- selector['paging']['startIndex'] = str(offset)
- more_pages = offset < int(page['totalNumEntries'])
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adxbuyer/v201409/__init__.py b/examples/adxbuyer/v201409/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/examples/adxbuyer/v201409/basic_operations/__init__.py b/examples/adxbuyer/v201409/basic_operations/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/examples/adxbuyer/v201409/basic_operations/add_ad_groups.py b/examples/adxbuyer/v201409/basic_operations/add_ad_groups.py
deleted file mode 100755
index 187d2596..00000000
--- a/examples/adxbuyer/v201409/basic_operations/add_ad_groups.py
+++ /dev/null
@@ -1,91 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2013 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds ad groups to a given campaign.
-
-To get ad groups, run get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupService.mutate
-"""
-
-__author__ = 'api.kwinter@gmail.com (Kevin Winter)'
-
-import uuid
-
-from googleads import adwords
-
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-
-
-def main(client, campaign_id):
- # Initialize appropriate service.
- ad_group_service = client.GetService('AdGroupService', version='v201409')
-
- # Construct operations and add ad groups.
- operations = [{
- 'operator': 'ADD',
- 'operand': {
- 'campaignId': campaign_id,
- 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(),
- 'status': 'ENABLED',
- 'biddingStrategyConfiguration': {
- 'bids': [
- {
- 'xsi_type': 'CpmBid',
- 'bid': {
- 'microAmount': '1000000'
- },
- }
- ]
- }
- }
- }, {
- 'operator': 'ADD',
- 'operand': {
- 'campaignId': campaign_id,
- 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(),
- 'status': 'ENABLED',
- 'biddingStrategyConfiguration': {
- 'bids': [
- {
- 'xsi_type': 'CpmBid',
- 'bid': {
- 'microAmount': '1000000'
- },
- }
- ]
- }
- }
- }]
- ad_groups = ad_group_service.mutate(operations)
-
- # Display results.
- for ad_group in ad_groups['value']:
- print ('Ad group with name \'%s\' and id \'%s\' was added.'
- % (ad_group['name'], ad_group['id']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adxbuyer/v201409/basic_operations/add_campaigns.py b/examples/adxbuyer/v201409/basic_operations/add_campaigns.py
deleted file mode 100755
index d2ddd0dd..00000000
--- a/examples/adxbuyer/v201409/basic_operations/add_campaigns.py
+++ /dev/null
@@ -1,123 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2013 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds campaigns. To get campaigns, run get_campaigns.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignService.mutate
-Tags: BudgetService.mutate
-"""
-
-__author__ = 'api.kwinter@gmail.com (Kevin Winter)'
-
-import datetime
-import uuid
-
-from googleads import adwords
-
-
-def main(client):
- # Initialize appropriate service.
- campaign_service = client.GetService('CampaignService', version='v201409')
- budget_service = client.GetService('BudgetService', version='v201409')
-
- # Create a budget, which can be shared by multiple campaigns.
- budget = {
- 'name': 'Interplanetary budget #%s' % uuid.uuid4(),
- 'amount': {
- 'microAmount': '50000000'
- },
- 'deliveryMethod': 'STANDARD',
- 'period': 'DAILY'
- }
-
- budget_operations = [{
- 'operator': 'ADD',
- 'operand': budget
- }]
-
- # Add the budget.
- budget_id = budget_service.mutate(budget_operations)['value'][0][
- 'budgetId']
-
- # Construct operations and add campaigns.
- operations = [{
- 'operator': 'ADD',
- 'operand': {
- 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(),
- 'status': 'PAUSED',
- 'advertisingChannelType': 'DISPLAY',
- 'biddingStrategyConfiguration': {
- 'biddingStrategyType': 'MANUAL_CPM',
- },
- 'endDate': (datetime.datetime.now() +
- datetime.timedelta(365)).strftime('%Y%m%d'),
- # Note that only the budgetId is required
- 'budget': {
- 'budgetId': budget_id
- },
- 'settings': [{
- 'xsi_type': 'RealTimeBiddingSetting',
- 'optIn': 'true'
- }],
- # Optional fields
- 'startDate': (datetime.datetime.now() +
- datetime.timedelta(1)).strftime('%Y%m%d'),
- 'adServingOptimizationStatus': 'ROTATE',
- 'frequencyCap': {
- 'impressions': '5',
- 'timeUnit': 'DAY',
- 'level': 'ADGROUP'
- }
- }
- }, {
- 'operator': 'ADD',
- 'operand': {
- 'name': 'Interplanetary Cruise Banners #%s' % uuid.uuid4(),
- 'status': 'PAUSED',
- 'advertisingChannelType': 'DISPLAY',
- 'biddingStrategyConfiguration': {
- 'biddingStrategyType': 'MANUAL_CPM',
- },
- 'endDate': (datetime.datetime.now() +
- datetime.timedelta(365)).strftime('%Y%m%d'),
- # Note that only the budgetId is required
- 'budget': {
- 'budgetId': budget_id
- },
- 'settings': [{
- 'xsi_type': 'RealTimeBiddingSetting',
- 'optIn': 'true'
- }],
- }
- }]
- campaigns = campaign_service.mutate(operations)
-
- # Display results.
- for campaign in campaigns['value']:
- print ('Campaign with name \'%s\' and id \'%s\' was added.'
- % (campaign['name'], campaign['id']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adxbuyer/v201409/basic_operations/add_placements.py b/examples/adxbuyer/v201409/basic_operations/add_placements.py
deleted file mode 100755
index a815d47c..00000000
--- a/examples/adxbuyer/v201409/basic_operations/add_placements.py
+++ /dev/null
@@ -1,90 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2013 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds ad group criteria to an ad group.
-
-To get ad groups, run get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupCriterionService.mutate
-"""
-
-__author__ = 'api.kwinter@gmail.com (Kevin Winter)'
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Initialize appropriate service.
- ad_group_criterion_service = client.GetService(
- 'AdGroupCriterionService', version='v201409')
-
- # Construct keyword ad group criterion object.
- placement1 = {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Placement',
- 'url': 'http://mars.google.com'
- },
- # These fields are optional.
- 'userStatus': 'PAUSED',
- 'destinationUrl': 'http://example.com/mars'
- }
-
- placement2 = {
- 'xsi_type': 'NegativeAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Placement',
- 'url': 'http://example.com/pluto'
- },
- }
-
- # Construct operations and add ad group criteria.
- operations = [
- {
- 'operator': 'ADD',
- 'operand': placement1
- },
- {
- 'operator': 'ADD',
- 'operand': placement2
- }
- ]
- ad_group_criteria = ad_group_criterion_service.mutate(
- operations)['value']
-
- # Display results.
- for criterion in ad_group_criteria:
- print ('Placement ad group criterion with ad group id \'%s\', criterion '
- 'id \'%s\', and url \'%s\' was added.'
- % (criterion['adGroupId'], criterion['criterion']['id'],
- criterion['criterion']['url']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adxbuyer/v201409/basic_operations/add_third_party_redirect_ad.py b/examples/adxbuyer/v201409/basic_operations/add_third_party_redirect_ad.py
deleted file mode 100755
index ce94ab77..00000000
--- a/examples/adxbuyer/v201409/basic_operations/add_third_party_redirect_ad.py
+++ /dev/null
@@ -1,102 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2013 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds several third party ads to a given ad group.
-
-To get an ad_group_id, run get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupAdService.mutate
-"""
-
-__author__ = 'api.kwinter@gmail.com (Kevin Winter)'
-
-import uuid
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Initialize appropriate service.
- ad_group_ad_service = client.GetService('AdGroupAdService', version='v201409')
-
- # Construct operations and add ads.
- operations = [
- {
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'AdGroupAd',
- 'adGroupId': ad_group_id,
- 'ad': {
- 'xsi_type': 'ThirdPartyRedirectAd',
- 'name': 'Example third party ad #%s' % uuid.uuid4(),
- 'url': 'http://www.example.com',
- 'dimensions': {
- 'width': '300',
- 'height': '250'
- },
- # This field normally contains the javascript ad tag.
- 'snippet': (''),
- 'certifiedVendorFormatId': '232',
- 'isCookieTargeted': 'false',
- 'isUserInterestTargeted': 'false',
- 'isTagged': 'false',
- 'richMediaAdType': 'STANDARD',
- 'expandingDirections': ['EXPANDING_UP', 'EXPANDING_DOWN'],
- 'adAttributes': ['ROLL_OVER_TO_EXPAND']
- }
- }
- },
- {
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'AdGroupAd',
- 'adGroupId': ad_group_id,
- 'ad': {
- 'xsi_type': 'ThirdPartyRedirectAd',
- 'name': 'Example third party ad #%s' % uuid.uuid4(),
- 'url': 'http://www.example.com',
- 'adDuration': '15000',
- 'sourceUrl': ('http://ad.doubleclick.net/pfadx/N270.126913.'
- '6102203221521/B3876671.21;dcadv=2215309;'
- 'sz=0x0;ord=%5btimestamp%5d;dcmt=text/xml'),
- 'certifiedVendorFormatId': '303',
- 'richMediaAdType': 'IN_STREAM_VIDEO'
- }
- }
- }
- ]
- ads = ad_group_ad_service.mutate(operations)
-
- # Display results.
- for ad in ads['value']:
- print ('Ad with ID \'%s\' and of type \'%s\' was added.'
- % (ad['ad']['id'], ad['ad']['Ad.Type']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adxbuyer/v201409/basic_operations/get_placements.py b/examples/adxbuyer/v201409/basic_operations/get_placements.py
deleted file mode 100755
index 5f109eee..00000000
--- a/examples/adxbuyer/v201409/basic_operations/get_placements.py
+++ /dev/null
@@ -1,78 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2013 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all ad group criteria in an account.
-
-To add placements, run add_placements.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupCriterionService.get
-"""
-
-__author__ = 'api.kwinter@gmail.com (Kevin Winter)'
-
-from googleads import adwords
-
-
-PAGE_SIZE = 500
-
-
-def main(client):
- # Initialize appropriate service.
- ad_group_criterion_service = client.GetService(
- 'AdGroupCriterionService', version='v201409')
-
- # Construct selector and get all ad group criteria.
- offset = 0
- selector = {
- 'fields': ['AdGroupId', 'Id', 'PlacementUrl'],
- 'predicates': [{
- 'field': 'CriteriaType',
- 'operator': 'EQUALS',
- 'values': ['PLACEMENT']
- }],
- 'paging': {
- 'startIndex': str(offset),
- 'numberResults': str(PAGE_SIZE)
- }
- }
- more_pages = True
- while more_pages:
- page = ad_group_criterion_service.get(selector)
-
- # Display results.
- if 'entries' in page:
- for criterion in page['entries']:
- print ('Placement ad group criterion with ad group id \'%s\', '
- 'criterion id \'%s\' and url \'%s\'.'
- % (criterion['adGroupId'], criterion['criterion']['id'],
- criterion['criterion']['url']))
- else:
- print 'No placements were found.'
- offset += PAGE_SIZE
- selector['paging']['startIndex'] = str(offset)
- more_pages = offset < int(page['totalNumEntries'])
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adxbuyer/v201409/basic_operations/get_third_party_redirect_ads.py b/examples/adxbuyer/v201409/basic_operations/get_third_party_redirect_ads.py
deleted file mode 100755
index 7e6401cd..00000000
--- a/examples/adxbuyer/v201409/basic_operations/get_third_party_redirect_ads.py
+++ /dev/null
@@ -1,83 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2013 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all third party ads for a given ad group.
-
-To add a third party ad, add_third_party_redirect_ad.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupAdService.get
-"""
-
-__author__ = 'api.kwinter@gmail.com (Kevin Winter)'
-
-from googleads import adwords
-
-
-PAGE_SIZE = 500
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Initialize appropriate service.
- ad_group_ad_service = client.GetService('AdGroupAdService', version='v201409')
-
- # Construct selector and get all ads for a given ad group.
- offset = 0
- selector = {
- 'fields': ['Id', 'AdGroupId', 'Status'],
- 'predicates': [
- {
- 'field': 'AdGroupId',
- 'operator': 'EQUALS',
- 'values': [ad_group_id]
- },
- {
- 'field': 'AdType',
- 'operator': 'EQUALS',
- 'values': ['THIRD_PARTY_REDIRECT_AD']
- }
- ],
- 'paging': {
- 'startIndex': str(offset),
- 'numberResults': str(PAGE_SIZE)
- }
- }
- more_pages = True
- while more_pages:
- page = ad_group_ad_service.get(selector)
-
- # Display results.
- if 'entries' in page:
- for ad in page['entries']:
- print ('Ad with id \'%s\', status \'%s\', and of type \'%s\' was found.'
- % (ad['ad']['id'], ad['status'], ad['ad']['Ad.Type']))
- else:
- print 'No ads were found.'
- offset += PAGE_SIZE
- selector['paging']['startIndex'] = str(offset)
- more_pages = offset < int(page['totalNumEntries'])
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adxbuyer/v201409/basic_operations/remove_placement.py b/examples/adxbuyer/v201409/basic_operations/remove_placement.py
deleted file mode 100755
index 1f1655ad..00000000
--- a/examples/adxbuyer/v201409/basic_operations/remove_placement.py
+++ /dev/null
@@ -1,71 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2013 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example deletes an ad group criterion using the 'REMOVE' operator.
-
-To get ad group criteria, run get_placements.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupCriterionService.mutate
-"""
-
-__author__ = 'api.kwinter@gmail.com (Kevin Winter)'
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-CRITERION_ID = 'INSERT_CRITERION_ID_HERE'
-
-
-def main(client, ad_group_id, criterion_id):
- # Initialize appropriate service.
- ad_group_criterion_service = client.GetService(
- 'AdGroupCriterionService', version='v201409')
-
- # Construct operations and delete ad group criteria.
- operations = [
- {
- 'operator': 'REMOVE',
- 'operand': {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Placement',
- 'id': criterion_id
- }
- }
- }
- ]
- result = ad_group_criterion_service.mutate(operations)
-
- # Display results.
- for criterion in result['value']:
- print ('Ad group criterion with ad group id \'%s\', criterion id \'%s\', '
- 'and type \'%s\' was deleted.'
- % (criterion['adGroupId'], criterion['criterion']['id'],
- criterion['criterion']['Criterion.Type']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID, CRITERION_ID)
diff --git a/examples/adxbuyer/v201409/basic_operations/update_placement.py b/examples/adxbuyer/v201409/basic_operations/update_placement.py
deleted file mode 100755
index bae10ac5..00000000
--- a/examples/adxbuyer/v201409/basic_operations/update_placement.py
+++ /dev/null
@@ -1,83 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2013 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates the bid of a placement.
-
-To add a placement, run add_placements.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupCriterionService.mutate
-"""
-
-__author__ = 'api.kwinter@gmail.com (Kevin Winter)'
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-CRITERION_ID = 'INSERT_PLACEMENT_CRITERION_ID_HERE'
-
-
-def main(client, ad_group_id, criterion_id):
- # Initialize appropriate service.
- ad_group_criterion_service = client.GetService(
- 'AdGroupCriterionService', version='v201409')
-
- # Construct operations and update bids.
- operations = [{
- 'operator': 'SET',
- 'operand': {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Placement',
- 'id': criterion_id,
- },
- 'biddingStrategyConfiguration': {
- 'bids': [
- {
- 'xsi_type': 'CpmBid',
- 'bid': {
- 'microAmount': '1000000'
- },
- }
- ]
- }
- }
- }]
- ad_group_criteria = ad_group_criterion_service.mutate(operations)
-
- # Display results.
- if 'value' in ad_group_criteria:
- for criterion in ad_group_criteria['value']:
- if criterion['criterion']['Criterion.Type'] == 'Keyword':
- print ('Ad group criterion with ad group id \'%s\' and criterion id '
- '\'%s\' had its bid set to \'%s\'.'
- % (criterion['adGroupId'], criterion['criterion']['id'],
- criterion['bids']['maxCpc']['amount']['microAmount']))
- else:
- print 'No ad group criteria were updated.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID, CRITERION_ID)
diff --git a/examples/adxbuyer/v201409/campaign_management/__init__.py b/examples/adxbuyer/v201409/campaign_management/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/examples/adxbuyer/v201409/campaign_management/add_placements_in_bulk.py b/examples/adxbuyer/v201409/campaign_management/add_placements_in_bulk.py
deleted file mode 100755
index df803b9e..00000000
--- a/examples/adxbuyer/v201409/campaign_management/add_placements_in_bulk.py
+++ /dev/null
@@ -1,138 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2013 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Illustrates how to perform asynchronous requests using the MutateJobService.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: MutateJobService.mutate
-Tags: MutateJobService.get
-Tags: MutateJobService.getResult
-"""
-
-__author__ = 'api.kwinter@gmail.com (Kevin Winter)'
-
-import random
-import re
-import time
-
-from googleads import adwords
-from googleads import errors
-
-
-RETRY_INTERVAL = 10
-RETRIES_COUNT = 30
-PLACEMENT_NUMBER = 100
-INDEX_REGEX = r'operations\[(\d+)\].operand'
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Initialize appropriate service.
- mutate_job_service = client.GetService('MutateJobService', version='v201409')
-
- # Create list of all operations for the job.
- operations = []
-
- # Create AdGroupCriterionOperations to add placements.
- for i in range(PLACEMENT_NUMBER):
- url = 'www.example.com/mars%d' % i
- if random.randint(1, 10) == 1:
- url = 'NOT_@_URL'
- operations.append({
- 'xsi_type': 'AdGroupCriterionOperation',
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Placement',
- 'url': url
- }
- }
- })
-
- # You can specify up to 3 job IDs that must successfully complete before
- # this job can be processed.
- policy = {
- 'prerequisiteJobIds': []
- }
-
- # Call mutate to create a new job.
- response = mutate_job_service.mutate(operations, policy)
-
- if not response:
- raise errors.GoogleAdsError('Failed to submit a job; aborting.')
-
- job_id = response['id']
- print 'Job with ID %s was successfully created.' % job_id
-
- # Create selector to retrieve job status and wait for it to complete.
- selector = {
- 'xsi_type': 'BulkMutateJobSelector',
- 'jobIds': [job_id]
- }
-
- time.sleep(RETRY_INTERVAL)
- # Poll for job status until it's finished.
- print 'Retrieving job status...'
- for i in range(RETRIES_COUNT):
- job_status_response = mutate_job_service.get(selector)
- status = job_status_response[0]['status']
- if status in ('COMPLETED', 'FAILED'):
- break
- print ('[%d] Current status is \'%s\', waiting %d seconds to retry...' %
- (i, status, RETRY_INTERVAL))
- time.sleep(RETRY_INTERVAL)
-
- if status == 'FAILED':
- raise errors.GoogleAdsError('Job failed with reason: \'%s\'' %
- job_status_response[0]['failure_reason'])
- if status in ('PROCESSING', 'PENDING'):
- raise errors.GoogleAdsError('Job did not complete within %d seconds' %
- (RETRY_INTERVAL * (RETRIES_COUNT - 1)))
-
- # Status must be COMPLETED.
- # Get the job result. Here we re-use the same selector.
- result_response = mutate_job_service.getResult(selector)
-
- # Output results.
- index = 0
- for result in result_response['SimpleMutateResult']['results']:
- if 'PlaceHolder' in result:
- print 'Operation [%d] - FAILED' % index
- else:
- print 'Operation [%d] - SUCCEEDED' % index
- index += 1
-
- # Output errors
- for error in result_response['SimpleMutateResult']['errors']:
- index = int(re.search(INDEX_REGEX, error['fieldPath']).group(1))
- reason = error['reason']
- url = operations[index]['operand']['criterion']['url']
- print ('ERROR - placement \'%s\' failed due to \'%s\'' %
- (url, reason))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adxbuyer/v201409/error_handling/__init__.py b/examples/adxbuyer/v201409/error_handling/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/examples/adxbuyer/v201409/error_handling/handle_partial_failures.py b/examples/adxbuyer/v201409/error_handling/handle_partial_failures.py
deleted file mode 100755
index 28d4b451..00000000
--- a/examples/adxbuyer/v201409/error_handling/handle_partial_failures.py
+++ /dev/null
@@ -1,117 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2013 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example demonstrates how to handle partial failures.
-
-To get ad groups, run get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupCriterionService.mutate
-"""
-
-__author__ = 'api.kwinter@gmail.com (Kevin Winter)'
-
-import re
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Enable partial failure.
- client.partial_failure = True
-
- # Initialize appropriate service.
- ad_group_criterion_service = client.GetService(
- 'AdGroupCriterionService', version='v201409')
-
- # Construct placement ad group criteria objects.
- placements = [
- {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Placement',
- 'url': 'www.example.com/something'
- }
- },
- {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Placement',
- 'url': 'INVALID!!_URL'
- }
- },
- {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Placement',
- 'url': 'www.example.com/somethingelse'
- }
- },
- {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Placement',
- 'url': 'BAD!!_URL'
- }
- }
- ]
-
- # Construct operations and add ad group criteria.
- operations = []
- for placement in placements:
- operations.append(
- {
- 'operator': 'ADD',
- 'operand': placement
- })
- result = ad_group_criterion_service.mutate(operations)
-
- # Display results.
- for criterion in result['value']:
- if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion':
- print ('Added placement ad group criterion with ad group id \'%s\', '
- 'criterion id \'%s\' and url \'%s\''
- % (criterion['adGroupId'], criterion['criterion']['id'],
- criterion['criterion']['url']))
-
- for error in result['partialFailureErrors']:
- index = re.findall(r'operations\[(.*)\]\.', error['fieldPath'])
- if index:
- print ('Placement ad group criterion with ad group id \'%s\' and url '
- '\'%s\' triggered a failure for the following reason: \'%s\'.'
- % (placements[int(index[0])]['adGroupId'],
- placements[int(index[0])]['criterion']['url'],
- error['errorString']))
- else:
- print 'The following failure has occurred: \'%s\'.' % error['errorString']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adxbuyer/v201502/__init__.py b/examples/adxbuyer/v201502/__init__.py
deleted file mode 100644
index 55fdaeac..00000000
--- a/examples/adxbuyer/v201502/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Examples for DoubleClick Ad Exchange Buyer SOAP API."""
diff --git a/examples/adxbuyer/v201502/basic_operations/__init__.py b/examples/adxbuyer/v201502/basic_operations/__init__.py
deleted file mode 100644
index 80acbea9..00000000
--- a/examples/adxbuyer/v201502/basic_operations/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Basic operations examples."""
diff --git a/examples/adxbuyer/v201502/basic_operations/add_ad_groups.py b/examples/adxbuyer/v201502/basic_operations/add_ad_groups.py
deleted file mode 100755
index 04027a3c..00000000
--- a/examples/adxbuyer/v201502/basic_operations/add_ad_groups.py
+++ /dev/null
@@ -1,91 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2013 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds ad groups to a given campaign.
-
-To get ad groups, run get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupService.mutate
-"""
-
-__author__ = 'api.kwinter@gmail.com (Kevin Winter)'
-
-import uuid
-
-from googleads import adwords
-
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-
-
-def main(client, campaign_id):
- # Initialize appropriate service.
- ad_group_service = client.GetService('AdGroupService', version='v201502')
-
- # Construct operations and add ad groups.
- operations = [{
- 'operator': 'ADD',
- 'operand': {
- 'campaignId': campaign_id,
- 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(),
- 'status': 'ENABLED',
- 'biddingStrategyConfiguration': {
- 'bids': [
- {
- 'xsi_type': 'CpmBid',
- 'bid': {
- 'microAmount': '1000000'
- },
- }
- ]
- }
- }
- }, {
- 'operator': 'ADD',
- 'operand': {
- 'campaignId': campaign_id,
- 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(),
- 'status': 'ENABLED',
- 'biddingStrategyConfiguration': {
- 'bids': [
- {
- 'xsi_type': 'CpmBid',
- 'bid': {
- 'microAmount': '1000000'
- },
- }
- ]
- }
- }
- }]
- ad_groups = ad_group_service.mutate(operations)
-
- # Display results.
- for ad_group in ad_groups['value']:
- print ('Ad group with name \'%s\' and id \'%s\' was added.'
- % (ad_group['name'], ad_group['id']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, CAMPAIGN_ID)
diff --git a/examples/adxbuyer/v201502/basic_operations/add_campaigns.py b/examples/adxbuyer/v201502/basic_operations/add_campaigns.py
deleted file mode 100755
index 1e11d1c4..00000000
--- a/examples/adxbuyer/v201502/basic_operations/add_campaigns.py
+++ /dev/null
@@ -1,123 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2013 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds campaigns. To get campaigns, run get_campaigns.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CampaignService.mutate
-Tags: BudgetService.mutate
-"""
-
-__author__ = 'api.kwinter@gmail.com (Kevin Winter)'
-
-import datetime
-import uuid
-
-from googleads import adwords
-
-
-def main(client):
- # Initialize appropriate service.
- campaign_service = client.GetService('CampaignService', version='v201502')
- budget_service = client.GetService('BudgetService', version='v201502')
-
- # Create a budget, which can be shared by multiple campaigns.
- budget = {
- 'name': 'Interplanetary budget #%s' % uuid.uuid4(),
- 'amount': {
- 'microAmount': '50000000'
- },
- 'deliveryMethod': 'STANDARD',
- 'period': 'DAILY'
- }
-
- budget_operations = [{
- 'operator': 'ADD',
- 'operand': budget
- }]
-
- # Add the budget.
- budget_id = budget_service.mutate(budget_operations)['value'][0][
- 'budgetId']
-
- # Construct operations and add campaigns.
- operations = [{
- 'operator': 'ADD',
- 'operand': {
- 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(),
- 'status': 'PAUSED',
- 'advertisingChannelType': 'DISPLAY',
- 'biddingStrategyConfiguration': {
- 'biddingStrategyType': 'MANUAL_CPM',
- },
- 'endDate': (datetime.datetime.now() +
- datetime.timedelta(365)).strftime('%Y%m%d'),
- # Note that only the budgetId is required
- 'budget': {
- 'budgetId': budget_id
- },
- 'settings': [{
- 'xsi_type': 'RealTimeBiddingSetting',
- 'optIn': 'true'
- }],
- # Optional fields
- 'startDate': (datetime.datetime.now() +
- datetime.timedelta(1)).strftime('%Y%m%d'),
- 'adServingOptimizationStatus': 'ROTATE',
- 'frequencyCap': {
- 'impressions': '5',
- 'timeUnit': 'DAY',
- 'level': 'ADGROUP'
- }
- }
- }, {
- 'operator': 'ADD',
- 'operand': {
- 'name': 'Interplanetary Cruise Banners #%s' % uuid.uuid4(),
- 'status': 'PAUSED',
- 'advertisingChannelType': 'DISPLAY',
- 'biddingStrategyConfiguration': {
- 'biddingStrategyType': 'MANUAL_CPM',
- },
- 'endDate': (datetime.datetime.now() +
- datetime.timedelta(365)).strftime('%Y%m%d'),
- # Note that only the budgetId is required
- 'budget': {
- 'budgetId': budget_id
- },
- 'settings': [{
- 'xsi_type': 'RealTimeBiddingSetting',
- 'optIn': 'true'
- }],
- }
- }]
- campaigns = campaign_service.mutate(operations)
-
- # Display results.
- for campaign in campaigns['value']:
- print ('Campaign with name \'%s\' and id \'%s\' was added.'
- % (campaign['name'], campaign['id']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adxbuyer/v201502/basic_operations/add_placements.py b/examples/adxbuyer/v201502/basic_operations/add_placements.py
deleted file mode 100755
index 7cb0bfe1..00000000
--- a/examples/adxbuyer/v201502/basic_operations/add_placements.py
+++ /dev/null
@@ -1,90 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2013 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds ad group criteria to an ad group.
-
-To get ad groups, run get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupCriterionService.mutate
-"""
-
-__author__ = 'api.kwinter@gmail.com (Kevin Winter)'
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Initialize appropriate service.
- ad_group_criterion_service = client.GetService(
- 'AdGroupCriterionService', version='v201502')
-
- # Construct keyword ad group criterion object.
- placement1 = {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Placement',
- 'url': 'http://mars.google.com'
- },
- # These fields are optional.
- 'userStatus': 'PAUSED',
- 'destinationUrl': 'http://example.com/mars'
- }
-
- placement2 = {
- 'xsi_type': 'NegativeAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Placement',
- 'url': 'http://example.com/pluto'
- },
- }
-
- # Construct operations and add ad group criteria.
- operations = [
- {
- 'operator': 'ADD',
- 'operand': placement1
- },
- {
- 'operator': 'ADD',
- 'operand': placement2
- }
- ]
- ad_group_criteria = ad_group_criterion_service.mutate(
- operations)['value']
-
- # Display results.
- for criterion in ad_group_criteria:
- print ('Placement ad group criterion with ad group id \'%s\', criterion '
- 'id \'%s\', and url \'%s\' was added.'
- % (criterion['adGroupId'], criterion['criterion']['id'],
- criterion['criterion']['url']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adxbuyer/v201502/basic_operations/add_third_party_redirect_ad.py b/examples/adxbuyer/v201502/basic_operations/add_third_party_redirect_ad.py
deleted file mode 100755
index 8ccd8581..00000000
--- a/examples/adxbuyer/v201502/basic_operations/add_third_party_redirect_ad.py
+++ /dev/null
@@ -1,102 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2013 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds several third party ads to a given ad group.
-
-To get an ad_group_id, run get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupAdService.mutate
-"""
-
-__author__ = 'api.kwinter@gmail.com (Kevin Winter)'
-
-import uuid
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Initialize appropriate service.
- ad_group_ad_service = client.GetService('AdGroupAdService', version='v201502')
-
- # Construct operations and add ads.
- operations = [
- {
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'AdGroupAd',
- 'adGroupId': ad_group_id,
- 'ad': {
- 'xsi_type': 'ThirdPartyRedirectAd',
- 'name': 'Example third party ad #%s' % uuid.uuid4(),
- 'url': 'http://www.example.com',
- 'dimensions': {
- 'width': '300',
- 'height': '250'
- },
- # This field normally contains the javascript ad tag.
- 'snippet': (''),
- 'certifiedVendorFormatId': '232',
- 'isCookieTargeted': 'false',
- 'isUserInterestTargeted': 'false',
- 'isTagged': 'false',
- 'richMediaAdType': 'STANDARD',
- 'expandingDirections': ['EXPANDING_UP', 'EXPANDING_DOWN'],
- 'adAttributes': ['ROLL_OVER_TO_EXPAND']
- }
- }
- },
- {
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'AdGroupAd',
- 'adGroupId': ad_group_id,
- 'ad': {
- 'xsi_type': 'ThirdPartyRedirectAd',
- 'name': 'Example third party ad #%s' % uuid.uuid4(),
- 'url': 'http://www.example.com',
- 'adDuration': '15000',
- 'sourceUrl': ('http://ad.doubleclick.net/pfadx/N270.126913.'
- '6102203221521/B3876671.21;dcadv=2215309;'
- 'sz=0x0;ord=%5btimestamp%5d;dcmt=text/xml'),
- 'certifiedVendorFormatId': '303',
- 'richMediaAdType': 'IN_STREAM_VIDEO'
- }
- }
- }
- ]
- ads = ad_group_ad_service.mutate(operations)
-
- # Display results.
- for ad in ads['value']:
- print ('Ad with ID \'%s\' and of type \'%s\' was added.'
- % (ad['ad']['id'], ad['ad']['Ad.Type']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adxbuyer/v201502/basic_operations/get_placements.py b/examples/adxbuyer/v201502/basic_operations/get_placements.py
deleted file mode 100755
index e2355618..00000000
--- a/examples/adxbuyer/v201502/basic_operations/get_placements.py
+++ /dev/null
@@ -1,78 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2013 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all ad group criteria in an account.
-
-To add placements, run add_placements.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupCriterionService.get
-"""
-
-__author__ = 'api.kwinter@gmail.com (Kevin Winter)'
-
-from googleads import adwords
-
-
-PAGE_SIZE = 500
-
-
-def main(client):
- # Initialize appropriate service.
- ad_group_criterion_service = client.GetService(
- 'AdGroupCriterionService', version='v201502')
-
- # Construct selector and get all ad group criteria.
- offset = 0
- selector = {
- 'fields': ['AdGroupId', 'Id', 'PlacementUrl'],
- 'predicates': [{
- 'field': 'CriteriaType',
- 'operator': 'EQUALS',
- 'values': ['PLACEMENT']
- }],
- 'paging': {
- 'startIndex': str(offset),
- 'numberResults': str(PAGE_SIZE)
- }
- }
- more_pages = True
- while more_pages:
- page = ad_group_criterion_service.get(selector)
-
- # Display results.
- if 'entries' in page:
- for criterion in page['entries']:
- print ('Placement ad group criterion with ad group id \'%s\', '
- 'criterion id \'%s\' and url \'%s\'.'
- % (criterion['adGroupId'], criterion['criterion']['id'],
- criterion['criterion']['url']))
- else:
- print 'No placements were found.'
- offset += PAGE_SIZE
- selector['paging']['startIndex'] = str(offset)
- more_pages = offset < int(page['totalNumEntries'])
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client)
diff --git a/examples/adxbuyer/v201502/basic_operations/get_third_party_redirect_ads.py b/examples/adxbuyer/v201502/basic_operations/get_third_party_redirect_ads.py
deleted file mode 100755
index 9b54a0ca..00000000
--- a/examples/adxbuyer/v201502/basic_operations/get_third_party_redirect_ads.py
+++ /dev/null
@@ -1,83 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2013 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all third party ads for a given ad group.
-
-To add a third party ad, add_third_party_redirect_ad.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupAdService.get
-"""
-
-__author__ = 'api.kwinter@gmail.com (Kevin Winter)'
-
-from googleads import adwords
-
-
-PAGE_SIZE = 500
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Initialize appropriate service.
- ad_group_ad_service = client.GetService('AdGroupAdService', version='v201502')
-
- # Construct selector and get all ads for a given ad group.
- offset = 0
- selector = {
- 'fields': ['Id', 'AdGroupId', 'Status'],
- 'predicates': [
- {
- 'field': 'AdGroupId',
- 'operator': 'EQUALS',
- 'values': [ad_group_id]
- },
- {
- 'field': 'AdType',
- 'operator': 'EQUALS',
- 'values': ['THIRD_PARTY_REDIRECT_AD']
- }
- ],
- 'paging': {
- 'startIndex': str(offset),
- 'numberResults': str(PAGE_SIZE)
- }
- }
- more_pages = True
- while more_pages:
- page = ad_group_ad_service.get(selector)
-
- # Display results.
- if 'entries' in page:
- for ad in page['entries']:
- print ('Ad with id \'%s\', status \'%s\', and of type \'%s\' was found.'
- % (ad['ad']['id'], ad['status'], ad['ad']['Ad.Type']))
- else:
- print 'No ads were found.'
- offset += PAGE_SIZE
- selector['paging']['startIndex'] = str(offset)
- more_pages = offset < int(page['totalNumEntries'])
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adxbuyer/v201502/basic_operations/remove_placement.py b/examples/adxbuyer/v201502/basic_operations/remove_placement.py
deleted file mode 100755
index 0c9ddcb8..00000000
--- a/examples/adxbuyer/v201502/basic_operations/remove_placement.py
+++ /dev/null
@@ -1,71 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2013 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example deletes an ad group criterion using the 'REMOVE' operator.
-
-To get ad group criteria, run get_placements.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupCriterionService.mutate
-"""
-
-__author__ = 'api.kwinter@gmail.com (Kevin Winter)'
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-CRITERION_ID = 'INSERT_CRITERION_ID_HERE'
-
-
-def main(client, ad_group_id, criterion_id):
- # Initialize appropriate service.
- ad_group_criterion_service = client.GetService(
- 'AdGroupCriterionService', version='v201502')
-
- # Construct operations and delete ad group criteria.
- operations = [
- {
- 'operator': 'REMOVE',
- 'operand': {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Placement',
- 'id': criterion_id
- }
- }
- }
- ]
- result = ad_group_criterion_service.mutate(operations)
-
- # Display results.
- for criterion in result['value']:
- print ('Ad group criterion with ad group id \'%s\', criterion id \'%s\', '
- 'and type \'%s\' was deleted.'
- % (criterion['adGroupId'], criterion['criterion']['id'],
- criterion['criterion']['Criterion.Type']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID, CRITERION_ID)
diff --git a/examples/adxbuyer/v201502/basic_operations/update_placement.py b/examples/adxbuyer/v201502/basic_operations/update_placement.py
deleted file mode 100755
index 6f08598d..00000000
--- a/examples/adxbuyer/v201502/basic_operations/update_placement.py
+++ /dev/null
@@ -1,83 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2013 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates the bid of a placement.
-
-To add a placement, run add_placements.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupCriterionService.mutate
-"""
-
-__author__ = 'api.kwinter@gmail.com (Kevin Winter)'
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-CRITERION_ID = 'INSERT_PLACEMENT_CRITERION_ID_HERE'
-
-
-def main(client, ad_group_id, criterion_id):
- # Initialize appropriate service.
- ad_group_criterion_service = client.GetService(
- 'AdGroupCriterionService', version='v201502')
-
- # Construct operations and update bids.
- operations = [{
- 'operator': 'SET',
- 'operand': {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Placement',
- 'id': criterion_id,
- },
- 'biddingStrategyConfiguration': {
- 'bids': [
- {
- 'xsi_type': 'CpmBid',
- 'bid': {
- 'microAmount': '1000000'
- },
- }
- ]
- }
- }
- }]
- ad_group_criteria = ad_group_criterion_service.mutate(operations)
-
- # Display results.
- if 'value' in ad_group_criteria:
- for criterion in ad_group_criteria['value']:
- if criterion['criterion']['Criterion.Type'] == 'Keyword':
- print ('Ad group criterion with ad group id \'%s\' and criterion id '
- '\'%s\' had its bid set to \'%s\'.'
- % (criterion['adGroupId'], criterion['criterion']['id'],
- criterion['bids']['maxCpc']['amount']['microAmount']))
- else:
- print 'No ad group criteria were updated.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID, CRITERION_ID)
diff --git a/examples/adxbuyer/v201502/campaign_management/__init__.py b/examples/adxbuyer/v201502/campaign_management/__init__.py
deleted file mode 100644
index db098bda..00000000
--- a/examples/adxbuyer/v201502/campaign_management/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Campaign management examples."""
diff --git a/examples/adxbuyer/v201502/campaign_management/add_placements_in_bulk.py b/examples/adxbuyer/v201502/campaign_management/add_placements_in_bulk.py
deleted file mode 100755
index 6eb3da56..00000000
--- a/examples/adxbuyer/v201502/campaign_management/add_placements_in_bulk.py
+++ /dev/null
@@ -1,138 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2013 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Illustrates how to perform asynchronous requests using the MutateJobService.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: MutateJobService.mutate
-Tags: MutateJobService.get
-Tags: MutateJobService.getResult
-"""
-
-__author__ = 'api.kwinter@gmail.com (Kevin Winter)'
-
-import random
-import re
-import time
-
-from googleads import adwords
-from googleads import errors
-
-
-RETRY_INTERVAL = 10
-RETRIES_COUNT = 30
-PLACEMENT_NUMBER = 100
-INDEX_REGEX = r'operations\[(\d+)\].operand'
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Initialize appropriate service.
- mutate_job_service = client.GetService('MutateJobService', version='v201502')
-
- # Create list of all operations for the job.
- operations = []
-
- # Create AdGroupCriterionOperations to add placements.
- for i in range(PLACEMENT_NUMBER):
- url = 'www.example.com/mars%d' % i
- if random.randint(1, 10) == 1:
- url = 'NOT_@_URL'
- operations.append({
- 'xsi_type': 'AdGroupCriterionOperation',
- 'operator': 'ADD',
- 'operand': {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Placement',
- 'url': url
- }
- }
- })
-
- # You can specify up to 3 job IDs that must successfully complete before
- # this job can be processed.
- policy = {
- 'prerequisiteJobIds': []
- }
-
- # Call mutate to create a new job.
- response = mutate_job_service.mutate(operations, policy)
-
- if not response:
- raise errors.GoogleAdsError('Failed to submit a job; aborting.')
-
- job_id = response['id']
- print 'Job with ID %s was successfully created.' % job_id
-
- # Create selector to retrieve job status and wait for it to complete.
- selector = {
- 'xsi_type': 'BulkMutateJobSelector',
- 'jobIds': [job_id]
- }
-
- time.sleep(RETRY_INTERVAL)
- # Poll for job status until it's finished.
- print 'Retrieving job status...'
- for i in range(RETRIES_COUNT):
- job_status_response = mutate_job_service.get(selector)
- status = job_status_response[0]['status']
- if status in ('COMPLETED', 'FAILED'):
- break
- print ('[%d] Current status is \'%s\', waiting %d seconds to retry...' %
- (i, status, RETRY_INTERVAL))
- time.sleep(RETRY_INTERVAL)
-
- if status == 'FAILED':
- raise errors.GoogleAdsError('Job failed with reason: \'%s\'' %
- job_status_response[0]['failure_reason'])
- if status in ('PROCESSING', 'PENDING'):
- raise errors.GoogleAdsError('Job did not complete within %d seconds' %
- (RETRY_INTERVAL * (RETRIES_COUNT - 1)))
-
- # Status must be COMPLETED.
- # Get the job result. Here we re-use the same selector.
- result_response = mutate_job_service.getResult(selector)
-
- # Output results.
- index = 0
- for result in result_response['SimpleMutateResult']['results']:
- if 'PlaceHolder' in result:
- print 'Operation [%d] - FAILED' % index
- else:
- print 'Operation [%d] - SUCCEEDED' % index
- index += 1
-
- # Output errors
- for error in result_response['SimpleMutateResult']['errors']:
- index = int(re.search(INDEX_REGEX, error['fieldPath']).group(1))
- reason = error['reason']
- url = operations[index]['operand']['criterion']['url']
- print ('ERROR - placement \'%s\' failed due to \'%s\'' %
- (url, reason))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/adxbuyer/v201502/error_handling/__init__.py b/examples/adxbuyer/v201502/error_handling/__init__.py
deleted file mode 100644
index b5203c57..00000000
--- a/examples/adxbuyer/v201502/error_handling/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Error handling examples."""
diff --git a/examples/adxbuyer/v201502/error_handling/handle_partial_failures.py b/examples/adxbuyer/v201502/error_handling/handle_partial_failures.py
deleted file mode 100755
index 8b57f953..00000000
--- a/examples/adxbuyer/v201502/error_handling/handle_partial_failures.py
+++ /dev/null
@@ -1,117 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2013 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example demonstrates how to handle partial failures.
-
-To get ad groups, run get_ad_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: AdGroupCriterionService.mutate
-"""
-
-__author__ = 'api.kwinter@gmail.com (Kevin Winter)'
-
-import re
-
-from googleads import adwords
-
-
-AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
-
-
-def main(client, ad_group_id):
- # Enable partial failure.
- client.partial_failure = True
-
- # Initialize appropriate service.
- ad_group_criterion_service = client.GetService(
- 'AdGroupCriterionService', version='v201502')
-
- # Construct placement ad group criteria objects.
- placements = [
- {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Placement',
- 'url': 'www.example.com/something'
- }
- },
- {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Placement',
- 'url': 'INVALID!!_URL'
- }
- },
- {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Placement',
- 'url': 'www.example.com/somethingelse'
- }
- },
- {
- 'xsi_type': 'BiddableAdGroupCriterion',
- 'adGroupId': ad_group_id,
- 'criterion': {
- 'xsi_type': 'Placement',
- 'url': 'BAD!!_URL'
- }
- }
- ]
-
- # Construct operations and add ad group criteria.
- operations = []
- for placement in placements:
- operations.append(
- {
- 'operator': 'ADD',
- 'operand': placement
- })
- result = ad_group_criterion_service.mutate(operations)
-
- # Display results.
- for criterion in result['value']:
- if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion':
- print ('Added placement ad group criterion with ad group id \'%s\', '
- 'criterion id \'%s\' and url \'%s\''
- % (criterion['adGroupId'], criterion['criterion']['id'],
- criterion['criterion']['url']))
-
- for error in result['partialFailureErrors']:
- index = re.findall(r'operations\[(.*)\]\.', error['fieldPath'])
- if index:
- print ('Placement ad group criterion with ad group id \'%s\' and url '
- '\'%s\' triggered a failure for the following reason: \'%s\'.'
- % (placements[int(index[0])]['adGroupId'],
- placements[int(index[0])]['criterion']['url'],
- error['errorString']))
- else:
- print 'The following failure has occurred: \'%s\'.' % error['errorString']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- adwords_client = adwords.AdWordsClient.LoadFromStorage()
-
- main(adwords_client, AD_GROUP_ID)
diff --git a/examples/dfa/authentication/create_dfa_client_with_service_account.py b/examples/dfa/authentication/create_dfa_client_with_service_account.py
deleted file mode 100755
index 77b2f8ec..00000000
--- a/examples/dfa/authentication/create_dfa_client_with_service_account.py
+++ /dev/null
@@ -1,54 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Initializes a DfaClient via impersonation using a Service Account."""
-
-__author__ = 'Mark Saniscalchi'
-
-from googleads import dfa
-from googleads import oauth2
-
-# OAuth 2.0 credential information. In a real application, you'd probably be
-# pulling these values from a credential storage.
-SERVICE_ACCOUNT_EMAIL = 'INSERT_SERVICE_ACCOUNT_EMAIL_HERE'
-KEY_FILE = 'INSERT_PATH_TO_KEY_FILE'
-SERVICE_ACCOUNT_USER = 'INSERT_IMPERSONATED_EMAIL_HERE'
-
-# DFA API information.
-USER_PROFILE_NAME = 'INSERT_USER_PROFILE_NAME_HERE'
-APPLICATION_NAME = 'INSERT_APPLICATION_NAME_HERE'
-
-
-def main(service_account_email, key_file, service_account_user,
- user_profile_name, application_name):
- oauth2_client = oauth2.GoogleServiceAccountClient(
- oauth2.GetAPIScope('dfa'), service_account_email, key_file,
- sub=service_account_user)
-
- dfa_client = dfa.DfaClient(user_profile_name, oauth2_client, application_name)
-
- campaign_service = dfa_client.GetService(
- 'campaign', server='https://advertisersapitest.doubleclick.net')
- results = campaign_service.getCampaignsByCriteria({})
- if results['records']:
- for campaign in results['records']:
- print ('Campaign with name \'%s\' and ID \'%s\' was found.'
- % (campaign['name'], campaign['id']))
-
-
-if __name__ == '__main__':
- main(SERVICE_ACCOUNT_EMAIL, KEY_FILE, SERVICE_ACCOUNT_USER, USER_PROFILE_NAME,
- APPLICATION_NAME)
diff --git a/examples/dfa/authentication/create_dfa_client_without_yaml.py b/examples/dfa/authentication/create_dfa_client_without_yaml.py
deleted file mode 100755
index 47677634..00000000
--- a/examples/dfa/authentication/create_dfa_client_without_yaml.py
+++ /dev/null
@@ -1,59 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Initializes a DfaClient without using yaml-cached credentials.
-
-While our LoadFromStorage method provides a useful shortcut to instantiate a
-client if you regularly use just one set of credentials, production applications
-may need to swap out users. This example shows you how to create an OAuth 2.0
-client and a DfaClient without relying on a yaml file.
-"""
-
-__author__ = 'Joseph DiLallo'
-
-from googleads import dfa
-from googleads import oauth2
-
-# OAuth 2.0 credential information. In a real application, you'd probably be
-# pulling these values from a credential storage.
-CLIENT_ID = 'INSERT_CLIENT_ID_HERE'
-CLIENT_SECRET = 'INSERT_CLIENT_SECRET_HERE'
-REFRESH_TOKEN = 'INSERT_REFRESH_TOKEN_HERE'
-
-# DFA API information.
-USER_PROFILE_NAME = 'INSERT_USER_PROFILE_NAME_HERE'
-APPLICATION_NAME = 'INSERT_APPLICATION_NAME_HERE'
-
-
-def main(client_id, client_secret, refresh_token, user_profile_name,
- application_name):
- oauth2_client = oauth2.GoogleRefreshTokenClient(
- client_id, client_secret, refresh_token)
-
- dfa_client = dfa.DfaClient(user_profile_name, oauth2_client, application_name)
-
- campaign_service = dfa_client.GetService(
- 'campaign', server='https://advertisersapitest.doubleclick.net')
- results = campaign_service.getCampaignsByCriteria({})
- if results['records']:
- for campaign in results['records']:
- print ('Campaign with name \'%s\' and ID \'%s\' was found.'
- % (campaign['name'], campaign['id']))
-
-
-if __name__ == '__main__':
- main(CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN, USER_PROFILE_NAME,
- APPLICATION_NAME)
diff --git a/examples/dfa/authentication/generate_refresh_token.py b/examples/dfa/authentication/generate_refresh_token.py
deleted file mode 100755
index aaed2437..00000000
--- a/examples/dfa/authentication/generate_refresh_token.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Generates a refresh token for use with DFA."""
-
-__author__ = 'Mark Saniscalchi'
-
-import sys
-
-from oauth2client import client
-
-# Your OAuth 2.0 Client ID and Secret. If you do not have an ID and Secret yet,
-# please go to https://console.developers.google.com and create a set.
-CLIENT_ID = 'INSERT_CLIENT_ID_HERE'
-CLIENT_SECRET = 'INSERT_CLIENT_SECRET_HERE'
-
-# The DFA API OAuth 2.0 scope.
-SCOPE = u'https://www.googleapis.com/auth/dfatrafficking'
-
-
-def main():
- """Retrieve and display the access and refresh token."""
- flow = client.OAuth2WebServerFlow(
- client_id=CLIENT_ID,
- client_secret=CLIENT_SECRET,
- scope=[SCOPE],
- user_agent='Ads Python Client Library',
- redirect_uri='urn:ietf:wg:oauth:2.0:oob')
-
- authorize_url = flow.step1_get_authorize_url()
-
- print ('Log into the Google Account you use to access your DFA account'
- 'and go to the following URL: \n%s\n' % (authorize_url))
- print 'After approving the token enter the verification code (if specified).'
- code = raw_input('Code: ').strip()
-
- try:
- credential = flow.step2_exchange(code)
- except client.FlowExchangeError, e:
- print 'Authentication has failed: %s' % e
- sys.exit(1)
- else:
- print ('OAuth 2.0 authorization successful!\n\n'
- 'Your access token is:\n %s\n\nYour refresh token is:\n %s'
- % (credential.access_token, credential.refresh_token))
-
-
-if __name__ == '__main__':
- main()
diff --git a/examples/dfa/v1_20/add_advertiser_user_filter.py b/examples/dfa/v1_20/add_advertiser_user_filter.py
deleted file mode 100755
index 582d7cda..00000000
--- a/examples/dfa/v1_20/add_advertiser_user_filter.py
+++ /dev/null
@@ -1,87 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Adds a filter to a user profile, limiting its access to certain advertisers.
-
-To get user IDs, run get_users.py. To get advertiser IDs, run
-get_advertisers.py.
-
-A similar pattern can be applied to set filters limiting site, user role,
-and/or campaign access for any user. To get the Filter Criteria Type ID, run
-get_user_filter_types.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: user.getUser, user.saveUser
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-USER_ID = 'INSERT_USER_ID_HERE'
-ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE'
-
-
-def main(client, user_id, advertiser_id):
- # Initialize appropriate service.
- user_service = client.GetService(
- 'user', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Retrieve the user who is to be modified.
- user = user_service.getUser(user_id)
-
- # Create and configure a user filter.
- advertiser_filter = {
- # The following field has been filled in to make a filter that allows a
- # user to access only the assigned objects.
- # This value was determined using get_user_filter_types.py.
- 'userFilterCriteriaId': '2',
- # Because this filter used the criteria type "Assigned" it is necessary
- # to specify what advertisers this user has access to. This next step
- # would be skipped for the criteria types "All" and "None".
-
- # Create a list of object filters to represent each object the user has
- # access to. Since this is an advertiser filter, the list elements
- # represent an advertiser each. The size of the list will need to match
- # the total number of advertisers the user is assigned.
- 'objectFilters': [{
- 'id': advertiser_id
- }]
- }
-
- # Add the filter to the user.
- user['advertiserUserFilter'] = advertiser_filter
-
- # Save the changes made and display a success message.
- result = user_service.saveUser(user)
-
- if result:
- print 'User with ID \'%s\' was modified.' % result['id']
- else:
- print 'No user was modified.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client, USER_ID, ADVERTISER_ID)
-
diff --git a/examples/dfa/v1_20/assign_advertisers_to_advertiser_group.py b/examples/dfa/v1_20/assign_advertisers_to_advertiser_group.py
deleted file mode 100755
index 9944e6c3..00000000
--- a/examples/dfa/v1_20/assign_advertisers_to_advertiser_group.py
+++ /dev/null
@@ -1,55 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example assigns a list of advertisers to an advertiser group.
-
-CAUTION: An advertiser that has campaigns associated with it cannot be
-removed from an advertiser group once assigned.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: advertisergroup.assignAdvertisersToAdvertiserGroup
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-ADVERTISER_IDS = ['INSERT_FIRST_ADVERTISER_ID_HERE',
- 'INSERT_SECOND_ADVERTISER_ID_HERE']
-ADVERTISER_GROUP_IDS = 'INSERT_ADVERTISER_GROUP_ID_HERE'
-
-
-def main(client, advertiser_ids, advertiser_group_id):
- # Initialize appropriate service.
- advertiser_group_service = client.GetService(
- 'advertisergroup', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Assign the advertisers to the advertiser group.
- advertiser_group_service.assignAdvertisersToAdvertiserGroup(
- advertiser_group_id, advertiser_ids)
- print 'Advertisers have been updated.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client, ADVERTISER_IDS, ADVERTISER_GROUP_IDS)
diff --git a/examples/dfa/v1_20/assign_creatives_to_placements.py b/examples/dfa/v1_20/assign_creatives_to_placements.py
deleted file mode 100755
index 51703c1a..00000000
--- a/examples/dfa/v1_20/assign_creatives_to_placements.py
+++ /dev/null
@@ -1,78 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Assigns creatives to placements and creates a unique ad for each assignment.
-
-To get creatives, run get_creatives.py example. To get placements,
-run get_placement.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: creative.assignCreativesToPlacements
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-CREATIVE_IDS = ['INSERT_FIRST_CREATIVE_ID', 'INSERT_SECOND_CREATIVE_ID']
-PLACEMENT_IDS = ['INSERT_FIRST_PLACEMENT_ID', 'INSERT_SECOND_PLACEMENT_ID']
-
-
-def main(client, creative_ids, placement_ids):
- # Initialize appropriate service.
- creative_service = client.GetService(
- 'creative', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Create creative placement assignment structure.
- creative_placement_assignments = []
- for index in range(len(creative_ids)):
- creative_placement_assignments.append({
- 'xsi_type': 'CreativePlacementAssignment',
- 'creativeId': creative_ids[index],
- 'placementId': placement_ids[index],
- 'placementIds': placement_ids
- })
-
- # Submit the request.
- results = creative_service.assignCreativesToPlacements(
- creative_placement_assignments)
-
- # Display results.
- if results:
- for assignment_result in results:
- if assignment_result['errorMessage'] is None:
- print ('Ad with name \'%s\' and ID \'%s\' was created.' %
- (assignment_result['adName'], assignment_result['adId']))
- else:
- print ('Assignment unsuccessful for creative ID \'%s\' and placementID'
- ' \'%s\'. Error message says \'%s\'.'
- % (assignment_result['creativeId'],
- assignment_result['placementId'],
- assignment_result['errorMessage']))
- else:
- print 'No ads were created.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client, CREATIVE_IDS, PLACEMENT_IDS)
diff --git a/examples/dfa/v1_20/create_advertiser.py b/examples/dfa/v1_20/create_advertiser.py
deleted file mode 100755
index 96ba7e38..00000000
--- a/examples/dfa/v1_20/create_advertiser.py
+++ /dev/null
@@ -1,55 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates an advertiser in a given DFA network.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: advertiser.saveAdvertiser
-"""
-
-__author__ = 'Joseph DiLallo'
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-def main(client):
- # Initialize appropriate service.
- advertiser_service = client.GetService(
- 'advertiser', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Construct and save advertiser.
- advertiser = {
- 'name': 'Advertiser %s' % uuid.uuid4(),
- 'approved': 'true'
- }
-
- result = advertiser_service.saveAdvertiser(advertiser)
-
- # Display results.
- print 'Advertiser with ID \'%s\' was created.' % result['id']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client)
diff --git a/examples/dfa/v1_20/create_advertiser_group.py b/examples/dfa/v1_20/create_advertiser_group.py
deleted file mode 100755
index e0e2e490..00000000
--- a/examples/dfa/v1_20/create_advertiser_group.py
+++ /dev/null
@@ -1,54 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates an advertiser group.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: advertisergroup.saveAdvertiserGroup
-"""
-
-__author__ = 'Joseph DiLallo'
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-def main(client):
- # Initialize appropriate service.
- advertiser_group_service = client.GetService(
- 'advertisergroup', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Construct and save advertiser.
- advertiser_group = {
- 'name': 'AdvertiserGroup %s' % uuid.uuid4()
- }
- result = advertiser_group_service.saveAdvertiserGroup(
- advertiser_group)
-
- # Display results.
- print 'Advertiser group with ID \'%s\' was created.' % result['id']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client)
diff --git a/examples/dfa/v1_20/create_campaign.py b/examples/dfa/v1_20/create_campaign.py
deleted file mode 100755
index 53969e95..00000000
--- a/examples/dfa/v1_20/create_campaign.py
+++ /dev/null
@@ -1,83 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates a campaign in a given advertiser.
-
-To create an advertiser, run create_advertiser.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: campaign.saveCampaign
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE'
-CAMPAIGN_NAME = 'INSERT_CAMPAIGN_NAME_HERE'
-URL = 'INSERT_LANDING_PAGE_URL_HERE'
-LANDING_PAGE_NAME = 'INSERT_LANDING_PAGE_NAME_HERE'
-START_DATE = '%(year)s-%(month)02d-%(day)02dT12:00:00' % {
- 'year': 'INSERT_START_YEAR_HERE',
- 'month': int('INSERT_START_MONTH_HERE'),
- 'day': int('INSERT_START_DAY_HERE')}
-END_DATE = '%(year)s-%(month)02d-%(day)02dT12:00:00' % {
- 'year': 'INSERT_END_YEAR_HERE',
- 'month': int('INSERT_END_MONTH_HERE'),
- 'day': int('INSERT_END_DAY_HERE')}
-
-
-def main(client, advertiser_id, campaign_name, url, landing_page_name,
- start_date, end_date):
- # Initialize appropriate service.
- campaign_service = client.GetService(
- 'campaign', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Create a default landing page for the campaign and save it.
- default_landing_page = {
- 'url': url,
- 'name': landing_page_name
- }
-
- default_landing_page_id = campaign_service.saveLandingPage(
- default_landing_page)['id']
-
- # Construct and save the campaign.
- campaign = {
- 'name': campaign_name,
- 'advertiserId': advertiser_id,
- 'defaultLandingPageId': default_landing_page_id,
- 'archived': 'false',
- 'startDate': start_date,
- 'endDate': end_date
- }
- result = campaign_service.saveCampaign(campaign)
-
- # Display results.
- print 'Campaign with ID \'%s\' was created.' % result['id']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client, ADVERTISER_ID, CAMPAIGN_NAME, URL, LANDING_PAGE_NAME,
- START_DATE, END_DATE)
diff --git a/examples/dfa/v1_20/create_content_category.py b/examples/dfa/v1_20/create_content_category.py
deleted file mode 100755
index d9a19808..00000000
--- a/examples/dfa/v1_20/create_content_category.py
+++ /dev/null
@@ -1,54 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates a content category with the given name and description.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: contentcategory.saveContentCategory
-"""
-
-__author__ = 'Joseph DiLallo'
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-def main(client):
- # Initialize appropriate service.
- content_category_service = client.GetService(
- 'contentcategory', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Construct and save content category.
- content_category = {
- 'name': 'Category %s' % uuid.uuid4()
- }
- result = content_category_service.saveContentCategory(
- content_category)
-
- # Display results.
- print 'Content category with ID \'%s\' was created.' % result['id']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client)
diff --git a/examples/dfa/v1_20/create_creative_field.py b/examples/dfa/v1_20/create_creative_field.py
deleted file mode 100755
index 5b58666c..00000000
--- a/examples/dfa/v1_20/create_creative_field.py
+++ /dev/null
@@ -1,59 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates a creative field associated with a given advertiser.
-
-To get an advertiser ID, run get_advertisers.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: creativefield.saveCreativeField
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE'
-CREATIVE_FIELD_NAME = 'INSERT_CREATIVE_FIELD_NAME_HERE'
-
-
-def main(client, advertiser_id, creative_field_name):
- # Initialize appropriate service.
- creative_field_service = client.GetService(
- 'creativefield', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Construct and save creative field.
- creative_field = {
- 'name': creative_field_name,
- 'advertiserId': advertiser_id,
- 'id': '-1'
- }
- result = creative_field_service.saveCreativeField(creative_field)
-
- # Display results.
- print 'Creative field with ID \'%s\' was created.' % result['id']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client, ADVERTISER_ID, CREATIVE_FIELD_NAME)
diff --git a/examples/dfa/v1_20/create_creative_field_value.py b/examples/dfa/v1_20/create_creative_field_value.py
deleted file mode 100755
index e2cbf7a7..00000000
--- a/examples/dfa/v1_20/create_creative_field_value.py
+++ /dev/null
@@ -1,60 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Creates a creative field value associated with a given creative field.
-
-To get the creative field ID, run get_creative_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: creativefield.saveCreativeFieldValue
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-CREATIVE_FIELD_ID = 'INSERT_CREATIVE_FIELD_ID_HERE'
-CREATIVE_FIELD_VALUE_NAME = 'INSERT_CREATIVE_FIELD_VALUE_NAME_HERE'
-
-
-def main(client, creative_field_id, creative_field_value_name):
- # Initialize appropriate service.
- creative_field_service = client.GetService(
- 'creativefield', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Construct and save creative field value.
- creative_field_value = {
- 'name': creative_field_value_name,
- 'creativeFieldId': creative_field_id,
- 'id': '-1'
- }
- result = creative_field_service.saveCreativeFieldValue(
- creative_field_value)
-
- # Display results.
- print 'Creative field value with ID \'%s\' was created.' % result['id']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client, CREATIVE_FIELD_ID, CREATIVE_FIELD_VALUE_NAME)
diff --git a/examples/dfa/v1_20/create_creative_group.py b/examples/dfa/v1_20/create_creative_group.py
deleted file mode 100755
index 5eb25fa3..00000000
--- a/examples/dfa/v1_20/create_creative_group.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates a creative group associated with a given advertiser.
-
-To get an advertiser ID, run get_advertisers.py. Valid group numbers are limited
-to 1 or 2.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: creativegroup.saveCreativeGroup
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE'
-GROUP_NUMBER = 'INSERT_GROUP_NUMBER_HERE'
-CREATIVE_GROUP_NAME = 'INSERT_CREATIVE_GROUP_NAME_HERE'
-
-
-def main(client, advertiser_id, group_number, creative_group_name):
- # Initialize appropriate service.
- creative_group_service = client.GetService(
- 'creativegroup', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Construct and save creative group.
- creative_group = {
- 'name': creative_group_name,
- 'id': '-1',
- 'advertiserId': advertiser_id,
- 'groupNumber': group_number
- }
- result = creative_group_service.saveCreativeGroup(creative_group)
-
- # Display results.
- print 'Creative group with ID \'%s\' was created.' % result['id']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client, ADVERTISER_ID, GROUP_NUMBER, CREATIVE_GROUP_NAME)
diff --git a/examples/dfa/v1_20/create_flash_inpage_creative.py b/examples/dfa/v1_20/create_flash_inpage_creative.py
deleted file mode 100755
index 06d7026e..00000000
--- a/examples/dfa/v1_20/create_flash_inpage_creative.py
+++ /dev/null
@@ -1,84 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Creates a "Flash InPage" creative in a given advertiser or campaign.
-
-If no campaign is specified then the creative is created in the advertiser
-provided. To get assets file names, run create_html_asset.py and
-create_image_asset.py. To get a size ID, run get_size.py. To get a creative
-type ID, run get_creative_type.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: creative.saveCreative
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE'
-CREATIVE_NAME = 'INSERT_CREATIVE_NAME_HERE'
-SWF_ASSET_FILE_NAME = 'INSERT_SWF_ASSET_FILE_NAME_HERE'
-IMG_ASSET_FILE_NAME = 'INSERT_IMG_ASSET_FILE_NAME_HERE'
-SIZE_ID = 'INSERT_SIZE_ID_HERE'
-
-
-def main(client, campaign_id, advertiser_id, creative_name, swf_asset_file_name,
- img_asset_file_name, size_id):
- # Initialize appropriate service.
- creative_service = client.GetService(
- 'creative', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Construct and save flash inpage creative structure.
- flash_inpage_creative = {
- 'name': creative_name,
- 'id': '0',
- 'advertiserId': advertiser_id,
- 'typeId': '24',
- 'sizeId': size_id,
- 'codeLocked': 'true',
- 'active': 'true',
- 'parentFlashAsset': {
- 'assetFilename': swf_asset_file_name
- },
- 'wmode': 'opaque',
- 'backupImageAsset': {
- 'assetFilename': img_asset_file_name
- },
- 'backupImageTargetWindow': {
- 'option': '_blank'
- }
- }
-
- result = creative_service.saveCreative(
- flash_inpage_creative, campaign_id)
-
- # Display results.
- print 'Flash inpage creative with ID \'%s\' was created.' % result['id']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client, CAMPAIGN_ID, ADVERTISER_ID, CREATIVE_NAME,
- SWF_ASSET_FILE_NAME, IMG_ASSET_FILE_NAME, SIZE_ID)
diff --git a/examples/dfa/v1_20/create_html_asset.py b/examples/dfa/v1_20/create_html_asset.py
deleted file mode 100755
index 6e24dd83..00000000
--- a/examples/dfa/v1_20/create_html_asset.py
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates a HTML creative asset in a given advertiser.
-
-To create an advertiser, run create_advertiser.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: creative.saveCreativeAsset
-"""
-
-__author__ = 'Joseph DiLallo'
-
-import base64
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE'
-ASSET_NAME = 'INSERT_SWF_ASSET_NAME_HERE'
-PATH_TO_FILE = 'INSERT_PATH_TO_SWF_FILE_HERE'
-
-
-def main(client, advertiser_id, asset_name, path_to_file):
- # Initialize appropriate service.
- creative_service = client.GetService(
- 'creative', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Convert file into format that can be sent in SOAP messages.
- with open(path_to_file, 'r') as file_handle:
- content = base64.encodestring(file_handle.read())
-
- # Construct and save HTML asset.
- html_asset = {
- 'name': asset_name,
- 'advertiserId': advertiser_id,
- 'content': content,
- # Set he following to true if this asset is being used for HTML creative.
- 'forHTMLCreatives': 'true'
- }
- result = creative_service.saveCreativeAsset(html_asset)
-
- # Display results.
- print ('Creative asset with file name of \'%s\' was created.'
- % result['savedFilename'])
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client, ADVERTISER_ID, ASSET_NAME, PATH_TO_FILE)
diff --git a/examples/dfa/v1_20/create_image_asset.py b/examples/dfa/v1_20/create_image_asset.py
deleted file mode 100755
index 52960c0b..00000000
--- a/examples/dfa/v1_20/create_image_asset.py
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates an image creative asset in a given advertiser.
-
-To create an advertiser, run create_advertiser.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: creative.saveCreativeAsset
-"""
-
-__author__ = 'Joseph DiLallo'
-
-import base64
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE'
-ASSET_NAME = 'INSERT_IMAGE_ASSET_NAME_HERE'
-PATH_TO_FILE = 'INSERT_PATH_TO_IMAGE_FILE_HERE'
-
-
-def main(client, advertiser_id, asset_name, path_to_file):
- # Initialize appropriate service.
- creative_service = client.GetService(
- 'creative', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Convert file into format that can be sent in SOAP messages.
- with open(path_to_file, 'r') as file_handle:
- content = base64.encodestring(file_handle.read())
-
- # Construct and save image asset.
- image_asset = {
- 'name': asset_name,
- 'advertiserId': advertiser_id,
- 'content': content,
- 'forHTMLCreatives': 'false'
- }
- result = creative_service.saveCreativeAsset(image_asset)
-
- # Display results.
- print ('Creative asset with file name of \'%s\' was created.'
- % result['savedFilename'])
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client, ADVERTISER_ID, ASSET_NAME, PATH_TO_FILE)
diff --git a/examples/dfa/v1_20/create_in_stream_video_creative.py b/examples/dfa/v1_20/create_in_stream_video_creative.py
deleted file mode 100755
index 2d368726..00000000
--- a/examples/dfa/v1_20/create_in_stream_video_creative.py
+++ /dev/null
@@ -1,87 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Creates an In-Stream video creative associated with a given advertiser.
-
-If a campaign is specified, the creative is also associated with that campaign.
-
-To associate In-Stream assets with an In-Stream video creative, first create
-the creative and then run upload_in_stream_asset.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: creative.saveCreative
-"""
-
-__author__ = 'Joseph DiLallo'
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-# Set the parameters for the new In-Stream video creative.
-ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE'
-VIDEO_DURATION = 'INSERT_VIDEO_DURATION_HERE'
-AD_ID = 'INSERT_VAST_AD_ID_HERE'
-SURVEY_URL = 'INSERT_VAST_SURVEY_URL_HERE'
-CLICK_THROUGH_URL = 'INSERT_VAST_CLICK_THROUGH_URL_HERE'
-# You may optionally set a campaign ID. If the campaign ID is set to 0, then the
-# creative will be associated only with the advertiser.
-CAMPAIGN_ID = '0'
-
-
-def main(client, advertiser_id, video_duration, ad_id, survey_url,
- click_through_url, campaign_id):
- # Initialize appropriate service.
- creative_service = client.GetService(
- 'creative', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Create the In-Stream video creative.
- in_stream_video_creative = {
- 'advertiserId': advertiser_id,
- 'name': 'In-Stream Video Creative #%s' % uuid.uuid4(),
- 'videoDuration': video_duration,
- # In-Stream video creatives have to be created inactive. One can only be
- # set active after at least one media file has been added to it or the API
- # will return an error message.
- 'active': 'false',
-
- # Set the video details based on the Video Ad Serving Template (VAST)
- # specification.
- 'adId': ad_id,
- 'description': 'You are viewing an In-Stream Video Creative',
- 'surveyUrl': survey_url,
- 'clickThroughUrl': click_through_url
- }
-
- # Save the In-Stream video creative.
- result = creative_service.saveCreative(
- in_stream_video_creative, campaign_id)
-
- # Display the new creative ID.
- print 'In-Stream video creative with ID \'%s\' was created.' % result['Id']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client, ADVERTISER_ID, VIDEO_DURATION, AD_ID, SURVEY_URL,
- CLICK_THROUGH_URL, CAMPAIGN_ID)
diff --git a/examples/dfa/v1_20/create_placement.py b/examples/dfa/v1_20/create_placement.py
deleted file mode 100755
index f7d5ee70..00000000
--- a/examples/dfa/v1_20/create_placement.py
+++ /dev/null
@@ -1,92 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates a placement in a given campaign.
-
-Requires the DFA site ID and campaign ID in which the placement will be created
-into. To create a campaign, run create_campaign.py. To get DFA site ID, run
-get_dfa_site.py. To get a size ID, run get_size.py. To get placement types, run
-get_placement_types.py. To get pricing types, run get_pricing_types.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: placement.savePlacement
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-PLACEMENT_NAME = 'INSERT_PLACEMENT_NAME_HERE'
-DFA_SITE_ID = 'INSERT_DFA_SITE_ID_HERE'
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-PRICING_TYPE = 'INSERT_PRICING_TYPE_HERE'
-PLACEMENT_TYPE = 'INSERT_PLACEMENT_TYPE_HERE'
-SIZE_ID = 'INSERT_SIZE_ID_HERE'
-START_DATE = '%(year)s-%(month)02d-%(day)02dT12:00:00' % {
- 'year': 'INSERT_START_YEAR_HERE',
- 'month': int('INSERT_START_MONTH_HERE'),
- 'day': int('INSERT_START_DAY_HERE')}
-END_DATE = '%(year)s-%(month)02d-%(day)02dT12:00:00' % {
- 'year': 'INSERT_END_YEAR_HERE',
- 'month': int('INSERT_END_MONTH_HERE'),
- 'day': int('INSERT_END_DAY_HERE')}
-
-
-def main(client, placement_name, dfa_site_id, campaign_id, pricing_type,
- placement_type, size_id, start_date, end_date):
- # Initialize appropriate service.
- placement_service = client.GetService(
- 'placement', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Construct and save placement.
- placement = {
- 'name': placement_name,
- 'campaignId': campaign_id,
- 'dfaSiteId': dfa_site_id,
- 'sizeId': size_id,
- 'placementType': placement_type,
- 'pricingSchedule': {
- 'startDate': start_date,
- 'endDate': end_date,
- 'pricingType': pricing_type
- }
- }
-
- # Set placement tag settings.
- tag_options = placement_service.getRegularPlacementTagOptions()
- tag_types = []
- for tag_listing in tag_options:
- tag_types.append(tag_listing['id'])
-
- placement['tagSettings'] = {'tagTypes': tag_types}
-
- result = placement_service.savePlacement(placement)
-
- # Display results.
- print 'Placement with ID \'%s\' was created.' % result['id']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client, PLACEMENT_NAME, DFA_SITE_ID, CAMPAIGN_ID, PRICING_TYPE,
- PLACEMENT_TYPE, SIZE_ID, START_DATE, END_DATE)
diff --git a/examples/dfa/v1_20/create_placement_strategy.py b/examples/dfa/v1_20/create_placement_strategy.py
deleted file mode 100755
index e47abf04..00000000
--- a/examples/dfa/v1_20/create_placement_strategy.py
+++ /dev/null
@@ -1,54 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates a placement strategy with the given name.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: strategy.savePlacementStrategy
-"""
-
-__author__ = 'Joseph DiLallo'
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-def main(client):
- # Initialize appropriate service.
- placement_strategy_service = client.GetService(
- 'strategy', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Construct and save placement strategy.
- placement_strategy = {
- 'name': 'Strategy %s' % uuid.uuid4()
- }
- result = placement_strategy_service.savePlacementStrategy(
- placement_strategy)
-
- # Display results.
- print 'Placement strategy with ID \'%s\' was created.' % result['id']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client)
diff --git a/examples/dfa/v1_20/create_rotation_group.py b/examples/dfa/v1_20/create_rotation_group.py
deleted file mode 100755
index afd14665..00000000
--- a/examples/dfa/v1_20/create_rotation_group.py
+++ /dev/null
@@ -1,104 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates a rotation group ad in a given campaign.
-
-To get ad types run get_ad_types.py. Start and end date for the ad must be
-within campaign start and end dates. To create creatives, run
-create_[type]_creative.py. To get available placements, run get_placements.py.
-To get a size ID, run get_size.py example.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ad.saveAd
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-SIZE_ID = 'INSERT_SIZE_ID_HERE'
-CREATIVE_ID = 'INSERT_CREATIVE_ID_HERE'
-PLACEMENT_ID = 'INSERT_PLACEMENT_ID_HERE'
-AD_NAME = 'INSERT_AD_NAME_HERE'
-START_DATE = '%(year)s-%(month)02d-%(day)02dT12:00:00' % {
- 'year': 'INSERT_START_YEAR_HERE',
- 'month': int('INSERT_START_MONTH_HERE'),
- 'day': int('INSERT_START_DAY_HERE')}
-END_DATE = '%(year)s-%(month)02d-%(day)02dT12:00:00' % {
- 'year': 'INSERT_END_YEAR_HERE',
- 'month': int('INSERT_END_MONTH_HERE'),
- 'day': int('INSERT_END_DAY_HERE')}
-
-
-def main(client, campaign_id, size_id, creative_id, placement_id, ad_name,
- start_date, end_date):
- # Initialize appropriate service.
- ad_service = client.GetService(
- 'ad', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Construct basic rotation group structure.
- rotation_group = {
- 'xsi_type': 'RotationGroup',
- 'name': ad_name,
- 'active': 'true',
- 'archived': 'false',
- 'campaignId': campaign_id,
- 'sizeId': size_id,
- 'typeId': '1',
- 'priority': '12',
- 'ratio': '1',
- 'rotationType': '1',
- 'startTime': start_date,
- 'endTime': end_date,
- }
-
- # Construct creative assignments and add them to the rotation group.
- creative_assignment = {
- 'active': 'true',
- 'creativeId': creative_id,
- 'clickThroughUrl': {
- 'defaultLandingPageUsed': 'true',
- 'landingPageId': '0'
- }
- }
- rotation_group['creativeAssignments'] = [creative_assignment]
-
- # Construct placement assignments and add them to the rotation group.
- placement_assignment = {
- 'active': 'true',
- 'placementId': placement_id
- }
- rotation_group['placementAssignments'] = [placement_assignment]
-
- # Save the rotation group.
- result = ad_service.saveAd(rotation_group)
-
- # Display results.
- print 'Ad with ID \'%s\' was created.' % result['id']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client, CAMPAIGN_ID, SIZE_ID, CREATIVE_ID, PLACEMENT_ID, AD_NAME,
- START_DATE, END_DATE)
diff --git a/examples/dfa/v1_20/create_spotlight_activity.py b/examples/dfa/v1_20/create_spotlight_activity.py
deleted file mode 100755
index 5c8387a1..00000000
--- a/examples/dfa/v1_20/create_spotlight_activity.py
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates a spotlight activity in a given activity group.
-
-To create an activity group, run create_spotlight_activity_group.py. To get tag
-methods types, run get_tag_methods.py. To get activity type IDs, run
-get_activity_types.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: spotlight.saveSpotlightActivity
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-ACTIVITY_GROUP_ID = 'INSERT_ACTIVITY_GROUP_ID_HERE'
-ACTIVITY_TYPE_ID = 'INSERT_ACTIVITY_TYPE_ID_HERE'
-TAG_METHOD_TYPE_ID = 'INSERT_TAG_METHOD_TYPE_ID_HERE'
-URL = 'INSERT_EXPECTED_URL_HERE'
-ACTIVITY_NAME = 'INSERT_ACTIVITY_NAME_HERE'
-
-
-def main(client, activity_group_id, activity_type_id, tag_method_type_id, url,
- activity_name):
- # Initialize appropriate service.
- spotlight_service = client.GetService(
- 'spotlight', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Construct and save spotlight activity.
- spotlight_activity = {
- 'name': activity_name,
- 'activityGroupId': activity_group_id,
- 'activityTypeId': activity_type_id,
- 'tagMethodTypeId': tag_method_type_id,
- 'expectedUrl': url
- }
- result = spotlight_service.saveSpotlightActivity(spotlight_activity)
-
- # Display results.
- print 'Spotlight activity with ID \'%s\' was created.' % result['id']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client, ACTIVITY_GROUP_ID, ACTIVITY_TYPE_ID, TAG_METHOD_TYPE_ID, URL,
- ACTIVITY_NAME)
diff --git a/examples/dfa/v1_20/create_spotlight_activity_group.py b/examples/dfa/v1_20/create_spotlight_activity_group.py
deleted file mode 100755
index 7b40dc31..00000000
--- a/examples/dfa/v1_20/create_spotlight_activity_group.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Creates a new activity group for a given spotlight configuration.
-
-To get spotlight tag configuration, run get_advertisers.py. To get activity
-types, run get_activity_types.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: spotlight.saveSpotlightActivityGroup
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-SPOTLIGHT_CONFIGURATION_ID = 'INSERT_SPOTLIGHT_CONFIGURATION_ID_HERE'
-ACTIVITY_TYPE = 'INSERT_ACTIVITY_TYPE_HERE'
-GROUP_NAME = 'INSERT_GROUP_NAME_HERE'
-
-
-def main(client, spotlight_configuration_id, activity_type, group_name):
- # Initialize appropriate service.
- spotlight_service = client.GetService(
- 'spotlight', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Construct and save spotlight activity group.
- spotlight_activity_group = {
- 'name': group_name,
- 'spotlightConfigurationId': spotlight_configuration_id,
- 'groupType': activity_type
- }
- result = spotlight_service.saveSpotlightActivityGroup(
- spotlight_activity_group)
-
- # Display results.
- print 'Spotlight activity group with ID \'%s\' was created.' % result['id']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client, SPOTLIGHT_CONFIGURATION_ID, ACTIVITY_TYPE, GROUP_NAME)
diff --git a/examples/dfa/v1_20/create_subnetwork.py b/examples/dfa/v1_20/create_subnetwork.py
deleted file mode 100755
index ba11a5e8..00000000
--- a/examples/dfa/v1_20/create_subnetwork.py
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates a subnetwork in a given DFA network.
-
-To get the network ID, run get_users.py. To get the available permissions, run
-get_available_permissions.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: subnetwork.saveSubnetwork
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-NETWORK_ID = 'INSERT_NETWORK_ID_HERE'
-SUBNETWORK_NAME = 'INSERT_SUBNETWORK_NAME_HERE'
-PERMISSION1 = 'INSERT_FIRST_PERMISSION_ID_HERE'
-PERMISSION2 = 'INSERT_SECOND_PERMISSION_ID_HERE'
-
-
-def main(client, network_id, subnetwork_name, permission1, permission2):
- # Initialize appropriate service.
- subnetwork_service = client.GetService(
- 'subnetwork', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Construct and the basic subnetwork structure.
- subnetwork = {
- 'name': subnetwork_name,
- 'networkId': network_id
- }
-
- # Create an array of all permissions assigned to this subnetwork and add it to
- # the subnetwork structure. To get a list of available permissions, run
- # get_available_permissions.py.
- subnetwork['availablePermissions'] = [permission1, permission2]
-
- # Save the subnetwork.
- result = subnetwork_service.saveSubnetwork(subnetwork)
-
- # Display results.
- print 'Subnetwork with ID \'%s\' was created.' % result['id']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client, NETWORK_ID, SUBNETWORK_NAME, PERMISSION1, PERMISSION2)
diff --git a/examples/dfa/v1_20/create_user_role.py b/examples/dfa/v1_20/create_user_role.py
deleted file mode 100755
index 4d2407aa..00000000
--- a/examples/dfa/v1_20/create_user_role.py
+++ /dev/null
@@ -1,79 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates a user role in a given DFA subnetwork.
-
-To get the subnetwork ID, run get_subnetworks.py. To get the available
-permissions, run get_available_permissions.py. To get the parent user role ID,
-run get_user_roles.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: userrole.saveUserRole
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-USER_ROLE_NAME = 'INSERT_USER_ROLE_NAME_HERE'
-SUBNETWORK_ID = 'INSERT_SUBNETWORK_ID_HERE'
-PARENT_USER_ROLE_ID = 'INSERT_PARENT_USER_ROLE_ID_HERE'
-PERMISSION1_ID = 'INSERT_FIRST_PERMISSION_ID_HERE'
-PERMISSION2_ID = 'INSERT_SECOND_PERMISSION_ID_HERE'
-
-
-def main(client, user_role_name, subnetwork_id, parent_user_role_id,
- permission1_id, permission2_id):
- # Initialize appropriate service.
- user_role_service = client.GetService(
- 'userrole', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Construct and the basic user role structure.
- user_role = {
- 'name': user_role_name,
- 'subnetworkId': subnetwork_id,
- 'parentUserRoleId': parent_user_role_id
- }
-
- # Create an array of all permissions assigned to this user role and add it to
- # the user role structure. To get a list of available permissions, run
- # get_available_permissions.py.
- permission1 = {
- 'id': permission1_id
- }
- permission2 = {
- 'id': permission2_id
- }
- user_role['permissions'] = [permission1, permission2]
-
- # Save the user role.
- result = user_role_service.saveUserRole(user_role)
-
- # Display results.
- print 'User role with ID \'%s\' was created.' % result['id']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client, USER_ROLE_NAME, SUBNETWORK_ID, PARENT_USER_ROLE_ID,
- PERMISSION1_ID, PERMISSION2_ID)
diff --git a/examples/dfa/v1_20/download_tags.py b/examples/dfa/v1_20/download_tags.py
deleted file mode 100755
index bd74c3a4..00000000
--- a/examples/dfa/v1_20/download_tags.py
+++ /dev/null
@@ -1,84 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example downloads HTML Tags for a given campaign and placement ID.
-
-To create campaigns, run create_campaign.py. To create placements, run
-create_placement.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: placement.getPlacementTagData
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
-PLACEMENT_ID = 'INSERT_PLACEMENT_ID_HERE'
-
-
-def main(client, campaign_id, placement_id):
- # Initialize appropriate service.
- placement_service = client.GetService(
- 'placement', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Set placement tag search criteria.
- placement_tag_criteria = {
- 'id': placement_id
- }
-
- # Get placement tag options.
- tag_options = placement_service.getRegularPlacementTagOptions()
- tag_types = [tag_listing['id'] for tag_listing in tag_options]
-
- # Add all types of tag options to the search criteria.
- placement_tag_criteria['tagOptionIds'] = tag_types
-
- # Create a list of placement tag search criterias.
- placement_tag_criterias = [placement_tag_criteria]
-
- # Get HTML tags for the placements.
- results = placement_service.getPlacementTagData(
- campaign_id, placement_tag_criterias)
-
- # Display tags for the placement ID used as criteria.
- for result in results:
- for placement_tag_info in result['placementTagInfos']:
- print 'Iframe/JavaScript tag for placement \'%s\' is \n%s\n' % (
- placement_tag_info['placement']['name'],
- placement_tag_info['iframeJavaScriptTag'])
- print 'JavaScript tag for placement \'%s\' is \n%s\n' % (
- placement_tag_info['placement']['name'],
- placement_tag_info['javaScriptTag'])
- print 'Standard tag for placement \'%s\' is \n%s\n' % (
- placement_tag_info['placement']['name'],
- placement_tag_info['standardTag'])
- print 'Internal Redirect tag for placement \'%s\' is \n%s\n' % (
- placement_tag_info['placement']['name'],
- placement_tag_info['internalRedirectTag'])
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client, CAMPAIGN_ID, PLACEMENT_ID)
diff --git a/examples/dfa/v1_20/get_activity_groups.py b/examples/dfa/v1_20/get_activity_groups.py
deleted file mode 100755
index 848f617b..00000000
--- a/examples/dfa/v1_20/get_activity_groups.py
+++ /dev/null
@@ -1,65 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example displays activity groups names and IDs for a given advertiser.
-
-To create an advertiser, run create_advertiser.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: spotlight.getSpotlightActivityGroups
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE'
-
-
-def main(client, advertiser_id):
- # Initialize appropriate service.
- spotlight_service = client.GetService(
- 'spotlight', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Set activity group search criteria structure and use advertiser ID as search
- # criteria.
- spotlight_activity_group_search_criteria = {
- 'advertiserId': advertiser_id
- }
-
- # Get activity groups.
- results = spotlight_service.getSpotlightActivityGroups(
- spotlight_activity_group_search_criteria)
-
- # Display activity group names and IDs.
- if results['records']:
- for activity_group in results['records']:
- print ('Activity group with name \'%s\' and ID \'%s\' was found.'
- % (activity_group['name'], activity_group['id']))
- else:
- print 'No activity groups found for your criteria.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client, ADVERTISER_ID)
diff --git a/examples/dfa/v1_20/get_activity_types.py b/examples/dfa/v1_20/get_activity_types.py
deleted file mode 100755
index e7b064c1..00000000
--- a/examples/dfa/v1_20/get_activity_types.py
+++ /dev/null
@@ -1,53 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example displays activity type names and IDs.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: spotlight.getSpotlightActivityTypes
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-def main(client):
- # Initialize appropriate service.
- spotlight_service = client.GetService(
- 'spotlight', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Get activity types.
- results = spotlight_service.getSpotlightActivityTypes()
-
- # Display activity type names and IDs.
- if results:
- for activity_type in results:
- print ('Activity type with name \'%s\' and ID \'%s\' was found.'
- % (activity_type['name'], activity_type['id']))
- else:
- print 'No activity types found.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client)
diff --git a/examples/dfa/v1_20/get_ad_types.py b/examples/dfa/v1_20/get_ad_types.py
deleted file mode 100755
index 4692ebf1..00000000
--- a/examples/dfa/v1_20/get_ad_types.py
+++ /dev/null
@@ -1,54 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Retrieves available ad types and displays the name and ID for each type.
-
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ad.getAdTypes
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-def main(client):
- # Initialize appropriate service.
- ad_service = client.GetService(
- 'ad', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Get ad types.
- results = ad_service.getAdTypes()
-
- # Display ad type names and IDs.
- if results:
- for ad_type in results:
- print ('Ad type with name \'%s\' and ID \'%s\' was found.'
- % (ad_type['name'], ad_type['id']))
- else:
- print 'No activity types found.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client)
diff --git a/examples/dfa/v1_20/get_advertiser_groups.py b/examples/dfa/v1_20/get_advertiser_groups.py
deleted file mode 100755
index 003ff214..00000000
--- a/examples/dfa/v1_20/get_advertiser_groups.py
+++ /dev/null
@@ -1,64 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Displays advertiser groups for the given search criteria.
-
-Results are limited to the first 10 records.
-
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: advertisergroup.getAdvertiserGroups
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-def main(client):
- # Initialize appropriate service.
- advertiser_group_service = client.GetService(
- 'advertisergroup', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Create advertiser group search criteria structure.
- advertiser_group_search_criteria = {
- 'pageSize': '10'
- }
-
- # Get advertiser group record set.
- results = advertiser_group_service.getAdvertiserGroups(
- advertiser_group_search_criteria)
-
- # Display advertiser group names, IDs and advertiser count.
- if results['records']:
- for advertiser_group in results['records']:
- print ('Advertiser group with name \'%s\', ID \'%s\', containing %s'
- ' advertisers was found.' % (advertiser_group['name'],
- advertiser_group['id'],
- advertiser_group['advertiserCount']))
- else:
- print 'No advertiser groups found for your criteria.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client)
diff --git a/examples/dfa/v1_20/get_advertisers.py b/examples/dfa/v1_20/get_advertisers.py
deleted file mode 100755
index d759a0b9..00000000
--- a/examples/dfa/v1_20/get_advertisers.py
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Fetches all advertisers in a DFA account.
-
-This example displays advertiser name, ID and spotlight configuration ID for
-the given search criteria. Results are limited to first 10 records.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: advertiser.getAdvertisers
-"""
-
-__author__ = 'Joseph DiLallo'
-
-import googleads.dfa
-
-
-def main(client):
- # Initialize appropriate service.
- advertiser_service = client.GetService(
- 'advertiser', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Create advertiser search criteria structure.
- page_number = 1
- advertiser_search_criteria = {
- 'pageSize': '100',
- 'pageNumber': str(page_number)
- }
-
- while True:
- # Get advertiser record set.
- results = advertiser_service.getAdvertisers(advertiser_search_criteria)
-
- # Display advertiser names, IDs and spotlight configuration IDs.
- if results['records']:
- for advertiser in results['records']:
- print ('Advertiser with name \'%s\', ID \'%s\', and spotlight '
- 'configuration id \'%s\' was found.'
- % (advertiser['name'], advertiser['id'], advertiser['spotId']))
- page_number += 1
- advertiser_search_criteria['pageNumber'] = str(page_number)
- if page_number > int(results['totalNumberOfPages']):
- break
-
- print 'Number of results found: %s' % results['totalNumberOfRecords']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = googleads.dfa.DfaClient.LoadFromStorage()
- main(dfa_client)
diff --git a/examples/dfa/v1_20/get_available_permissions.py b/examples/dfa/v1_20/get_available_permissions.py
deleted file mode 100755
index 2ed69e68..00000000
--- a/examples/dfa/v1_20/get_available_permissions.py
+++ /dev/null
@@ -1,63 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Displays the permissions that a user role or subnetwork may be granted.
-
-To get a subnetwork ID, run get_subnetworks.py.
-
-A user role may not be set with more permissions than the subnetwork it
-belongs to. You may enter a subnetwork ID to see the maximum permissions a
-user role belonging to it can have, or enter '0' as the subnetwork ID to see
-all possible permissions.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: userrole.getAvailablePermissions
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-SUBNETWORK_ID = 'INSERT_SUBNETWORK_ID_HERE'
-
-
-def main(client, subnetwork_id):
- # Initialize appropriate service.
- user_role_service = client.GetService(
- 'userrole', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Get available permissions.
- results = user_role_service.getAvailablePermissions(subnetwork_id)
-
- # Display permission name and its ID.
- if results:
- for permission in results:
- print ('Permission with name \'%s\' and ID \'%s\' was found.'
- % (permission['name'], permission['id']))
- else:
- print 'No permissions found.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client, SUBNETWORK_ID)
diff --git a/examples/dfa/v1_20/get_campaigns.py b/examples/dfa/v1_20/get_campaigns.py
deleted file mode 100755
index ad8bf39f..00000000
--- a/examples/dfa/v1_20/get_campaigns.py
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets existing campaigns based on a given search criteria.
-
-Results are limited to the first 10.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: campaign.getCampaignsByCriteria
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-def main(client):
- # Initialize appropriate service.
- campaign_service = client.GetService(
- 'campaign', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Create campaign search criteria structure.
- page_number = 1
- campaign_search_criteria = {
- 'pageSize': '100',
- 'pageNumber': str(page_number)
- }
-
- while True:
- # Get campaign record set.
- results = campaign_service.getCampaignsByCriteria(
- campaign_search_criteria)
-
- # Display campaign names and IDs.
- if results['records']:
- for campaign in results['records']:
- print ('Campaign with name \'%s\' and ID \'%s\' was found.'
- % (campaign['name'], campaign['id']))
- page_number += 1
- campaign_search_criteria['pageNumber'] = str(page_number)
- if page_number > int(results['totalNumberOfPages']):
- break
-
- print 'Number of results found: %s' % results['totalNumberOfRecords']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client)
diff --git a/examples/dfa/v1_20/get_change_log_for_advertiser.py b/examples/dfa/v1_20/get_change_log_for_advertiser.py
deleted file mode 100755
index 8af6c0f9..00000000
--- a/examples/dfa/v1_20/get_change_log_for_advertiser.py
+++ /dev/null
@@ -1,77 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example displays the change logs of a specified advertiser object.
-
-Results are limited to the first 10 records.
-
-A similar pattern can be applied to get change logs for many other object
-types. Run get_change_log_object_types.py for a list of other supported object
-types and their ID numbers.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: changelog.getChangeLogRecords
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE'
-
-
-def main(client, advertiser_id):
- # Initialize appropriate service.
- change_log_service = client.GetService(
- 'changelog', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Create change log search criteria structure.
- change_log_search_criteria = {
- 'pageSize': '10',
- 'objectId': advertiser_id,
- # The following field has been filled in to choose advertiser change
- # logs. This values was determined using get_change_log_object_types.py.
- 'objectTypeId': '1'
- }
-
- # Get change log record set.
- results = change_log_service.getChangeLogRecords(
- change_log_search_criteria)
-
- # Display the contents of each change log record.
- if results['records']:
- for change_log in results['records']:
- print ('Action \'%s\', Context \'%s\', Change Date \'%s\','
- ' New Value \'%s\', Old Value \'%s\', Profile Name \'%s\''
- ' was found.'
- % (change_log['action'],
- change_log['context'], change_log['changeDate'],
- change_log['newValue'], change_log['oldValue'],
- change_log['username']))
- else:
- print 'No change log entries found for your criteria.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client, ADVERTISER_ID)
diff --git a/examples/dfa/v1_20/get_change_log_object_types.py b/examples/dfa/v1_20/get_change_log_object_types.py
deleted file mode 100755
index 9952c95c..00000000
--- a/examples/dfa/v1_20/get_change_log_object_types.py
+++ /dev/null
@@ -1,53 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example displays change log object type names and IDs.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: changelog.getChangeLogObjectTypes
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-def main(client):
- # Initialize appropriate service.
- change_log_service = client.GetService(
- 'changelog', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Get change log object types.
- results = change_log_service.getChangeLogObjectTypes()
-
- # Display change log object type names and IDs.
- if results:
- for object_type in results:
- print ('Change log object type with name \'%s\' and ID \'%s\' was found.'
- % (object_type['name'], object_type['id']))
- else:
- print 'No change log object types found.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client)
diff --git a/examples/dfa/v1_20/get_content_categories.py b/examples/dfa/v1_20/get_content_categories.py
deleted file mode 100755
index 7c0b1cc3..00000000
--- a/examples/dfa/v1_20/get_content_categories.py
+++ /dev/null
@@ -1,61 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example displays available content categories for a given search string.
-
-Results are limited to 10.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: contentcategory.getContentCategories
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-def main(client):
- # Initialize appropriate service.
- content_category_service = client.GetService(
- 'contentcategory', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Create content category search criteria structure.
- content_category_search_criteria = {
- 'pageSize': '10'
- }
-
- # Get content category record set.
- results = content_category_service.getContentCategories(
- content_category_search_criteria)
-
- # Display content category names, IDs and descriptions.
- if results['records']:
- for content_category in results['records']:
- print ('Content category with name \'%s\' and ID \'%s\' was found.'
- % (content_category['name'], content_category['id']))
- else:
- print 'No content categories found for your criteria.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client)
diff --git a/examples/dfa/v1_20/get_countries.py b/examples/dfa/v1_20/get_countries.py
deleted file mode 100755
index 358a2b85..00000000
--- a/examples/dfa/v1_20/get_countries.py
+++ /dev/null
@@ -1,60 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Displays all countries matching a search criteria.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: spotlight.getCountriesByCriteria
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-def main(client):
- # Initialize appropriate service.
- spotlight_service = client.GetService(
- 'spotlight', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Set search criteria.
- country_search_criteria = {
- 'secure': 'false'
- }
-
- # Get countries.
- results = spotlight_service.getCountriesByCriteria(
- country_search_criteria)
-
- # Display country names, codes and secure server support information.
- if results:
- for country in results:
- print ('Country with name \'%s\', country code \'%s\', and supports a'
- ' secure server? \'%s\'.'
- % (country['name'], country['countryCode'], country['secure']))
- else:
- print 'No countries found for your criteria.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client)
diff --git a/examples/dfa/v1_20/get_creative_field.py b/examples/dfa/v1_20/get_creative_field.py
deleted file mode 100755
index 6be814e4..00000000
--- a/examples/dfa/v1_20/get_creative_field.py
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Retrieves and displays available creative fields for a given string.
-
-Results are limited to the first 10.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: creativefield.getCreativeFields
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE'
-
-
-def main(client, advertiser_id):
- # Initialize appropriate service.
- creative_field_service = client.GetService(
- 'creativefield', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Set up creative field search criteria structure.
- creative_field_search_criteria = {
- 'advertiserIds': [advertiser_id],
- 'pageSize': '10'
- }
-
- # Get creative fields for the selected criteria.
- results = creative_field_service.getCreativeFields(
- creative_field_search_criteria)
-
- # Display creative field names, IDs, advertiser IDs, and number of values.
- if results['records']:
- for creative_field in results['records']:
- print ('Creative field with name \'%s\', ID \'%s\', advertiser ID \'%s\','
- ' and containing \'%s\' values was found.'
- % (creative_field['name'], creative_field['id'],
- creative_field['advertiserId'],
- creative_field['totalNumberOfValues']))
- else:
- print 'No creative fields found for your criteria.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client, ADVERTISER_ID)
diff --git a/examples/dfa/v1_20/get_creative_field_values.py b/examples/dfa/v1_20/get_creative_field_values.py
deleted file mode 100755
index c97e1ac2..00000000
--- a/examples/dfa/v1_20/get_creative_field_values.py
+++ /dev/null
@@ -1,63 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Retrieves and displays available creative field values for a given string.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: creativefield.getCreativeFieldValues
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-CREATIVE_FIELD_ID = 'INSERT_CREATIVE_FIELD_ID_HERE'
-
-
-def main(client, creative_field_id):
- # Initialize appropriate service.
- creative_field_service = client.GetService(
- 'creativefield', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Set up creative field value search criteria structure.
- creative_field_value_search_criteria = {
- 'creativeFieldIds': [creative_field_id],
- 'pageSize': '10'
- }
-
- # Get creative field values for the selected criteria.
- results = creative_field_service.getCreativeFieldValues(
- creative_field_value_search_criteria)
-
- # Display creative field value names and IDs.
- if results['records']:
- for creative_field_value in results['records']:
- print ('Creative field value with name \'%s\' and ID \'%s\' was found.'
- % (creative_field_value['name'], creative_field_value['id']))
- else:
- print 'No creative field values found for your criteria.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client, CREATIVE_FIELD_ID)
diff --git a/examples/dfa/v1_20/get_creative_groups.py b/examples/dfa/v1_20/get_creative_groups.py
deleted file mode 100755
index 9f942270..00000000
--- a/examples/dfa/v1_20/get_creative_groups.py
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Retrieves and displays available creative groups for a given advertiser.
-
-To get an advertiser ID, run get_advertisers.py. Results are limited to the
-first 10.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: creativegroup.getCreativeGroups
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE'
-
-
-def main(client, advertiser_id):
- # Initialize appropriate service.
- creative_group_service = client.GetService(
- 'creativegroup', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Set up creative group search criteria structure.
- creative_group_search_criteria = {
- 'advertiserIds': [advertiser_id],
- }
-
- # Get creatives groups for the selected criteria.
- results = creative_group_service.getCreativeGroups(
- creative_group_search_criteria)
-
- # Display creative group names, IDs, advertiser IDs, and group numbers.
- if results['records']:
- for creative_field_value in results['records']:
- print ('Creative group with name \'%s\', ID \'%s\', advertiser ID \'%s\','
- ' and group number \'%s\' was found.'
- % (creative_field_value['name'], creative_field_value['id'],
- creative_field_value['advertiserId'],
- creative_field_value['groupNumber']))
- else:
- print 'No creative groups found for your criteria.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client, ADVERTISER_ID)
diff --git a/examples/dfa/v1_20/get_creative_types.py b/examples/dfa/v1_20/get_creative_types.py
deleted file mode 100755
index 09d7c7d8..00000000
--- a/examples/dfa/v1_20/get_creative_types.py
+++ /dev/null
@@ -1,53 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Gets available creative types and displays the name and ID for each type.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: creative.getCreativeTypes
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-def main(client):
- # Initialize appropriate service.
- creative_service = client.GetService(
- 'creative', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Get creative types.
- results = creative_service.getCreativeTypes()
-
- # Display creative types and IDs.
- if results:
- for creative_type in results:
- print ('Creative type with name \'%s\' and ID \'%s\' was found.'
- % (creative_type['name'], creative_type['id']))
- else:
- print 'No creative types found.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client)
diff --git a/examples/dfa/v1_20/get_creatives.py b/examples/dfa/v1_20/get_creatives.py
deleted file mode 100755
index cc891cd5..00000000
--- a/examples/dfa/v1_20/get_creatives.py
+++ /dev/null
@@ -1,72 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Retrieves and displays available creatives for a given advertiser.
-
-To create an advertiser, run create_advertiser.py. Results are limited to the
-first 10.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: creative.getCreatives
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE'
-
-
-def main(client, advertiser_id):
- # Initialize appropriate service.
- creative_service = client.GetService(
- 'creative', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Set up creative search criteria structure.
- page_number = 1
- creative_search_criteria = {
- 'advertiserId': advertiser_id,
- 'pageSize': '100',
- 'pageNumber': str(page_number)
- }
-
- while True:
- # Get creatives for the selected criteria.
- results = creative_service.getCreatives(creative_search_criteria)
-
- # Display creative name and its ID.
- if results['records']:
- for creative in results['records']:
- print ('Creative with name \'%s\' and ID \'%s\' was found.'
- % (creative['name'], creative['id']))
- page_number += 1
- creative_search_criteria['pageNumber'] = str(page_number)
- if page_number > int(results['totalNumberOfPages']):
- break
-
- print 'Number of results found: %s' % results['totalNumberOfRecords']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client, ADVERTISER_ID)
diff --git a/examples/dfa/v1_20/get_dfa_site.py b/examples/dfa/v1_20/get_dfa_site.py
deleted file mode 100755
index 38a15a56..00000000
--- a/examples/dfa/v1_20/get_dfa_site.py
+++ /dev/null
@@ -1,60 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets existing DFA sites based on a given search criteria.
-
-Results are limited to the first 10.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: site.getDfaSites
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-def main(client):
- # Initialize appropriate service.
- site_service = client.GetService(
- 'site', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Create DFA site search criteria structure.
- dfa_site_search_criteria = {
- 'pageSize': '10'
- }
-
- # Get the sites.
- results = site_service.getDfaSites(dfa_site_search_criteria)
-
- # Display DFA site names and IDs.
- if results['records']:
- for dfa_site in results['records']:
- print ('DFA site with name \'%s\' and ID \'%s\' was found.'
- % (dfa_site['name'], dfa_site['id']))
- else:
- print 'No DFA sites found for your criteria.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client)
diff --git a/examples/dfa/v1_20/get_placement_strategies.py b/examples/dfa/v1_20/get_placement_strategies.py
deleted file mode 100755
index e3852bd5..00000000
--- a/examples/dfa/v1_20/get_placement_strategies.py
+++ /dev/null
@@ -1,61 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Displays available placement strategies for a given search string.
-
-Results are limited to 10.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: strategy.getPlacementStrategiesByCriteria
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-def main(client):
- # Initialize appropriate service.
- placement_strategy_service = client.GetService(
- 'strategy', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Create placement strategy search criteria structure.
- placement_strategy_search_criteria = {
- 'pageSize': '10'
- }
-
- # Get placement strategy record set.
- results = placement_strategy_service.getPlacementStrategiesByCriteria(
- placement_strategy_search_criteria)
-
- # Display placement strategy names, IDs and descriptions.
- if results['records']:
- for placement in results['records']:
- print ('Placement strategy with name \'%s\' and ID \'%s\' was found.'
- % (placement['name'], placement['id']))
- else:
- print 'No placement strategies found for your criteria.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client)
diff --git a/examples/dfa/v1_20/get_placement_types.py b/examples/dfa/v1_20/get_placement_types.py
deleted file mode 100755
index b1e6004f..00000000
--- a/examples/dfa/v1_20/get_placement_types.py
+++ /dev/null
@@ -1,53 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example displays placement type names and IDs.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: placement.getPlacementTypes
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-def main(client):
- # Initialize appropriate service.
- placement_service = client.GetService(
- 'placement', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Get placement types.
- results = placement_service.getPlacementTypes()
-
- # Display placement type names and IDs.
- if results:
- for placement_type in results:
- print ('Placement type with name \'%s\' and ID \'%s\' was found.'
- % (placement_type['name'], placement_type['id']))
- else:
- print 'No placement types found.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client)
diff --git a/examples/dfa/v1_20/get_placements.py b/examples/dfa/v1_20/get_placements.py
deleted file mode 100755
index 3d9c9b2e..00000000
--- a/examples/dfa/v1_20/get_placements.py
+++ /dev/null
@@ -1,61 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example displays available placements for a given search string.
-
-Results are limited to 10.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: placement.getPlacementsByCriteria
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-def main(client):
- # Initialize appropriate service.
- placement_service = client.GetService(
- 'placement', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Set placement search criteria.
- placement_search_criteria = {
- 'pageSize': '10'
- }
-
- # Get placement types.
- results = placement_service.getPlacementsByCriteria(
- placement_search_criteria)
-
- # Display placement names and IDs.
- if results['records']:
- for placement in results['records']:
- print ('Placement with name \'%s\' and ID \'%s\' was found.'
- % (placement['name'], placement['id']))
- else:
- print 'No placements found for your criteria.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client)
diff --git a/examples/dfa/v1_20/get_pricing_types.py b/examples/dfa/v1_20/get_pricing_types.py
deleted file mode 100755
index 48d1c5a5..00000000
--- a/examples/dfa/v1_20/get_pricing_types.py
+++ /dev/null
@@ -1,53 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example displays placement pricing type names and IDs.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: placement.getPricingTypes
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-def main(client):
- # Initialize appropriate service.
- placement_service = client.GetService(
- 'placement', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Get placement pricing types.
- results = placement_service.getPricingTypes()
-
- # Display placement pricing type names and IDs.
- if results:
- for creative_type in results:
- print ('Pricing type with name \'%s\' and ID \'%s\' was found.'
- % (creative_type['name'], creative_type['id']))
- else:
- print 'No pricing types found.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client)
diff --git a/examples/dfa/v1_20/get_size.py b/examples/dfa/v1_20/get_size.py
deleted file mode 100755
index a60e7657..00000000
--- a/examples/dfa/v1_20/get_size.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets the size ID for a given width and height.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: size.getSize
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-WIDTH = 'INSERT_WIDTH_HERE'
-HEIGHT = 'INSERT_HEIGHT_HERE'
-
-
-def main(client, width, height):
- # Initialize appropriate service.
- size_service = client.GetService(
- 'size', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Create size search criteria.
- size_search_criteria = {
- 'width': width,
- 'height': height
- }
-
- # Get size.
- size_record_set = size_service.getSizes(size_search_criteria)
-
- # Display size ID.
- if size_record_set['records']:
- for size in size_record_set['records']:
- print 'Size id for \'%sx%s\' is \'%s\'.' % (width, height, size['id'])
- else:
- print 'No sizes found for your criteria.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client, WIDTH, HEIGHT)
diff --git a/examples/dfa/v1_20/get_subnetworks.py b/examples/dfa/v1_20/get_subnetworks.py
deleted file mode 100755
index eb578443..00000000
--- a/examples/dfa/v1_20/get_subnetworks.py
+++ /dev/null
@@ -1,66 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Displays subnetwork names, IDs, and subnetwork IDs for a given search string.
-
-Results are limited to 10.
-
-Note that the permissions assigned to a subnetwork are not returned in a
-human-readable format with this example. Run get_available_permissions.py to
-see what permissions are available on a subnetwork.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: subnetwork.getSubnetworks
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-def main(client):
- # Initialize appropriate service.
- subnetwork_service = client.GetService(
- 'subnetwork', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Set subnetwork search criteria.
- subnetwork_search_criteria = {
- 'pageSize': '10'
- }
-
- # Get subnetworks.
- results = subnetwork_service.getSubnetworks(
- subnetwork_search_criteria)
-
- # Display subnetwork names, IDs, and subnetwork IDs.
- if results['records']:
- for subnetwork in results['records']:
- print ('Subnetwork with name \'%s\', ID \'%s\', part of network ID \'%s\''
- ' was found.' % (subnetwork['name'], subnetwork['id'],
- subnetwork['networkId']))
- else:
- print 'No subnetworks found for your criteria.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client)
diff --git a/examples/dfa/v1_20/get_tag_method_types.py b/examples/dfa/v1_20/get_tag_method_types.py
deleted file mode 100755
index 044373fc..00000000
--- a/examples/dfa/v1_20/get_tag_method_types.py
+++ /dev/null
@@ -1,53 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example displays activity method type names and IDs.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: spotlight.getSpotlightTagMethodTypes
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-def main(client):
- # Initialize appropriate service.
- spotlight_service = client.GetService(
- 'spotlight', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Get method types.
- results = spotlight_service.getSpotlightTagMethodTypes()
-
- # Display method type names and IDs.
- if results:
- for method_type in results:
- print ('Method type with name \'%s\' and ID \'%s\' was found.'
- % (method_type['name'], method_type['id']))
- else:
- print 'No method types found.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client)
diff --git a/examples/dfa/v1_20/get_user_filter_types.py b/examples/dfa/v1_20/get_user_filter_types.py
deleted file mode 100755
index e7b9c28c..00000000
--- a/examples/dfa/v1_20/get_user_filter_types.py
+++ /dev/null
@@ -1,53 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example displays user filter criteria type names and IDs.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: user.getAvailableUserFilterCriteriaTypes
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-def main(client):
- # Initialize appropriate service.
- user_service = client.GetService(
- 'user', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Get user filter criteria types.
- results = user_service.getAvailableUserFilterCriteriaTypes()
-
- # Display user filter criteria types.
- if results:
- for filter_type in results:
- print ('User filter criteria type with name \'%s\' and ID \'%s\' was '
- 'found.' % (filter_type['name'], filter_type['id']))
- else:
- print 'No user filter criteria types found.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client)
diff --git a/examples/dfa/v1_20/get_user_roles.py b/examples/dfa/v1_20/get_user_roles.py
deleted file mode 100755
index fe41f565..00000000
--- a/examples/dfa/v1_20/get_user_roles.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Displays user roles for the given search criteria.
-
-Results are limited to the first 10 records.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: userrole.getUserRoles
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-def main(client):
- # Initialize appropriate service.
- user_role_service = client.GetService(
- 'userrole', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Set user role search criteria.
- user_role_search_criteria = {
- 'pageSize': '10'
- }
-
- # Get user roles that match the search criteria.
- results = user_role_service.getUserRoles(user_role_search_criteria)
-
- # Display user role names, IDs, subnetwork IDs, number of assigned users, and
- # assigned permissions.
- if results['userRoles']:
- for user_role in results['userRoles']:
- print ('User role with name \'%s\', ID \'%s\', subnetwork ID \'%s\', and '
- 'assigned to \'%s\' users was found.'
- % (user_role['name'], user_role['id'], user_role['subnetworkId'],
- user_role['totalAssignedUsers']))
- if user_role['permissions']:
- print ' The above user role has the following permissions:'
- for permission in user_role['permissions']:
- print (' Permission with name \'%s\' and ID \'%s\'.'
- % (permission['name'], permission['id']))
- else:
- print ' The above user role has no permissions assigned.'
- else:
- print 'No user roles found for your criteria.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client)
diff --git a/examples/dfa/v1_20/get_users.py b/examples/dfa/v1_20/get_users.py
deleted file mode 100755
index f7a57109..00000000
--- a/examples/dfa/v1_20/get_users.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example displays users for the given search criteria.
-
-Results are limited to the first 10 records.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: user.getUsersByCriteria
-"""
-
-__author__ = 'Joseph DiLallo'
-
-# Import appropriate modules from the client library.
-from googleads import dfa
-
-
-def main(client):
- # Initialize appropriate service.
- user_service = client.GetService(
- 'user', 'v1.20', 'https://advertisersapitest.doubleclick.net')
-
- # Set user search criteria.
- user_search_criteria = {
- 'pageSize': '10'
- }
-
- # Get users that match the search criteria.
- results = user_service.getUsersByCriteria(user_search_criteria)
-
- # Display user names, IDs, network IDs, subnetwork IDs, and group IDs.
- if results['records']:
- for user in results['records']:
- print ('User with name \'%s\', ID \'%s\', network ID \'%s\', '
- 'subnetwork ID \'%s\', and user role id \'%s\' was found.'
- % (user['name'], user['id'], user['networkId'],
- user['subnetworkId'], user['userGroupId']))
- else:
- print 'No users found for your criteria.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfa_client = dfa.DfaClient.LoadFromStorage()
- main(dfa_client)
diff --git a/examples/dfp/authentication/create_dfp_client_with_service_account.py b/examples/dfp/authentication/create_dfp_client_with_service_account.py
deleted file mode 100755
index 59b92fd3..00000000
--- a/examples/dfp/authentication/create_dfp_client_with_service_account.py
+++ /dev/null
@@ -1,46 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Initializes a DfpClient using a Service Account."""
-
-__author__ = 'Mark Saniscalchi'
-
-from googleads import dfp
-from googleads import oauth2
-
-# OAuth 2.0 credential information. In a real application, you'd probably be
-# pulling these values from a credential storage.
-SERVICE_ACCOUNT_EMAIL = 'INSERT_SERVICE_ACCOUNT_EMAIL'
-KEY_FILE = 'INSERT_KEY_FILE_PATH'
-
-# DFP API information.
-APPLICATION_NAME = 'INSERT_APPLICATION_NAME_HERE'
-
-
-def main(service_account_email, key_file, application_name):
- oauth2_client = oauth2.GoogleServiceAccountClient(
- oauth2.GetAPIScope('dfp'), service_account_email, key_file)
-
- dfp_client = dfp.DfpClient(oauth2_client, application_name)
-
- networks = dfp_client.GetService('NetworkService').getAllNetworks()
- for network in networks:
- print ('Network with network code \'%s\' and display name \'%s\' was found.'
- % (network['networkCode'], network['displayName']))
-
-
-if __name__ == '__main__':
- main(SERVICE_ACCOUNT_EMAIL, KEY_FILE, APPLICATION_NAME)
diff --git a/examples/dfp/authentication/create_dfp_client_without_yaml.py b/examples/dfp/authentication/create_dfp_client_without_yaml.py
deleted file mode 100755
index 357d0622..00000000
--- a/examples/dfp/authentication/create_dfp_client_without_yaml.py
+++ /dev/null
@@ -1,53 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Initializes a DfpClient without using yaml-cached credentials.
-
-While our LoadFromStorage method provides a useful shortcut to instantiate a
-client if you regularly use just one set of credentials, production applications
-may need to swap out users. This example shows you how to create an OAuth 2.0
-client and a DfpClient without relying on a yaml file.
-"""
-
-__author__ = 'Joseph DiLallo'
-
-from googleads import dfp
-from googleads import oauth2
-
-# OAuth 2.0 credential information. In a real application, you'd probably be
-# pulling these values from a credential storage.
-CLIENT_ID = 'INSERT_CLIENT_ID_HERE'
-CLIENT_SECRET = 'INSERT_CLIENT_SECRET_HERE'
-REFRESH_TOKEN = 'INSERT_REFRESH_TOKEN_HERE'
-
-# DFP API information.
-APPLICATION_NAME = 'INSERT_APPLICATION_NAME_HERE'
-
-
-def main(client_id, client_secret, refresh_token, application_name):
- oauth2_client = oauth2.GoogleRefreshTokenClient(
- client_id, client_secret, refresh_token)
-
- dfp_client = dfp.DfpClient(oauth2_client, application_name)
-
- networks = dfp_client.GetService('NetworkService').getAllNetworks()
- for network in networks:
- print ('Network with network code \'%s\' and display name \'%s\' was found.'
- % (network['networkCode'], network['displayName']))
-
-
-if __name__ == '__main__':
- main(CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN, APPLICATION_NAME)
diff --git a/examples/dfp/authentication/generate_refresh_token.py b/examples/dfp/authentication/generate_refresh_token.py
deleted file mode 100755
index de6aa6da..00000000
--- a/examples/dfp/authentication/generate_refresh_token.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Generates a refresh token for use with DFP."""
-
-__author__ = 'Mark Saniscalchi'
-
-import sys
-
-from oauth2client import client
-
-# Your OAuth 2.0 Client ID and Secret. If you do not have an ID and Secret yet,
-# please go to https://console.developers.google.com and create a set.
-CLIENT_ID = 'INSERT_CLIENT_ID_HERE'
-CLIENT_SECRET = 'INSERT_CLIENT_SECRET_HERE'
-
-# The DFP API OAuth 2.0 scope.
-SCOPE = u'https://www.googleapis.com/auth/dfp'
-
-
-def main():
- """Retrieve and display the access and refresh token."""
- flow = client.OAuth2WebServerFlow(
- client_id=CLIENT_ID,
- client_secret=CLIENT_SECRET,
- scope=[SCOPE],
- user_agent='Ads Python Client Library',
- redirect_uri='urn:ietf:wg:oauth:2.0:oob')
-
- authorize_url = flow.step1_get_authorize_url()
-
- print ('Log into the Google Account you use to access your DFP account'
- 'and go to the following URL: \n%s\n' % (authorize_url))
- print 'After approving the token enter the verification code (if specified).'
- code = raw_input('Code: ').strip()
-
- try:
- credential = flow.step2_exchange(code)
- except client.FlowExchangeError, e:
- print 'Authentication has failed: %s' % e
- sys.exit(1)
- else:
- print ('OAuth 2.0 authorization successful!\n\n'
- 'Your access token is:\n %s\n\nYour refresh token is:\n %s'
- % (credential.access_token, credential.refresh_token))
-
-
-if __name__ == '__main__':
- main()
diff --git a/examples/dfp/v201405/activity_group_service/__init__.py b/examples/dfp/v201405/activity_group_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201405/activity_group_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201405/activity_group_service/create_activity_groups.py b/examples/dfp/v201405/activity_group_service/create_activity_groups.py
deleted file mode 100755
index f828c977..00000000
--- a/examples/dfp/v201405/activity_group_service/create_activity_groups.py
+++ /dev/null
@@ -1,74 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new activity groups.
-
-To determine which activity groups exist, run get_all_activity_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ActivityGroupService.createActivityGroups
-"""
-
-__author__ = ('Vincent Tsao',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the advertiser company this activity group is associated with.
-ADVERTISER_COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
-
-
-def main(client, advertiser_company_id):
- # Initialize appropriate service.
- activity_group_service = client.GetService('ActivityGroupService',
- version='v201405')
-
- # Create a short-term activity group.
- short_term_activity_group = {
- 'name': 'Short-term activity group #%s' % uuid.uuid4(),
- 'companyIds': [advertiser_company_id],
- 'clicksLookback': '1',
- 'impressionsLookback': '1'
- }
-
- # Create a long-term activity group.
- long_term_activity_group = {
- 'name': 'Long-term activity group #%s' % uuid.uuid4(),
- 'companyIds': [advertiser_company_id],
- 'clicksLookback': '30',
- 'impressionsLookback': '30'
- }
-
- # Create the activity groups on the server.
- activity_groups = activity_group_service.createActivityGroups([
- short_term_activity_group, long_term_activity_group])
-
- # Display results.
- for activity_group in activity_groups:
- print ('Activity group with ID \'%s\' and name \'%s\' was created.'
- % (activity_group['id'], activity_group['name']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ADVERTISER_COMPANY_ID)
diff --git a/examples/dfp/v201405/activity_group_service/get_active_activity_groups.py b/examples/dfp/v201405/activity_group_service/get_active_activity_groups.py
deleted file mode 100755
index 92a75cef..00000000
--- a/examples/dfp/v201405/activity_group_service/get_active_activity_groups.py
+++ /dev/null
@@ -1,72 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all active activity groups.
-
-To create activity groups, run create_activity_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ActivityGroupService.getActivityGroupsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- activity_group_service = client.GetService('ActivityGroupService',
- version='v201405')
-
- # Create statement object to only select active activity groups.
- values = [{
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ACTIVE'
- }
- }]
- query = 'WHERE status = :status'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Get activity groups by statement.
- while True:
- response = activity_group_service.getActivityGroupsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for activity_group in response['results']:
- print ('Activity group with ID \'%s\' and name \'%s\' was found.'
- % (activity_group['id'], activity_group['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/activity_group_service/get_all_activity_groups.py b/examples/dfp/v201405/activity_group_service/get_all_activity_groups.py
deleted file mode 100755
index 2ffd28d7..00000000
--- a/examples/dfp/v201405/activity_group_service/get_all_activity_groups.py
+++ /dev/null
@@ -1,63 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all activity groups.
-
-To create activity groups, run create_activity_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ActivityGroupService.getActivityGroupsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- activity_group_service = client.GetService('ActivityGroupService',
- version='v201405')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get activity groups by statement.
- while True:
- response = activity_group_service.getActivityGroupsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for activity_group in response['results']:
- print ('Activity group with ID \'%s\' and name \'%s\' was found.'
- % (activity_group['id'], activity_group['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/activity_group_service/update_activity_groups.py b/examples/dfp/v201405/activity_group_service/update_activity_groups.py
deleted file mode 100755
index 64c6c6fa..00000000
--- a/examples/dfp/v201405/activity_group_service/update_activity_groups.py
+++ /dev/null
@@ -1,80 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates activity groups.
-
-To determine which activity groups exist, run get_all_activity_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ActivityGroupService.getActivityGroup
-Tags: ActivityGroupService.updateActivityGroups
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the activity group and the company to update it with.
-ACTIVITY_GROUP_ID = 'INSERT_ACTIVITY_GROUP_ID_HERE'
-ADVERTISER_COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
-
-
-def main(client, activity_group_id, advertiser_company_id):
- # Initialize appropriate service.
- activity_group_service = client.GetService('ActivityGroupService',
- version='v201405')
-
- # Create statement object to select a single activity groups by ID.
- values = [{
- 'key': 'activityGroupId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': activity_group_id
- }
- }]
- query = 'WHERE id = :activityGroupId'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get activity groups by statement.
- response = activity_group_service.getActivityGroupsByStatement(
- statement.ToStatement())
- if 'results' in response:
- updated_activity_groups = []
- for activity_group in response['results']:
- activity_group['companyIds'].append(advertiser_company_id)
- updated_activity_groups.append(activity_group)
- # Update the activity groups on the server.
- activity_groups = activity_group_service.updateActivityGroups(
- updated_activity_groups)
-
- for activity_group in activity_groups:
- print (('Activity group with ID \'%s\' and name \'%s\' was updated.')
- % (activity_group['id'], activity_group['name']))
- else:
- print 'No activity groups found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ACTIVITY_GROUP_ID, ADVERTISER_COMPANY_ID)
diff --git a/examples/dfp/v201405/activity_service/__init__.py b/examples/dfp/v201405/activity_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201405/activity_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201405/activity_service/create_activities.py b/examples/dfp/v201405/activity_service/create_activities.py
deleted file mode 100755
index 48bff97e..00000000
--- a/examples/dfp/v201405/activity_service/create_activities.py
+++ /dev/null
@@ -1,71 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new activities.
-
-To determine which activities groups exist, run get_all_activities.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ActivityService.createActivities
-"""
-
-__author__ = ('Vincent Tsao',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the activity group this activity is associated with.
-ACTIVITY_GROUP_ID = 'INSERT_ACTIVITY_GROUP_ID_HERE'
-
-
-def main(client, activity_group_id):
- # Initialize appropriate service.
- activity_service = client.GetService('ActivityService', version='v201405')
-
- # Create a daily visits activity.
- daily_visits_activity = {
- 'name': 'Activity #%s' % uuid.uuid4(),
- 'activityGroupId': activity_group_id,
- 'type': 'DAILY_VISITS'
- }
-
- # Create a custom activity.
- custom_activity = {
- 'name': 'Activity #%s' % uuid.uuid4(),
- 'activityGroupId': activity_group_id,
- 'type': 'CUSTOM'
- }
-
- # Create the activities on the server.
- activities = activity_service.createActivities([
- daily_visits_activity, custom_activity])
-
- # Display results.
- for activity in activities:
- print ('An activity with ID \'%s\', name \'%s\', and type \'%s\' was '
- 'created.' % (activity['id'], activity['name'], activity['type']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ACTIVITY_GROUP_ID)
diff --git a/examples/dfp/v201405/activity_service/get_active_activities.py b/examples/dfp/v201405/activity_service/get_active_activities.py
deleted file mode 100755
index 7416ce96..00000000
--- a/examples/dfp/v201405/activity_service/get_active_activities.py
+++ /dev/null
@@ -1,69 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all active activities.
-
-To create activities, run create_activities.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ActivityService.getActivitiesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- activity_service = client.GetService('ActivityService', version='v201405')
-
- # Create statement object to only select active activities.
- values = [{
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ACTIVE'
- }
- }]
- query = 'WHERE status = :status'
- statement = dfp.FilterStatement(query, values)
-
- # Get activities by statement.
- while True:
- response = activity_service.getActivitiesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for activity in response['results']:
- print ('Activity with ID \'%s\', name \'%s\', and type \'%s\' was '
- 'found.' % (activity['id'], activity['name'], activity['type']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/activity_service/get_all_activities.py b/examples/dfp/v201405/activity_service/get_all_activities.py
deleted file mode 100755
index 24057333..00000000
--- a/examples/dfp/v201405/activity_service/get_all_activities.py
+++ /dev/null
@@ -1,61 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all activities.
-
-To create activities, run create_activities.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ActivityService.getActivitiesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- activity_service = client.GetService('ActivityService', version='v201405')
-
- # Create statement object to select only all activities.
- statement = dfp.FilterStatement()
-
- # Get activities by statement.
- while True:
- response = activity_service.getActivitiesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for activity in response['results']:
- print ('Activity with ID \'%s\', name \'%s\', and type \'%s\' was '
- 'found.' % (activity['id'], activity['name'], activity['type']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/activity_service/update_activities.py b/examples/dfp/v201405/activity_service/update_activities.py
deleted file mode 100755
index 21f96ad5..00000000
--- a/examples/dfp/v201405/activity_service/update_activities.py
+++ /dev/null
@@ -1,76 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates activities.
-
-To determine which activities exist, run get_all_activities.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ActivityService.updateActivities
- ActivityService.getActivitiesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the activity to update.
-ACTIVITY_ID = 'INSERT_ACTIVITY_ID_HERE'
-
-
-def main(client, activity_id):
- # Initialize appropriate service.
- activity_service = client.GetService('ActivityService', version='v201405')
-
- # Create statement object to select one activity by ID to update.
- values = [{
- 'key': 'activityId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': activity_id
- }
- }]
- query = 'WHERE id = :activityId'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get activities by statement.
- response = activity_service.getActivitiesByStatement(
- statement.ToStatement())
- if 'results' in response:
- updated_activities = []
- for activity in response['results']:
- # Update the expected URL.
- activity['expectedURL'] = 'https://google.com'
- updated_activities.append(activity)
- # Update the activity on the server.
- activities = activity_service.updateActivities(updated_activities)
-
- for updated_activity in activities:
- print (('Activity with ID \'%s\' and name \'%s\' was updated.')
- % (updated_activity['id'], updated_activity['name']))
- else:
- print 'No activities found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ACTIVITY_ID)
diff --git a/examples/dfp/v201405/audience_segment_service/__init__.py b/examples/dfp/v201405/audience_segment_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201405/audience_segment_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201405/audience_segment_service/create_audience_segments.py b/examples/dfp/v201405/audience_segment_service/create_audience_segments.py
deleted file mode 100755
index a5622118..00000000
--- a/examples/dfp/v201405/audience_segment_service/create_audience_segments.py
+++ /dev/null
@@ -1,100 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates a new rule based first party audience segment."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the IDs of the custom criteria to be used in the segment rule.
-CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'
-CUSTOM_TARGETING_VALUE_ID = 'INSERT_CUSTOM_TARGETING_VALUE_ID_HERE'
-
-def main(client, custom_targeting_key_id, custom_targeting_value_id):
- # Initialize client object.
- client = dfp.DfpClient.LoadFromStorage()
-
- # Initialize appropriate services.
- audience_segment_service = client.GetService(
- 'AudienceSegmentService', version='v201405')
- network_service = client.GetService('NetworkService', version='v201405')
-
- # Get the root ad unit ID used to target the entire network.
- root_ad_unit_id = (
- network_service.getCurrentNetwork()['effectiveRootAdUnitId'])
-
- # Create inventory targeting (pointed at root ad unit i.e. the whole network)
- inventory_targeting = {
- 'targetedAdUnits': [
- {'adUnitId': root_ad_unit_id}
- ]
- }
-
- # Create custom criteria.
- custom_criteria = [
- {
- 'xsi_type': 'CustomCriteria',
- 'keyId': CUSTOM_TARGETING_KEY_ID,
- 'valueIds': [CUSTOM_TARGETING_VALUE_ID],
- 'operator': 'IS'
- }
- ]
-
- # Create the custom criteria set.
- top_custom_criteria_set = {
- 'logicalOperator': 'AND',
- 'children': custom_criteria
- }
-
- # Create the audience segment rule.
- rule = {
- 'inventoryRule': inventory_targeting,
- 'customCriteriaRule': top_custom_criteria_set
- }
-
- # Create an audience segment.
- audience_segment = [
- {
- 'xsi_type': 'RuleBasedFirstPartyAudienceSegment',
- 'name': ('Sports enthusiasts audience segment %s' %
- uuid.uuid4()),
- 'description': 'Sports enthusiasts between the ages of 20 and 30',
- 'pageViews': '6',
- 'recencyDays': '6',
- 'membershipExpirationDays': '88',
- 'rule': rule
- }
- ]
-
- audience_segments = (
- audience_segment_service.createAudienceSegments(audience_segment))
-
- for created_audience_segment in audience_segments:
- print ('An audience segment with ID \'%s\', name \'%s\', and type \'%s\' '
- 'was created.' % (created_audience_segment['id'],
- created_audience_segment['name'],
- created_audience_segment['type']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CUSTOM_TARGETING_KEY_ID, CUSTOM_TARGETING_VALUE_ID)
diff --git a/examples/dfp/v201405/audience_segment_service/get_all_audience_segments.py b/examples/dfp/v201405/audience_segment_service/get_all_audience_segments.py
deleted file mode 100755
index 721c7a16..00000000
--- a/examples/dfp/v201405/audience_segment_service/get_all_audience_segments.py
+++ /dev/null
@@ -1,60 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all audience segments.
-
-To create audience segments, run create_audience_segments.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize client object.
- client = dfp.DfpClient.LoadFromStorage()
-
- # Initialize appropriate service.
- audience_segment_service = client.GetService(
- 'AudienceSegmentService', version='v201405')
-
- # Create statement object to select all audience segments.
- statement = dfp.FilterStatement()
-
- # Get audience segments by statement.
- while True:
- response = audience_segment_service.getAudienceSegmentsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for segment in response['results']:
- print ('Audience segment with id \'%s\' and name '
- '\'%s\' of size %s was found.' %
- (segment['id'], segment['name'], segment['size']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/audience_segment_service/get_first_party_audience_segments.py b/examples/dfp/v201405/audience_segment_service/get_first_party_audience_segments.py
deleted file mode 100755
index 60d8bc6f..00000000
--- a/examples/dfp/v201405/audience_segment_service/get_first_party_audience_segments.py
+++ /dev/null
@@ -1,69 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all first party audience segments.
-
-To create first party audience segments, run create_audience_segments.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize client object.
- client = dfp.DfpClient.LoadFromStorage()
-
- # Initialize appropriate service.
- audience_segment_service = client.GetService(
- 'AudienceSegmentService', version='v201405')
-
- # Create statement object to only select first party audience segments.
- values = [{
- 'key': 'type',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'FIRST_PARTY'
- }
- }]
- query = 'WHERE Type = :type'
- statement = dfp.FilterStatement(query, values)
-
- # Get audience segments by statement.
- while True:
- response = audience_segment_service.getAudienceSegmentsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- segments = response['results']
- for segment in segments:
- print ('Audience segment with id \'%s\' and name \'%s\' of size '
- '%s was found. ' %
- (segment['id'], segment['name'], segment['size']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201405/audience_segment_service/populate_first_party_audience_segments.py
deleted file mode 100755
index 7a348cb0..00000000
--- a/examples/dfp/v201405/audience_segment_service/populate_first_party_audience_segments.py
+++ /dev/null
@@ -1,84 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example populates a specific first party audience segment.
-
-To determine which first party audience segments exist, run
-get_first_party_audience_segments.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-AUDIENCE_SEGMENT_ID = 'INSERT_AUDIENCE_SEGMENT_ID_HERE'
-
-
-def main(client, audience_segment_id):
- # Initialize client object.
- client = dfp.DfpClient.LoadFromStorage()
-
- # Initialize appropriate service.
- audience_segment_service = client.GetService(
- 'AudienceSegmentService', version='v201405')
-
- # Create statement object to get the specified first party audience segment.
- values = (
- [{'key': 'type',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'FIRST_PARTY'
- }
- },
- {'key': 'audience_segment_id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': AUDIENCE_SEGMENT_ID
- }
- }])
- query = 'WHERE Type = :type AND Id = :audience_segment_id'
- statement = dfp.FilterStatement(query, values, 1)
-
- response = audience_segment_service.getAudienceSegmentsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- segments = response['results']
-
- for segment in segments:
- print ('Audience segment with id \'%s\' and name \'%s\' will be populated.'
- % (segment['id'], segment['name']))
-
- action = {
- 'xsi_type': 'PopulateAudienceSegments'
- }
-
- populated_audience_segments = (
- audience_segment_service.performAudienceSegmentAction(
- action, statement.ToStatement()))
-
- print ('%s audience segment populated' %
- populated_audience_segments['numChanges'])
- else:
- print 'No Results Found'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, AUDIENCE_SEGMENT_ID)
diff --git a/examples/dfp/v201405/audience_segment_service/update_audience_segments.py b/examples/dfp/v201405/audience_segment_service/update_audience_segments.py
deleted file mode 100755
index db92594e..00000000
--- a/examples/dfp/v201405/audience_segment_service/update_audience_segments.py
+++ /dev/null
@@ -1,82 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates rule based first party audience segments.
-
-To determine which audience segments exist, run get_all_audience_segments.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-AUDIENCE_SEGMENT_ID = 'INSERT_AUDIENCE_SEGMENT_ID_HERE'
-
-
-def main(client, audience_segment_id):
- # Initialize client object.
- client = dfp.DfpClient.LoadFromStorage()
-
- # Initialize appropriate service.
- audience_segment_service = client.GetService(
- 'AudienceSegmentService', version='v201405')
-
- # Create statement object to get the specified first party audience segment.
- values = (
- [{'key': 'type',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'FIRST_PARTY'
- }
- },
- {'key': 'audience_segment_id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': AUDIENCE_SEGMENT_ID
- }
- }])
- query = 'WHERE Type = :type AND Id = :audience_segment_id'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get audience segments by statement.
- response = audience_segment_service.getAudienceSegmentsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- updated_audience_segments = []
- for audience_segment in response['results']:
- print ('Audience segment with id \'%s\' and name \'%s\' will be updated.'
- % (audience_segment['id'], audience_segment['name']))
-
- audience_segment['membershipExpirationDays'] = '180'
- updated_audience_segments.append(audience_segment)
-
- audience_segments = audience_segment_service.updateAudienceSegments(
- updated_audience_segments)
-
- for audience_segment in audience_segments:
- print ('Audience segment with id \'%s\' and name \'%s\' was updated' %
- (audience_segment['id'], audience_segment['name']))
- else:
- print 'No audience segment found to update.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, AUDIENCE_SEGMENT_ID)
diff --git a/examples/dfp/v201405/company_service/__init__.py b/examples/dfp/v201405/company_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201405/company_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201405/company_service/create_companies.py b/examples/dfp/v201405/company_service/create_companies.py
deleted file mode 100755
index 02cd259c..00000000
--- a/examples/dfp/v201405/company_service/create_companies.py
+++ /dev/null
@@ -1,65 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new companies.
-
-To determine which companies exist, run get_all_companies.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CompanyService.createCompanies
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- company_service = client.GetService('CompanyService', version='v201405')
-
- # Create company objects.
- companies = [
- {
- 'name': 'Advertiser #%s' % uuid.uuid4(),
- 'type': 'ADVERTISER'
- },
- {
- 'name': 'Agency #%s' % uuid.uuid4(),
- 'type': 'AGENCY'
- }
- ]
-
- # Add companies.
- companies = company_service.createCompanies(companies)
-
- # Display results.
- for company in companies:
- print ('Company with ID \'%s\', name \'%s\', and type \'%s\' was created.'
- % (company['id'], company['name'], company['type']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/company_service/get_advertisers.py b/examples/dfp/v201405/company_service/get_advertisers.py
deleted file mode 100755
index 6aa1853d..00000000
--- a/examples/dfp/v201405/company_service/get_advertisers.py
+++ /dev/null
@@ -1,69 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all companies that are advertisers.
-
-To create companies, run create_companies.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CompanyService.getCompaniesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- company_service = client.GetService('CompanyService', version='v201405')
-
- # Create statement object to only select companies that are advertisers.
- values = [{
- 'key': 'type',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ADVERTISER'
- }
- }]
- query = 'WHERE type = :type'
- statement = dfp.FilterStatement(query, values)
-
- # Get companies by statement.
- while True:
- response = company_service.getCompaniesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for company in response['results']:
- print ('Company with ID \'%s\', name \'%s\', and type \'%s\' was found.'
- % (company['id'], company['name'], company['type']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/company_service/get_all_companies.py b/examples/dfp/v201405/company_service/get_all_companies.py
deleted file mode 100755
index 0adc4355..00000000
--- a/examples/dfp/v201405/company_service/get_all_companies.py
+++ /dev/null
@@ -1,61 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all companies.
-
-To create companies, run create_companies.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CompanyService.getCompaniesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- company_service = client.GetService('CompanyService', version='v201405')
-
- # Create statement object to select all companies.
- statement = dfp.FilterStatement()
-
- # Get companies by statement.
- while True:
- response = company_service.getCompaniesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for company in response['results']:
- print ('Company with ID \'%s\', name \'%s\', and type \'%s\' was found.'
- % (company['id'], company['name'], company['type']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/company_service/update_companies.py b/examples/dfp/v201405/company_service/update_companies.py
deleted file mode 100755
index 955ad22b..00000000
--- a/examples/dfp/v201405/company_service/update_companies.py
+++ /dev/null
@@ -1,77 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates company comments.
-
-To determine which companies exist, run get_all_companies.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CompanyService.updateCompanies
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the company to update.
-COMPANY_ID = 'INSERT_COMPANY_ID_HERE'
-
-
-def main(client, company_id):
- # Initialize appropriate service.
- company_service = client.GetService('CompanyService', version='v201405')
-
- # Create statement object to only select a single company by ID.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': company_id
- }
- }]
- query = 'WHERE id = :id'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get companies by statement.
- response = company_service.getCompaniesByStatement(
- statement.ToStatement())
- if 'results' in response:
- updated_companies = []
- for company in response['results']:
- company['comment'] += ' Updated.'
- updated_companies.append(company)
-
- # Update the companies on the server.
- companies = company_service.updateCompanies(updated_companies)
-
- # Display results.
- for company in companies:
- print (('Company with ID \'%s\', name \'%s\', and comment \'%s\''
- 'was updated.')
- % (company['id'], company['name'], company['comment']))
- else:
- print 'No companies found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, COMPANY_ID)
diff --git a/examples/dfp/v201405/contact_service/__init__.py b/examples/dfp/v201405/contact_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201405/contact_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201405/contact_service/create_contacts.py b/examples/dfp/v201405/contact_service/create_contacts.py
deleted file mode 100755
index ffe5edc2..00000000
--- a/examples/dfp/v201405/contact_service/create_contacts.py
+++ /dev/null
@@ -1,74 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new contacts.
-
-To determine which contacts exist, run get_all_contacts.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContactService.createContacts
-"""
-
-__author__ = ('Vincent Tsao',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the advertiser company this contact is associated with.
-ADVERTISER_COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
-
-# Set the ID of the agency company this contact is associated with.
-AGENCY_COMPANY_ID = 'INSERT_AGENCY_COMPANY_ID_HERE'
-
-
-def main(client, advertiser_company_id, agency_company_id):
- # Initialize appropriate service.
- contact_service = client.GetService('ContactService', version='v201405')
-
- # Create an advertiser contact.
- advertiser_contact = {
- 'name': 'Mr. Advertiser #%s' % uuid.uuid4(),
- 'email': 'advertiser@advertising.com',
- 'companyId': advertiser_company_id
- }
-
- # Create an agency contact.
- agency_contact = {
- 'name': 'Ms. Agency #%s' % uuid.uuid4(),
- 'email': 'agency@agencies.com',
- 'companyId': agency_company_id
- }
-
- # Create the contacts on the server.
- contacts = contact_service.createContacts([advertiser_contact,
- agency_contact])
-
- # Display results.
- for contact in contacts:
- print ('Contact with ID \'%s\' name \'%s\' was created.'
- % (contact['id'], contact['name']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ADVERTISER_COMPANY_ID, AGENCY_COMPANY_ID)
diff --git a/examples/dfp/v201405/contact_service/get_all_contacts.py b/examples/dfp/v201405/contact_service/get_all_contacts.py
deleted file mode 100755
index dc04fb53..00000000
--- a/examples/dfp/v201405/contact_service/get_all_contacts.py
+++ /dev/null
@@ -1,61 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all contacts.
-
-To create contacts, run create_contacts.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContactService.getContactsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- contact_service = client.GetService('ContactService', version='v201405')
-
- # Create statement object to get all contacts.
- statement = dfp.FilterStatement()
-
- # Get contacts by statement.
- while True:
- response = contact_service.getContactsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for contact in response['results']:
- print ('Contact with ID \'%s\' and name \'%s\' was found.'
- % (contact['id'], contact['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/contact_service/get_uninvited_contacts.py b/examples/dfp/v201405/contact_service/get_uninvited_contacts.py
deleted file mode 100755
index a92fa524..00000000
--- a/examples/dfp/v201405/contact_service/get_uninvited_contacts.py
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all contacts that aren't invited yet.
-
-To create contacts, run create_contacts.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContactService.getContactsByStatement
-"""
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- contact_service = client.GetService('ContactService', version='v201405')
-
- # Create statement object to only select contacts that are uninvited.
- values = [{
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'UNINVITED'
- }
- }]
- query = 'WHERE status = :status'
- statement = dfp.FilterStatement(query, values)
-
- # Get contacts by statement.
- while True:
- response = contact_service.getContactsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for contact in response['results']:
- print ('Contact with ID \'%s\' and name \'%s\' was found.'
- % (contact['id'], contact['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/contact_service/update_contacts.py b/examples/dfp/v201405/contact_service/update_contacts.py
deleted file mode 100755
index 1aa2b6a9..00000000
--- a/examples/dfp/v201405/contact_service/update_contacts.py
+++ /dev/null
@@ -1,79 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates contact addresses.
-
-To determine which contacts exist, run get_all_contacts.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContactService.updateContacts
- ContactService.getContactsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the contact to update.
-CONTACT_ID = 'INSERT_CONTACT_ID_HERE'
-
-
-def main(client, contact_id):
- # Initialize appropriate service.
- contact_service = client.GetService('ContactService', version='v201405')
-
- # Create statement object to select the single contact by ID.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': contact_id
- }
- }]
- query = 'WHERE id = :id'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get contacts by statement.
- response = contact_service.getContactsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- updated_contacts = []
- for contact in response['results']:
- contact['address'] = '123 New Street, New York, NY, 10011'
- updated_contacts.append(contact)
-
- # Update the contact on the server.
- contacts = contact_service.updateContacts(updated_contacts)
-
- # Display results.
- for contact in contacts:
- print (('Contact with ID \'%s\', name \'%s\', and address \'%s\' '
- 'was updated.')
- % (contact['id'], contact['name'], contact['address']))
- else:
- print 'No contacts found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CONTACT_ID)
diff --git a/examples/dfp/v201405/content_metadata_key_hierarchy_service/__init__.py b/examples/dfp/v201405/content_metadata_key_hierarchy_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201405/content_metadata_key_hierarchy_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201405/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/dfp/v201405/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py
deleted file mode 100755
index 33bcb53d..00000000
--- a/examples/dfp/v201405/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py
+++ /dev/null
@@ -1,81 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new content metadata key hierarchies.
-
-To determine which content metadata key hierarchies exist, run
-get_all_content_metadata_key_hierarchies.py.
-
-This feature is only available to DFP video publishers.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContentMetadataKeyHierarchyService.createContentMetadataKeyHierarchies
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the IDs of the custom targeting keys for the hierarchy.
-HIERARCHY_LEVEL_ONE_KEY_ID = 'INSERT_LEVEL_ONE_CUSTOM_TARGETING_KEY_ID_HERE'
-HIERARCHY_LEVEL_TWO_KEY_ID = 'INSERT_LEVEL_TWO_CUSTOM_TARGETING_KEY_ID_HERE'
-
-
-def main(client, hierarchy_level_one_key_id, hierarchy_level_two_key_id):
- # Initialize appropriate service.
- content_metadata_key_hierarchy_service = client.GetService(
- 'ContentMetadataKeyHierarchyService', version='v201405')
-
- hierarchy_level_1 = {
- 'customTargetingKeyId': hierarchy_level_one_key_id,
- 'hierarchyLevel': '1'
- }
-
- hierarchy_level_2 = {
- 'customTargetingKeyId': hierarchy_level_two_key_id,
- 'hierarchyLevel': '2'
- }
-
- hierarchy_levels = [hierarchy_level_1, hierarchy_level_2]
-
- # Create content metadata key hierarchy object.
- content_metadata_key_hierarchy = {
- 'name': 'Content Metadata Key Hierarchy #%s' % uuid.uuid4(),
- 'hierarchyLevels': hierarchy_levels
- }
-
- content_metadata_key_hierarchies = (
- content_metadata_key_hierarchy_service
- .createContentMetadataKeyHierarchies([content_metadata_key_hierarchy]))
-
- # Display results.
- for content_metadata_key_hierarchy in content_metadata_key_hierarchies:
- print ('Content metadata key hierarchy with id \'%s\' and name \'%s\''
- ' was created.' % (content_metadata_key_hierarchy['id'],
- content_metadata_key_hierarchy['name']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, HIERARCHY_LEVEL_ONE_KEY_ID, HIERARCHY_LEVEL_TWO_KEY_ID)
diff --git a/examples/dfp/v201405/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py b/examples/dfp/v201405/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py
deleted file mode 100755
index 76329f98..00000000
--- a/examples/dfp/v201405/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py
+++ /dev/null
@@ -1,88 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example deletes content metadata key hierarchies.
-
-To determine which content metadata key hierarchies exist, run
-get_all_content_metadata_key_hierarchies.py.
-
-This feature is only available to DFP video publishers.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContentMetadataKeyHierarchyService.getContentMetadataKeyHierarchiesByStatement
- ContentMetadataKeyHierarchyService.perfomContentMetadataKeyHierarchyAction
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the content metadata key hierarchy to delete.
-CONTENT_METADATA_KEY_HIERARCHY_ID = (
- 'INSERT_CONTENT_METADATA_KEY_HIERARCHY_ID_HERE')
-
-
-def main(client, content_metadata_key_hierarchy_id):
- # Initialize appropriate service.
- content_metadata_key_hierarchy_service = client.GetService(
- 'ContentMetadataKeyHierarchyService', version='v201405')
-
- # Create a query to select a single content metadata key hierarchy.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': content_metadata_key_hierarchy_id
- }
- }]
-
- query = 'WHERE id = :id ORDER BY id ASC'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get a single content metadata key hierarchy by statement.
- response = (content_metadata_key_hierarchy_service
- .getContentMetadataKeyHierarchiesByStatement(
- statement.ToStatement())[0])
- content_metadata_key_hierarchies = (response['results']
- if 'results' in response else None)
-
- # Display results.
- if content_metadata_key_hierarchies:
- for content_metadata_key_hierarchy in content_metadata_key_hierarchies:
- print ('Content metadata key hierarchy with ID \'%s\' and name \'%s\' '
- 'will be deleted.' % (content_metadata_key_hierarchy['id'],
- content_metadata_key_hierarchy['name']))
-
- # Perform action.
- result = (content_metadata_key_hierarchy_service
- .performContentMetadataKeyHierarchyAction(
- {'type': 'DeleteContentMetadataKeyHierarchies'},
- statement.ToStatement()))[0]
-
- # Display results.
- print ('Number of content metadata key hierarchies deleted: %s' %
- result['numChanges'])
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CONTENT_METADATA_KEY_HIERARCHY_ID)
diff --git a/examples/dfp/v201405/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/dfp/v201405/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py
deleted file mode 100755
index 85a72d91..00000000
--- a/examples/dfp/v201405/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py
+++ /dev/null
@@ -1,66 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all content metadata key hierarchies.
-
-This feature is only available to DFP video publishers.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContentMetadataKeyHierarchyService.getContentMetadataKeyHierarchiesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- content_metadata_key_hierarchy_service = client.GetService(
- 'ContentMetadataKeyHierarchyService', version='v201405')
-
- # Create statement object to select all content.
- statement = dfp.FilterStatement()
-
- # Get content by statement.
- while True:
- response = (content_metadata_key_hierarchy_service
- .getContentMetadataKeyHierarchiesByStatement(
- statement.ToStatement())[0])
- content_metadata_key_hierarchies = (response['results']
- if 'results' in response else None)
- if content_metadata_key_hierarchies:
- # Display results.
- for content_metadata_key_hierarchy in content_metadata_key_hierarchies:
- print ('Content metadata key hierarchyy with id \'%s\' and name \'%s\''
- ' was found.' % (content_metadata_key_hierarchy['id'],
- content_metadata_key_hierarchy['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/dfp/v201405/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py
deleted file mode 100755
index cc154a7a..00000000
--- a/examples/dfp/v201405/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py
+++ /dev/null
@@ -1,100 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates content metadata key hierarchies.
-
-To determine which content metadata key hierarchies exist, run
-get_all_content_metadata_key_hierarchies.py.
-
-This feature is only available to DFP video publishers.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContentMetadataKeyHierarchyService.getContentMetadataKeyHierarchiesByStatement
- ContentMetadataKeyHierarchyService.updateContentMetadataKeyHierarchies
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the content metadata key hierarchy to update.
-CONTENT_METADATA_KEY_HIERARCHY_ID = (
- 'INSERT_CONTENT_METADATA_KEY_HIERARCHY_ID_HERE')
-# Set the ID of the custom targeting key to be added as a hierarchy level.
-CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'
-
-
-def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id):
- # Initialize appropriate service.
- content_metadata_key_hierarchy_service = client.GetService(
- 'ContentMetadataKeyHierarchyService', version='v201405')
-
- # Create a query to select a single content metadata key hierarchy.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': content_metadata_key_hierarchy_id
- }
- }]
-
- query = 'WHERE id = :id ORDER BY id ASC'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get a single content metadata key hierarchy by statement.
- response = (content_metadata_key_hierarchy_service
- .getContentMetadataKeyHierarchiesByStatement(
- statement.ToStatement()))[0]
- content_metadata_key_hierarchies = (response['results']
- if 'results' in response else None)
-
- if content_metadata_key_hierarchies:
- content_metadata_key_hierarchy = content_metadata_key_hierarchies[0]
-
- # Update the content metadata key hierarchy by adding a hierarchy level.
- hierarchy_levels = content_metadata_key_hierarchy['hierarchyLevels']
-
- hierarchy_level = {
- 'customTargetingKeyId': custom_targeting_key_id,
- 'hierarchyLevel': str(len(hierarchy_levels) + 1)
- }
-
- content_metadata_key_hierarchy['hierarchyLevels'] = (
- hierarchy_levels.append(hierarchy_level))
-
- content_metadata_key_hierarchies = (
- content_metadata_key_hierarchy_service
- .updateContentMetadataKeyHierarchies(content_metadata_key_hierarchies))
-
- # Display results.
- for content_metadata_key_hierarchy in content_metadata_key_hierarchies:
- print ('Content metadata key hierarchy with id \'%s\' and name \'%s\''
- ' was updated.' % (content_metadata_key_hierarchy['id'],
- content_metadata_key_hierarchy['name']))
-
- else:
- print 'No content metadata key hierarchies were found'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CONTENT_METADATA_KEY_HIERARCHY_ID, CUSTOM_TARGETING_KEY_ID)
diff --git a/examples/dfp/v201405/content_service/__init__.py b/examples/dfp/v201405/content_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201405/content_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201405/content_service/get_all_content.py b/examples/dfp/v201405/content_service/get_all_content.py
deleted file mode 100755
index 88b3d0c9..00000000
--- a/examples/dfp/v201405/content_service/get_all_content.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all content.
-
-This feature is only available to DFP video publishers.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContentService.getContentByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- content_service = client.GetService('ContentService', version='v201405')
-
- # Create statement object to select all content.
- statement = dfp.FilterStatement()
-
- # Get content by statement.
- while True:
- response = content_service.getContentByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for content_item in response['results']:
- print ('Content with id \'%s\', name \'%s\', and status \'%s\' was '
- 'found.' % (content_item['id'], content_item['name'],
- content_item['status']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/content_service/get_content_by_category.py b/examples/dfp/v201405/content_service/get_content_by_category.py
deleted file mode 100755
index ab2fcc6b..00000000
--- a/examples/dfp/v201405/content_service/get_content_by_category.py
+++ /dev/null
@@ -1,112 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all active content categorized as a "comedy" using the
-network's content browse custom targeting key.
-
-This feature is only available to DFP video publishers.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContentService.getContentByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- content_service = client.GetService('ContentService', version='v201405')
- network_service = client.GetService('NetworkService', version='v201405')
- custom_targeting_service = client.GetService(
- 'CustomTargetingService', version='v201405')
-
- # Get the network's content browse custom targeting key.
- network = network_service.getCurrentNetwork()
- key_id = network['contentBrowseCustomTargetingKeyId']
-
- # Create a statement to select the categories matching the name comedy.
- values = [
- {
- 'key': 'contentBrowseCustomTargetingKeyId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': key_id
- }
- },
- {
- 'key': 'category',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'comedy'
- }
- }
- ]
- category_filter_query = ('WHERE customTargetingKeyId = '
- ':contentBrowseCustomTargetingKeyId and name = '
- ':category')
- category_filter_statement = dfp.FilterStatement(
- category_filter_query, values, 1)
-
- # Get categories matching the filter statement.
- response = custom_targeting_service.getCustomTargetingValuesByStatement(
- category_filter_statement.ToStatement())
-
- # Get the custom targeting value ID for the comedy category.
- if 'results' in response:
- category_custom_targeting_value_id = (response['results']['id'])
-
- # Create a statement to select the active content.
- content_values = [
- {
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ACTIVE'
- }
- }
- ]
- content_query = 'WHERE status = :status'
- content_statement = dfp.FilterStatement(content_query, content_values)
-
- while True:
- # Get the content by statement and custom targeting value.
- response = content_service.getContentByStatementAndCustomTargetingValue(
- content_statement.ToStatement(),
- category_custom_targeting_value_id)
- if 'results' in response:
- # Display results.
- for content_item in response['results']:
- print ('Content with id \'%s\', name \'%s\', and status \'%s\' was '
- 'found.' % (content_item['id'], content_item['name'],
- content_item['status']))
- content_statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/creative_service/__init__.py b/examples/dfp/v201405/creative_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201405/creative_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201405/creative_service/create_creative_from_template.py b/examples/dfp/v201405/creative_service/create_creative_from_template.py
deleted file mode 100755
index d6a8e3fd..00000000
--- a/examples/dfp/v201405/creative_service/create_creative_from_template.py
+++ /dev/null
@@ -1,104 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates a new template creative for a given advertiser.
-
-To determine which companies are advertisers, run get_advertisers.py.
-To determine which creative templates exist, run
-get_all_creative_templates.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeService.createCreative
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import base64
-import os
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set id of the advertiser (company) that the creative will be assigned to.
-ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
-
-
-def main(client, advertiser_id):
- # Initialize appropriate service.
- creative_service = client.GetService('CreativeService', version='v201405')
-
- # Use the image banner with optional third party tracking template.
- creative_template_id = '10000680'
-
- image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data',
- 'medium_rectangle.jpg'), 'r').read()
- image_data = base64.encodestring(image_data)
- # Create creative from templates.
- creative = {
- 'xsi_type': 'TemplateCreative',
- 'name': 'Template Creative #%s' % uuid.uuid4(),
- 'advertiserId': advertiser_id,
- 'size': {'width': '300', 'height': '250'},
- 'creativeTemplateId': creative_template_id,
- 'creativeTemplateVariableValues': [
- {
- 'xsi_type': 'AssetCreativeTemplateVariableValue',
- 'uniqueName': 'Imagefile',
- 'assetByteArray': image_data,
- 'fileName': 'image%s.jpg' % uuid.uuid4()
- },
- {
- 'xsi_type': 'LongCreativeTemplateVariableValue',
- 'uniqueName': 'Imagewidth',
- 'value': '300'
- },
- {
- 'xsi_type': 'LongCreativeTemplateVariableValue',
- 'uniqueName': 'Imageheight',
- 'value': '250'
- },
- {
- 'xsi_type': 'UrlCreativeTemplateVariableValue',
- 'uniqueName': 'ClickthroughURL',
- 'value': 'www.google.com'
- },
- {
- 'xsi_type': 'StringCreativeTemplateVariableValue',
- 'uniqueName': 'Targetwindow',
- 'value': '_blank'
- }
- ]
- }
-
- # Call service to create the creative.
- creative = creative_service.createCreative(creative)
-
- # Display results.
- print ('Template creative with id \'%s\', name \'%s\', and type \'%s\' was '
- 'created and can be previewed at %s.'
- % (creative['id'], creative['name'], creative['Creative.Type'],
- creative['previewUrl']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ADVERTISER_ID)
diff --git a/examples/dfp/v201405/creative_service/create_creatives.py b/examples/dfp/v201405/creative_service/create_creatives.py
deleted file mode 100755
index 507692d3..00000000
--- a/examples/dfp/v201405/creative_service/create_creatives.py
+++ /dev/null
@@ -1,94 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new image creatives for a given advertiser.
-
-To determine which companies are advertisers, run get_advertisers.py.
-To determine which creatives already exist, run get_all_creatives.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeService.createCreatives
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import base64
-import os
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set id of the advertiser (company) that all creatives will be assigned to.
-ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
-
-
-def main(client, advertiser_id):
- # Initialize appropriate service.
- creative_service = client.GetService('CreativeService', version='v201405')
-
- # Create creative objects.
- creatives = []
- with open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data',
- 'medium_rectangle.jpg'), 'r') as image:
- image_data = base64.encodestring(image.read())
-
- for i in xrange(5):
- # Create creative size.
- size = {
- 'width': '300',
- 'height': '250'
- }
-
- # Create image asset.
- creative_asset = {
- 'xsi_type': 'CreativeAsset',
- 'fileName': 'image.jpg',
- 'assetByteArray': image_data,
- 'size': size
- }
-
- # Create an image creative.
- creative = {
- 'xsi_type': 'ImageCreative',
- 'name': 'Image Creative #%s' % uuid.uuid4(),
- 'advertiserId': advertiser_id,
- 'destinationUrl': 'http://google.com',
- 'size': size,
- 'primaryImageAsset': creative_asset
- }
-
- creatives.append(creative)
-
- # Add creatives.
- creatives = creative_service.createCreatives(creatives)
-
- # Display results.
- for creative in creatives:
- print ('Image creative with id \'%s\', name \'%s\', and type \'%s\' was '
- 'created and can be previewed at %s.'
- % (creative['id'], creative['name'], creative['Creative.Type'],
- creative['previewUrl']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ADVERTISER_ID)
diff --git a/examples/dfp/v201405/creative_service/create_custom_creative.py b/examples/dfp/v201405/creative_service/create_custom_creative.py
deleted file mode 100755
index fe474983..00000000
--- a/examples/dfp/v201405/creative_service/create_custom_creative.py
+++ /dev/null
@@ -1,90 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates a custom creative for a given advertiser.
-
-This feature is only available to DFP premium solution networks. To determine
-which companies are advertisers, run get_advertisers.py. To determine
-which creative templates exist, run get_all_creative_templates.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeService.createCreative
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import base64
-import os
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set id of the advertiser (company) that the creative will be assigned to.
-ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
-
-
-def main(client, advertiser_id):
- # Initialize appropriate service.
- creative_service = client.GetService('CreativeService', version='v201405')
-
- # Get the image data for the creative.
- image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data',
- 'medium_rectangle.jpg'), 'r').read()
- image_data = base64.encodestring(image_data)
-
- # Create the HTML snippet used in the custom creative.
- html_snippet = (' Click above for '
- 'great deals!') % ('%%CLICK_URL_UNESC%%', '%%DEST_URL%%',
- '%%FILE:IMAGE_ASSET%%')
-
- # Create custom creative.
- creative = {
- 'xsi_type': 'CustomCreative',
- 'name': 'Custom Creative #%s' % uuid.uuid4(),
- 'advertiserId': advertiser_id,
- 'size': {'width': '300', 'height': '250'},
- 'destinationUrl': 'http://google.com',
- 'customCreativeAssets': [
- {
- 'xsi_type': 'CustomCreativeAsset',
- 'macroName': 'IMAGE_ASSET',
- 'assetByteArray': image_data,
- 'fileName': 'image%s.jpg' % uuid.uuid4()
- }
- ],
- 'htmlSnippet': html_snippet
- }
-
- # Call service to create the creative.
- creative = creative_service.createCreative(creative)
-
- # Display results.
- if creative:
- print ('Template creative with id \'%s\', name \'%s\', and type \'%s\' was '
- 'created and can be previewed at %s.'
- % (creative['id'], creative['name'], creative['Creative.Type'],
- creative['previewUrl']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ADVERTISER_ID)
diff --git a/examples/dfp/v201405/creative_service/get_all_creatives.py b/examples/dfp/v201405/creative_service/get_all_creatives.py
deleted file mode 100755
index 3833a0e4..00000000
--- a/examples/dfp/v201405/creative_service/get_all_creatives.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all creatives.
-
-To create creatives, run create_creatives.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeService.getCreativesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- creative_service = client.GetService('CreativeService', version='v201405')
-
- # Create statement object to select all creatives.
- statement = dfp.FilterStatement()
-
- # Get creatives by statement.
- while True:
- response = creative_service.getCreativesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for creative in response['results']:
- print ('Creative with id \'%s\', name \'%s\', and type \'%s\' was '
- 'found.' % (creative['id'], creative['name'],
- creative['Creative.Type']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/creative_service/get_creatives_by_statement.py b/examples/dfp/v201405/creative_service/get_creatives_by_statement.py
deleted file mode 100755
index 58060128..00000000
--- a/examples/dfp/v201405/creative_service/get_creatives_by_statement.py
+++ /dev/null
@@ -1,72 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all image creatives.
-
-To create an image creative, run create_creatives.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeService.getCreativesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- creative_service = client.GetService('CreativeService', version='v201405')
-
- # Create statement object to only select image creatives.
- values = [{
- 'key': 'creativeType',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ImageCreative'
- }
- }]
- query = 'WHERE creativeType = :creativeType'
- statement = dfp.FilterStatement(query, values)
-
- # Get creatives by statement.
- while True:
- response = creative_service.getCreativesByStatement(
- statement.ToStatement())
- creatives = response['results']
-
- if creatives:
- # Display results.
- for creative in creatives:
- print ('Creative with id \'%s\', name \'%s\', and type \'%s\' was '
- 'found.' % (creative['id'], creative['name'],
- creative['Creative.Type']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/creative_service/update_creatives.py b/examples/dfp/v201405/creative_service/update_creatives.py
deleted file mode 100755
index 19e2d64c..00000000
--- a/examples/dfp/v201405/creative_service/update_creatives.py
+++ /dev/null
@@ -1,84 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates the destination URL of a single image creative.
-
-To determine which image creatives exist, run get_all_creatives.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeService.updateCreatives
- CreativeService.getCreativesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-IMAGE_CREATIVE_ID = 'INSERT_IMAGE_CREATIVE_ID_HERE'
-
-
-def main(client, image_creative_id):
- # Initialize appropriate service.
- creative_service = client.GetService('CreativeService', version='v201405')
-
- # Create statement object to get all image creatives.
- values = [{
- 'key': 'type',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ImageCreative'
- }
- }, {
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': image_creative_id
- }
- }]
- query = 'WHERE creativeType = :type AND id = :id'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get creatives by statement.
- response = creative_service.getCreativesByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- # Update each local creative object by changing its destination URL.
- updated_creatives = []
- for creative in response['results']:
- creative['destinationUrl'] = 'http://news.google.com'
- updated_creatives.append(creative)
-
- # Update creatives remotely.
- creatives = creative_service.updateCreatives(updated_creatives)
-
- # Display results.
- for creative in creatives:
- print ('Image creative with id \'%s\' and destination URL \'%s\' was '
- 'updated.' % (creative['id'], creative['destinationUrl']))
- else:
- print 'No creatives found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, IMAGE_CREATIVE_ID)
diff --git a/examples/dfp/v201405/creative_set_service/__init__.py b/examples/dfp/v201405/creative_set_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201405/creative_set_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201405/creative_set_service/associate_creative_set_to_line_item.py b/examples/dfp/v201405/creative_set_service/associate_creative_set_to_line_item.py
deleted file mode 100755
index aed79ecc..00000000
--- a/examples/dfp/v201405/creative_set_service/associate_creative_set_to_line_item.py
+++ /dev/null
@@ -1,59 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates a line item creative association for a creative
-set.
-
-To create creative sets, run create_creative_set.py. To create creatives, run
-create_creatives.py. To determine which LICAs exist, run get_all_licas.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: LineItemCreativeAssociationService.createLineItemCreativeAssociations
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-CREATIVE_SET_ID = 'INSERT_CREATIVE_SET_ID_HERE'
-LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
-
-
-def main(client, creative_set_id, line_item_id):
- # Initialize appropriate service.
- lica_service = client.GetService(
- 'LineItemCreativeAssociationService', version='v201405')
-
- # Create LICA for a creative set.
- lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id}
-
- # Add LICA.
- lica = lica_service.createLineItemCreativeAssociations([lica])
-
- # Display results.
- print (('LICA with line item ID \'%s\' and creative set ID \'%s\' was '
- 'created.') % (lica['lineItemId'], lica['creativeSetId']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CREATIVE_SET_ID, LINE_ITEM_ID)
diff --git a/examples/dfp/v201405/creative_set_service/create_creative_set.py b/examples/dfp/v201405/creative_set_service/create_creative_set.py
deleted file mode 100755
index 6a595d7e..00000000
--- a/examples/dfp/v201405/creative_set_service/create_creative_set.py
+++ /dev/null
@@ -1,64 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new creative sets.
-
-To determine which creative sets exist, run get_all_creative_sets.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeSetService.createCreativeSet
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-MASTER_CREATIVE_ID = 'INSERT_MASTER_CREATIVE_ID_HERE'
-COMPANION_CREATIVE_ID = 'INSERT_COMPANION_CREATIVE_ID_HERE'
-
-
-def main(client, master_creative_id, companion_creative_id):
- # Initialize appropriate service.
- creative_set_service = client.GetService('CreativeSetService',
- version='v201405')
-
- # Create creative set objects.
- creative_set = {'name': 'Creative set #%s' % uuid.uuid4(),
- 'masterCreativeId': master_creative_id,
- 'companionCreativeIds': [companion_creative_id]}
-
- # Add creative sets.
- creative_set = creative_set_service.createCreativeSet(creative_set)
-
- # Display results.
- if creative_set:
- print (('Creative set with ID \'%s\', master creative ID \'%s\', and '
- 'companion creative IDs {%s} was created.')
- % (creative_set['id'], creative_set['masterCreativeId'],
- ','.join(creative_set['companionCreativeIds'])))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, MASTER_CREATIVE_ID, COMPANION_CREATIVE_ID)
diff --git a/examples/dfp/v201405/creative_set_service/get_all_creative_sets.py b/examples/dfp/v201405/creative_set_service/get_all_creative_sets.py
deleted file mode 100755
index ed98c0c7..00000000
--- a/examples/dfp/v201405/creative_set_service/get_all_creative_sets.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all creative sets.
-
-To create creative sets, run create_creative_sets.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeSetService.getCreativeSetsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- creative_set_service = client.GetService('CreativeSetService',
- version='v201405')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get creative sets by statement.
- while True:
- response = creative_set_service.getCreativeSetsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for creative_set in response['results']:
- print ('Creative set with ID \'%s\' and name \'%s\' was found.'
- % (creative_set['id'], creative_set['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/creative_set_service/get_creative_sets_by_statement.py b/examples/dfp/v201405/creative_set_service/get_creative_sets_by_statement.py
deleted file mode 100755
index 4a5ce727..00000000
--- a/examples/dfp/v201405/creative_set_service/get_creative_sets_by_statement.py
+++ /dev/null
@@ -1,75 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all creative sets for a master creative.
-
-To create creative sets, run create_creative_sets.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeSetService.getCreativeSetsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-MASTER_CREATIVE_ID = 'INSERT_MASTER_CREATIVE_ID_HERE'
-
-
-def main(client, master_creative_id):
- # Initialize appropriate service.
- creative_set_service = client.GetService('CreativeSetService',
- version='v201405')
-
- # Create statement object to only select creative sets that have the given
- # master creative.
- values = [{
- 'key': 'masterCreativeId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': master_creative_id
- }
- }]
- query = 'WHERE masterCreativeId = :masterCreativeId'
- statement = dfp.FilterStatement(query, values)
-
- # Get creative sets by statement.
- while True:
- response = creative_set_service.getCreativeSetsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for creative_set in response['results']:
- print (('Creative set with ID \'%s\', master creative ID \'%s\', and '
- 'companion creative IDs {%s} was found.')
- % (creative_set['id'], creative_set['masterCreativeId'],
- ','.join(creative_set['companionCreativeIds'])))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, MASTER_CREATIVE_ID)
diff --git a/examples/dfp/v201405/creative_set_service/update_creative_set.py b/examples/dfp/v201405/creative_set_service/update_creative_set.py
deleted file mode 100755
index 7a217338..00000000
--- a/examples/dfp/v201405/creative_set_service/update_creative_set.py
+++ /dev/null
@@ -1,82 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates a creative set by adding a companion creative.
-
-To determine which creative sets exist, run get_all_creative_sets.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeSetService.updateCreativeSet
- CreativeSetService.getCreativeSetsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the creative set to update.
-CREATIVE_SET_ID = 'INSERT_CREATIVE_SET_ID_HERE'
-COMPANION_CREATIVE_ID = 'INSERT_COMPANION_CREATIVE_ID_HERE'
-
-
-def main(client, creative_set_id, companion_creative_id):
- # Initialize appropriate service.
- creative_set_service = client.GetService('CreativeSetService',
- version='v201405')
-
- # Create statement to select a single creative set by ID.
- values = [{
- 'key': 'creativeSetId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': creative_set_id
- }
- }]
- query = 'WHERE id = :creativeSetId'
- statement = dfp.FilterStatement(query, values)
-
- # Get creative set.
- response = creative_set_service.getCreativeSetsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- updated_created_sets = []
- for creative_set in response['results']:
- creative_set['companionCreativeIds'].append(companion_creative_id)
- updated_created_sets.append(creative_set)
-
- # Update the creative sets on the server.
- creative_sets = creative_set_service.updateCreativeSet(updated_created_sets)
-
- # Display results.
- for creative_set in creative_sets:
- print (('Creative set with ID \'%s\', master creative ID \'%s\', and '
- 'companion creative IDs {%s} was updated.')
- % (creative_set['id'], creative_set['masterCreativeId'],
- ','.join(creative_set['companionCreativeIds'])))
- else:
- print 'No creative sets found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CREATIVE_SET_ID, COMPANION_CREATIVE_ID)
diff --git a/examples/dfp/v201405/creative_template_service/__init__.py b/examples/dfp/v201405/creative_template_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201405/creative_template_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201405/creative_template_service/get_all_creative_templates.py b/examples/dfp/v201405/creative_template_service/get_all_creative_templates.py
deleted file mode 100755
index ecb87f6e..00000000
--- a/examples/dfp/v201405/creative_template_service/get_all_creative_templates.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all creative templates.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeTemplateService.getCreativeTemplatesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- creative_template_service = client.GetService(
- 'CreativeTemplateService', version='v201405')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get creative templates by statement.
- while True:
- response = creative_template_service.getCreativeTemplatesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for template in response['results']:
- print ('Creative template with id \'%s\', name \'%s\', and type \'%s\' '
- 'was found.' % (template['id'],
- template['name'],
- template['type']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/creative_template_service/get_creative_templates_by_statement.py b/examples/dfp/v201405/creative_template_service/get_creative_templates_by_statement.py
deleted file mode 100755
index 30385d02..00000000
--- a/examples/dfp/v201405/creative_template_service/get_creative_templates_by_statement.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all system defined creative templates.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeTemplateService.getCreativeTemplatesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- creative_template_service = client.GetService(
- 'CreativeTemplateService', version='v201405')
-
- # Create statement object to only select system defined creative templates.
- values = [{
- 'key': 'creativeTemplateType',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'SYSTEM_DEFINED'
- }
- }]
- query = 'WHERE type = :creativeTemplateType'
- statement = dfp.FilterStatement(query, values)
-
- # Get creative templates by statement.
- while True:
- response = creative_template_service.getCreativeTemplatesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for template in response['results']:
- print ('Creative template with id \'%s\', name \'%s\', and type \'%s\' '
- 'was found.' % (template['id'],
- template['name'],
- template['type']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/creative_wrapper_service/create_creative_wrappers.py b/examples/dfp/v201405/creative_wrapper_service/create_creative_wrappers.py
deleted file mode 100755
index 26765892..00000000
--- a/examples/dfp/v201405/creative_wrapper_service/create_creative_wrappers.py
+++ /dev/null
@@ -1,66 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates a new creative wrapper.
-
-Creative wrappers must be associated with a LabelType.CREATIVE_WRAPPER label and
-applied to ad units by AdUnit.appliedLabels. To determine which creative
-wrappers exist, run get_all_creative_wrappers.py
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeWrapperService.createCreativeWrappers
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-LABEL_ID = 'INSERT_CREATIVE_WRAPPER_LABEL_ID_HERE'
-
-
-def main(client, label_id):
- # Initialize appropriate service.
- creative_wrapper_service = client.GetService('CreativeWrapperService',
- version='v201405')
-
- # Create creative wrapper objects.
- creative_wrapper = {
- # A label can only be associated with one creative wrapper.
- 'labelId': label_id,
- 'ordering': 'INNER',
- 'header': {'htmlSnippet': 'My creative wrapper header'},
- 'footer': {'htmlSnippet': 'My creative wrapper footer'}
- }
-
- # Add creative wrapper.
- creative_wrappers = creative_wrapper_service.createCreativeWrappers(
- [creative_wrapper])
-
- # Display results.
- for creative_wrapper in creative_wrappers:
- print ('Creative wrapper with ID \'%s\' applying to label \'%s\' was '
- 'created.' % (creative_wrapper['id'], creative_wrapper['labelId']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, LABEL_ID)
diff --git a/examples/dfp/v201405/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201405/creative_wrapper_service/deactivate_creative_wrapper.py
deleted file mode 100755
index 1e3e55ee..00000000
--- a/examples/dfp/v201405/creative_wrapper_service/deactivate_creative_wrapper.py
+++ /dev/null
@@ -1,92 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example deactivates a creative wrapper belonging to a label.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeWrapperService.getCreativeWrapperByStatement
-Tags: CreativeWrapperService.performCreativeWrapperAction
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-LABEL_ID = 'INSERT_LABEL_ID_HERE'
-
-
-def main(client, label_id):
- # Initialize appropriate service.
- creative_wrapper_service = client.GetService('CreativeWrapperService',
- version='v201405')
-
- # Create a query to select the active creative wrappers for the given label.
- values = [{
- 'key': 'labelId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': label_id
- }
- }, {
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ACTIVE'
- }
- }]
- query = 'WHERE status = :status AND labelId = :labelId'
- statement = dfp.FilterStatement(query, values)
-
- creative_wrappers_deactivated = 0
-
- # Get creative wrappers by statement.
- while True:
- response = creative_wrapper_service.getCreativeWrappersByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for creative_wrapper in response['results']:
- print ('Creative wrapper with ID \'%s\' applying to label \'%s\' with '
- 'status \'%s\' will be deactivated.' %
- (creative_wrapper['id'],
- creative_wrapper['labelId'],
- creative_wrapper['status']))
- # Perform action.
- result = creative_wrapper_service.performCreativeWrapperAction(
- {'xsi_type': 'DeactivateCreativeWrappers'}, statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- creative_wrappers_deactivated += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Display results.
- if creative_wrappers_deactivated > 0:
- print ('Number of creative wrappers deactivated: %s' %
- creative_wrappers_deactivated)
- else:
- print 'No creative wrappers were deactivated.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, LABEL_ID)
diff --git a/examples/dfp/v201405/creative_wrapper_service/get_active_creative_wrappers.py b/examples/dfp/v201405/creative_wrapper_service/get_active_creative_wrappers.py
deleted file mode 100755
index 76906aa6..00000000
--- a/examples/dfp/v201405/creative_wrapper_service/get_active_creative_wrappers.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all active creative wrappers.
-
-To create creative wrappers, run create_creative_wrappers.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeWrapperService.getCreativeWrappersByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- creative_wrapper_service = client.GetService('CreativeWrapperService',
- version='v201405')
-
- # Create statement object to only select active creative wrappers.
- values = [{
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ACTIVE'
- }
- }]
- query = 'WHERE status = :status'
- statement = dfp.FilterStatement(query, values)
-
- # Get creative wrappers by statement.
- while True:
- response = creative_wrapper_service.getCreativeWrappersByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for creative_wrapper in response['results']:
- print ('Creative wrapper with ID \'%s\' applying to label \'%s\' was '
- 'found.' % (creative_wrapper['id'], creative_wrapper['labelId']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/creative_wrapper_service/get_all_creative_wrappers.py b/examples/dfp/v201405/creative_wrapper_service/get_all_creative_wrappers.py
deleted file mode 100755
index f5438edd..00000000
--- a/examples/dfp/v201405/creative_wrapper_service/get_all_creative_wrappers.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all creative wrappers.
-
-To create creative wrappers, run create_creative_wrappers.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeWrapperService.getCreativeWrappersByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- creative_wrapper_service = client.GetService('CreativeWrapperService',
- version='v201405')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get creative wrappers by statement.
- while True:
- response = creative_wrapper_service.getCreativeWrappersByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for creative_wrapper in response['results']:
- print ('Creative wrapper with ID \'%s\' applying to label \'%s\' was '
- 'found.' % (creative_wrapper['id'], creative_wrapper['labelId']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/creative_wrapper_service/update_creative_wrappers.py b/examples/dfp/v201405/creative_wrapper_service/update_creative_wrappers.py
deleted file mode 100755
index 926cb14f..00000000
--- a/examples/dfp/v201405/creative_wrapper_service/update_creative_wrappers.py
+++ /dev/null
@@ -1,81 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates a creative wrapper to the 'OUTER' wrapping order.
-
-To determine which creative wrappers exist, run get_all_creative_wrappers.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeWrapperService.getCreativeWrappersByStatement
-Tags: CreativeWrapperService.updateCreativeWrappers
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the creative wrapper to update.
-CREATIVE_WRAPPER_ID = 'INSERT_CREATIVE_WRAPPER_ID_HERE'
-
-
-def main(client, creative_wrapper_id):
- # Initialize appropriate service.
- creative_wrapper_service = client.GetService('CreativeWrapperService',
- version='v201405')
-
- # Create statement to get a creative wrapper by ID.
- values = [{
- 'key': 'creativeWrapperId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': creative_wrapper_id
- }
- }]
- query = 'WHERE id = :creativeWrapperId'
- statement = dfp.FilterStatement(query, values)
-
- # Get creative wrappers.
- response = creative_wrapper_service.getCreativeWrappersByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- updated_creative_wrappers = []
- for creative_wrapper in response['results']:
- creative_wrapper['ordering'] = 'OUTER'
- updated_creative_wrappers.append(creative_wrapper)
-
- # Update the creative wrappers on the server.
- creative_wrappers = creative_wrapper_service.updateCreativeWrappers(
- updated_creative_wrappers)
-
- # Display results.
- for creative_wrapper in creative_wrappers:
- print (('Creative wrapper with ID \'%s\' and wrapping order \'%s\' '
- 'was updated.') % (creative_wrapper['id'],
- creative_wrapper['ordering']))
- else:
- print 'No creative wrappers found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CREATIVE_WRAPPER_ID)
diff --git a/examples/dfp/v201405/custom_field_service/__init__.py b/examples/dfp/v201405/custom_field_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201405/custom_field_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201405/custom_field_service/create_custom_field_options.py b/examples/dfp/v201405/custom_field_service/create_custom_field_options.py
deleted file mode 100755
index 756a80cd..00000000
--- a/examples/dfp/v201405/custom_field_service/create_custom_field_options.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates custom field options for a drop-down custom field.
-
-Once created, custom field options can be found under the options fields of the
-drop-down custom field and they cannot be deleted. To determine which custom
-fields exist, run get_all_custom_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomFieldService.createCustomFieldOptions
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the drop-down custom field to create options for.
-CUSTOM_FIELD_ID = 'INSERT_DROP_DOWN_CUSTOM_FIELD_ID_HERE'
-
-
-def main(client, custom_field_id):
- # Initialize appropriate service.
- custom_field_service = client.GetService(
- 'CustomFieldService', version='v201405')
-
- # Create custom field options.
- custom_field_options = [
- {
- 'displayName': 'Approved',
- 'customFieldId': custom_field_id
- },
- {
- 'displayName': 'Unapproved',
- 'customFieldId': custom_field_id
- }
- ]
-
- # Add custom field options.
- custom_field_options = custom_field_service.createCustomFieldOptions(
- custom_field_options)
-
- # Display results.
- for custom_field_option in custom_field_options:
- print ('Custom field option with ID \'%s\' and name \'%s\' was created.'
- % (custom_field_option['id'], custom_field_option['displayName']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CUSTOM_FIELD_ID)
diff --git a/examples/dfp/v201405/custom_field_service/create_custom_fields.py b/examples/dfp/v201405/custom_field_service/create_custom_fields.py
deleted file mode 100755
index 7ceff6be..00000000
--- a/examples/dfp/v201405/custom_field_service/create_custom_fields.py
+++ /dev/null
@@ -1,69 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates custom fields.
-
-To determine which custom fields exist, run get_all_custom_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomFieldService.createCustomFields
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- custom_field_service = client.GetService(
- 'CustomFieldService', version='v201405')
-
- # Create custom field objects.
- custom_fields = [
- {
- 'name': 'Customer comments #%s' % uuid.uuid4(),
- 'entityType': 'LINE_ITEM',
- 'dataType': 'STRING',
- 'visibility': 'FULL'
- }, {
- 'name': 'Internal approval status #%s' % uuid.uuid4(),
- 'entityType': 'LINE_ITEM',
- 'dataType': 'DROP_DOWN',
- 'visibility': 'FULL'
- }
- ]
-
- # Add custom fields.
- custom_fields = custom_field_service.createCustomFields(custom_fields)
-
- # Display results.
- for custom_field in custom_fields:
- print ('Custom field with ID \'%s\' and name \'%s\' was created.'
- % (custom_field['id'], custom_field['name']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201405/custom_field_service/deactivate_all_line_item_custom_fields.py
deleted file mode 100755
index ed0985c0..00000000
--- a/examples/dfp/v201405/custom_field_service/deactivate_all_line_item_custom_fields.py
+++ /dev/null
@@ -1,89 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example deactivates all active line items custom fields.
-
-To determine which custom fields exist, run get_all_custom_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomFieldService.getCustomFieldsByStatement
-Tags: CustomFieldService.performCustomFieldAction
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- custom_field_service = client.GetService(
- 'CustomFieldService', version='v201405')
-
- # Create statement to select only active custom fields that apply to
- # line items.
- values = [
- {
- 'key': 'entityType',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'LINE_ITEM'
- }
- }, {
- 'key': 'isActive',
- 'value': {
- 'xsi_type': 'BooleanValue',
- 'value': 'true'
- }
- }
- ]
- query = 'WHERE entityType = :entityType and isActive = :isActive'
- statement = dfp.FilterStatement(query, values)
-
- custom_fields_deactivated = 0
-
- # Get custom fields by statement.
- while True:
- response = custom_field_service.getCustomFieldsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for custom_field in response['results']:
- print ('Custom field with ID \'%s\' and name \'%s\' will'
- ' be deactivated.' % (custom_field['id'], custom_field['name']))
- result = custom_field_service.performCustomFieldAction(
- {'xsi_type': 'DeactivateCustomFields'}, statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- custom_fields_deactivated += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- if custom_fields_deactivated > 0:
- print 'Number of custom fields deactivated: %s' % custom_fields_deactivated
- else:
- print 'No custom fields were deactivated.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/custom_field_service/get_all_custom_fields.py b/examples/dfp/v201405/custom_field_service/get_all_custom_fields.py
deleted file mode 100755
index 775ed8bd..00000000
--- a/examples/dfp/v201405/custom_field_service/get_all_custom_fields.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all custom fields.
-
-To create custom fields, run create_custom_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomFieldService.getCustomFieldsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- custom_field_service = client.GetService(
- 'CustomFieldService', version='v201405')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get custom fields by statement.
- while True:
- response = custom_field_service.getCustomFieldsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for custom_field in response['results']:
- print ('Custom field with ID \'%s\' and name \'%s\' was found.'
- % (custom_field['id'], custom_field['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/custom_field_service/get_all_line_item_custom_fields.py b/examples/dfp/v201405/custom_field_service/get_all_line_item_custom_fields.py
deleted file mode 100755
index e968eb82..00000000
--- a/examples/dfp/v201405/custom_field_service/get_all_line_item_custom_fields.py
+++ /dev/null
@@ -1,72 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all custom fields that apply to line items.
-
-To create custom fields, run create_custom_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomFieldService.getCustomFieldsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- custom_field_service = client.GetService(
- 'CustomFieldService', version='v201405')
-
- # Create statement to select only custom fields that apply to line items.
- values = [{
- 'key': 'entityType',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'LINE_ITEM'
- }
- }]
- query = 'WHERE entityType = :entityType'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Get custom fields by statement.
- while True:
- response = custom_field_service.getCustomFieldsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for custom_field in response['results']:
- print ('Custom field with ID \'%s\' and name \'%s\' was found.'
- % (custom_field['id'], custom_field['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/custom_field_service/set_line_item_custom_field_value.py b/examples/dfp/v201405/custom_field_service/set_line_item_custom_field_value.py
deleted file mode 100755
index cac1e042..00000000
--- a/examples/dfp/v201405/custom_field_service/set_line_item_custom_field_value.py
+++ /dev/null
@@ -1,160 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example sets custom field values on a line item.
-
-To determine which custom fields exist, run get_all_custom_fields.py.
-To determine which line item exist, run get_all_line_items.py.
-To create custom field options, run create_custom_field_options.py
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomFieldService.getCustomFieldsByStatement
- LineItemService.getLineItemsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the custom fields, custom field option, and line item.
-CUSTOM_FIELD_ID = 'INSERT_CUSTOM_FIELD_ID_HERE'
-DROP_DOWN_CUSTOM_FIELD_ID = 'INSERT_DROP_DOWN_CUSTOM_FIELD_ID_HERE'
-CUSTOM_FIELD_OPTION_ID = 'INSERT_CUSTOM_FIELD_OPTION_ID_HERE'
-LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
-
-
-def main(client, custom_field_id, drop_down_custom_field_id,
- custom_field_option_id, line_item_id):
- # Initialize appropriate services.
- custom_field_service = client.GetService(
- 'CustomFieldService', version='v201405')
-
- line_item_service = client.GetService('LineItemService', version='v201405')
-
- # Create statement to get a custom field.
- custom_field_values = [{
- 'key': 'customFieldId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': custom_field_id
- }
- }]
- custom_field_query = 'WHERE id = :customFieldId'
- custom_field_statement = dfp.FilterStatement(
- custom_field_query, custom_field_values, 1)
-
- # Get custom field.
- custom_field = custom_field_service.getCustomFieldsByStatement(
- custom_field_statement.ToStatement())['results'][0]
-
- # Create statement to get a drop down custom field.
- drop_down_custom_field_values = [{
- 'key': 'dropDownCustomFieldId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': drop_down_custom_field_id
- }
- }]
- drop_down_custom_field_query = 'WHERE id = :dropDownCustomFieldId'
- drop_down_custom_field_statement = dfp.FilterStatement(
- drop_down_custom_field_query, drop_down_custom_field_values, 1)
-
- # Get drop-down custom field.
- drop_down_custom_field = custom_field_service.getCustomFieldsByStatement(
- drop_down_custom_field_statement.ToStatement())['results'][0]
-
- # Create statement to get a line item.
- line_item_values = [{
- 'key': 'lineItemId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': line_item_id
- }
- }]
- line_item_query = 'WHERE id = :lineItemId'
- line_item_statement = dfp.FilterStatement(
- line_item_query, line_item_values, 1)
-
- # Get line item.
- line_item = line_item_service.getLineItemsByStatement(
- line_item_statement.ToStatement())['results'][0]
-
- if custom_field and line_item:
- # Create custom field values.
- custom_field_value = {
- 'customFieldId': custom_field['id'],
- 'xsi_type': 'CustomFieldValue',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'Custom field value'
- }
- }
-
- drop_down_custom_field_value = {
- 'customFieldId': drop_down_custom_field['id'],
- 'xsi_type': 'DropDownCustomFieldValue',
- 'customFieldOptionId': custom_field_option_id,
- }
-
- custom_field_values = [custom_field_value, drop_down_custom_field_value]
-
- old_custom_field_values = []
- if 'customFieldValues' in line_item:
- old_custom_field_values = line_item['customFieldValues']
-
- # Only add existing custom field values for different custom fields than the
- # ones you are setting.
- for old_custom_field_value in old_custom_field_values:
- if (old_custom_field_value['customFieldId'] !=
- custom_field_value['customFieldId']
- and old_custom_field_value['customFieldId'] !=
- drop_down_custom_field_value['customFieldId']):
- custom_field_values.append(old_custom_field_value)
-
- line_item['customFieldValues'] = custom_field_values
-
- # Update the line item on the server.
- line_items = line_item_service.updateLineItems([line_item])
-
- # Display results.
- for line_item in line_items:
- custom_field_value_strings = []
- for value in line_item['customFieldValues']:
- if value['BaseCustomFieldValue.Type'] == 'CustomFieldValue':
- custom_field_value_string = (
- '{ID: \'%s\', value: \'%s\'}'
- % (value['customFieldId'], value['value']['value']))
- elif value['BaseCustomFieldValue.Type'] == 'DropDownCustomFieldValue':
- custom_field_value_string = (
- '{ID: \'%s\', custom field option ID: \'%s\'}'
- % (value['customFieldId'], value['customFieldOptionId']))
- custom_field_value_strings.append(custom_field_value_string)
- print ('Line item with ID \'%s\' set with custom field values %s.'
- % (line_item['id'], ','.join(custom_field_value_strings)))
- else:
- print 'Line item or custom field not found.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CUSTOM_FIELD_ID, DROP_DOWN_CUSTOM_FIELD_ID,
- CUSTOM_FIELD_OPTION_ID, LINE_ITEM_ID)
diff --git a/examples/dfp/v201405/custom_field_service/update_custom_fields.py b/examples/dfp/v201405/custom_field_service/update_custom_fields.py
deleted file mode 100755
index b9d08219..00000000
--- a/examples/dfp/v201405/custom_field_service/update_custom_fields.py
+++ /dev/null
@@ -1,79 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates custom field descriptions.
-
-To determine which custom fields exist, run get_all_custom_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomFieldService.updateCustomFields
- CustomFieldService.getCustomFieldByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the custom field to update.
-CUSTOM_FIELD_ID = 'INSERT_CUSTOM_FIELD_ID_HERE'
-
-
-def main(client, custom_field_id):
- # Initialize appropriate service.
- custom_field_service = client.GetService(
- 'CustomFieldService', version='v201405')
-
- # Create statement to get a custom field.
- values = [{
- 'key': 'customFieldId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': custom_field_id
- }
- }]
- query = 'WHERE id = :customFieldId'
- statement = dfp.FilterStatement(query, values)
-
- # Get custom field.
- custom_fields = custom_field_service.getCustomsFieldByStatement(
- statement.ToStatement())
-
- if custom_fields:
- for custom_field in custom_fields:
- custom_field['description'] += ' Updated.'
-
- # Update the custom field on the server.
- custom_fields = custom_field_service.updateCustomFields(custom_fields)
-
- # Display results.
- for custom_field in custom_fields:
- print (('Custom field with ID \'%s\', name \'%s\', and '
- 'description \'%s\' was updated.')
- % (custom_field['id'], custom_field['name'],
- custom_field['description']))
- else:
- print 'No custom fields found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CUSTOM_FIELD_ID)
diff --git a/examples/dfp/v201405/custom_targeting_service/__init__.py b/examples/dfp/v201405/custom_targeting_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201405/custom_targeting_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201405/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/dfp/v201405/custom_targeting_service/create_custom_targeting_keys_and_values.py
deleted file mode 100755
index aaf013e3..00000000
--- a/examples/dfp/v201405/custom_targeting_service/create_custom_targeting_keys_and_values.py
+++ /dev/null
@@ -1,136 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates new custom targeting keys and values.
-
-To determine which custom targeting keys and values exist, run
-get_all_custom_targeting_keys_and_values.py. To target these custom targeting
-keys and values, run target_custom_criteria_example.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomTargetingService.createCustomTargetingKeys
- CustomTargetingService.createCustomTargetingValues
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- custom_targeting_service = client.GetService(
- 'CustomTargetingService', version='v201405')
-
- # Create custom targeting key objects.
- keys = [
- {
- 'displayName': 'gender',
- 'name': 'g',
- 'type': 'PREDEFINED'
- },
- {
- 'displayName': 'car model',
- 'name': 'c',
- 'type': 'FREEFORM'
- },
- # Add predefined key that may be use for content targeting.
- {
- 'displayName': 'genre',
- 'name': 'genre',
- 'type': 'PREDEFINED'
- }
- ]
-
- # Add custom targeting keys.
- keys = custom_targeting_service.createCustomTargetingKeys(keys)
-
- # Display results.
- if keys:
- for key in keys:
- print ('A custom targeting key with id \'%s\', name \'%s\', and display '
- 'name \'%s\' was created.' % (key['id'], key['name'],
- key['displayName']))
- else:
- print 'No keys were created.'
-
- # Create custom targeting value objects.
- values = [
- {
- 'customTargetingKeyId': keys['id'],
- 'displayName': 'male',
- # Name is set to 1 so that the actual name can be hidden from website
- # users.
- 'name': '1',
- 'matchType': 'EXACT'
- },
- {
- 'customTargetingKeyId': keys['id'],
- 'displayName': 'female',
- # Name is set to 2 so that the actual name can be hidden from website
- # users.
- 'name': '2',
- 'matchType': 'EXACT'
- },
- {
- 'customTargetingKeyId': keys[1]['id'],
- 'displayName': 'honda civic',
- 'name': 'honda civic',
- 'matchType': 'EXACT'
- },
- {
- 'customTargetingKeyId': keys[1]['id'],
- 'displayName': 'toyota',
- 'name': 'toyota',
- 'matchType': 'EXACT'
- },
- {
- 'customTargetingKeyId': keys[2]['id'],
- 'displayName': 'comedy',
- 'name': 'comedy',
- 'matchType': 'EXACT'
- },
- {
- 'customTargetingKeyId': keys[2]['id'],
- 'displayName': 'drama',
- 'name': 'drama',
- 'matchType': 'EXACT'
- }
- ]
-
- # Add custom targeting values.
- values = custom_targeting_service.createCustomTargetingValues(values)
-
- # Display results.
- if values:
- for value in values:
- print ('A custom targeting value with id \'%s\', belonging to key with id'
- ' \'%s\', name \'%s\', and display name \'%s\' was created.'
- % (value['id'], value['customTargetingKeyId'], value['name'],
- value['displayName']))
- else:
- print 'No values were created.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/custom_targeting_service/delete_custom_targeting_keys.py b/examples/dfp/v201405/custom_targeting_service/delete_custom_targeting_keys.py
deleted file mode 100755
index 255bb15d..00000000
--- a/examples/dfp/v201405/custom_targeting_service/delete_custom_targeting_keys.py
+++ /dev/null
@@ -1,85 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example deletes a custom targeting key by its name.
-
-To determine which custom targeting keys exist, run
-get_all_custom_targeting_keys_and_values.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomTargetingService.getCustomTargetingKeysByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-KEY_NAME = 'INSERT_CUSTOM_TARGETING_KEY_NAME_HERE'
-
-
-def main(client, key_name):
- # Initialize appropriate service.
- custom_targeting_service = client.GetService(
- 'CustomTargetingService', version='v201405')
-
- values = [{
- 'key': 'name',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': key_name
- }
- }]
- query = 'WHERE name = :name'
- statement = dfp.FilterStatement(query, values)
-
- deleted_custom_targeting_keys = 0
-
- # Get custom targeting keys.
- while True:
- response = custom_targeting_service.getCustomTargetingKeysByStatement(
- statement.ToStatement())
- if 'results' in response:
- key_ids = [key['id'] for key in response['results']]
- action = {'xsi_type': 'DeleteCustomTargetingKeys'}
- key_query = 'WHERE id IN (%s)' % ', '.join(key_ids)
- key_statement = dfp.FilterStatement(key_query)
-
- # Delete custom targeting keys.
- result = custom_targeting_service.performCustomTargetingKeyAction(
- action, key_statement.ToStatement())
-
- if result and int(result['numChanges']) > 0:
- deleted_custom_targeting_keys += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- if deleted_custom_targeting_keys > 0:
- print ('Number of custom targeting keys deleted: %s'
- % deleted_custom_targeting_keys)
- else:
- print 'No custom targeting keys were deleted.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, KEY_NAME)
diff --git a/examples/dfp/v201405/custom_targeting_service/delete_custom_targeting_values.py b/examples/dfp/v201405/custom_targeting_service/delete_custom_targeting_values.py
deleted file mode 100755
index d673a16d..00000000
--- a/examples/dfp/v201405/custom_targeting_service/delete_custom_targeting_values.py
+++ /dev/null
@@ -1,86 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example deletes custom targeting values for a given custom targeting
-key.
-
-To determine which custom targeting keys and values exist, run
-get_all_custom_targeting_keys_and_values.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomTargetingService.getCustomTargetingValuesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'
-
-
-def main(client, key_id):
- # Initialize appropriate service.
- custom_targeting_service = client.GetService(
- 'CustomTargetingService', version='v201405')
-
- filter_values = [{
- 'key': 'keyId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': key_id
- }
- }]
- query = 'WHERE customTargetingKeyId = :keyId'
- statement = dfp.FilterStatement(query, filter_values)
-
- deleted_custom_targeting_values = 0
-
- # Get custom targeting values.
- while True:
- response = custom_targeting_service.getCustomTargetingValuesByStatement(
- statement.ToStatement())
- if 'results' in response:
- value_ids = [value['id'] for value in response['results']]
- action = {'xsi_type': 'DeleteCustomTargetingValues'}
- value_query = ('WHERE customTargetingKeyId = :keyId '
- 'AND id IN (%s)' % ', '.join(value_ids))
- value_statement = dfp.FilterStatement(value_query, filter_values)
-
- # Delete custom targeting values.
- result = custom_targeting_service.performCustomTargetingValueAction(
- action, value_statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- deleted_custom_targeting_values += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- if deleted_custom_targeting_values > 0:
- print ('Number of custom targeting values deleted: %s'
- % deleted_custom_targeting_values)
- else:
- print 'No custom targeting values were deleted.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, KEY_ID)
diff --git a/examples/dfp/v201405/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201405/custom_targeting_service/get_all_custom_targeting_keys_and_values.py
deleted file mode 100755
index 6a979a5d..00000000
--- a/examples/dfp/v201405/custom_targeting_service/get_all_custom_targeting_keys_and_values.py
+++ /dev/null
@@ -1,90 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all custom targeting keys and the values.
-
-To create custom targeting keys and values, run
-create_custom_targeting_keys_and_values.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- custom_targeting_service = client.GetService(
- 'CustomTargetingService', version='v201405')
-
- # Create statement to get all targeting keys.
- targeting_key_statement = dfp.FilterStatement()
-
- all_keys = []
-
- # Get custom targeting keys by statement.
- while True:
- response = custom_targeting_service.getCustomTargetingKeysByStatement(
- targeting_key_statement.ToStatement())
- if 'results' in response:
- all_keys.extend(response['results'])
- targeting_key_statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- if all_keys:
- # Create map of custom targeting key id to custom targeting values.
- key_value_map = {}
-
- # Create statement to get all targeting values.
- query = ('WHERE customTargetingKeyId IN (%s)'
- % ', '.join([key['id'] for key in all_keys]))
- targeting_value_statement = dfp.FilterStatement(query)
-
- # Get custom targeting values by statement.
- while True:
- response = custom_targeting_service.getCustomTargetingValuesByStatement(
- targeting_value_statement.ToStatement())
- if 'results' in response:
- for key in all_keys:
- for value in response['results']:
- if key['id'] == value['customTargetingKeyId']:
- if key['id'] not in key_value_map.keys():
- key_value_map[key['id']] = []
- key_value_map[key['id']].append(value)
- targeting_value_statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Display results.
- for key in all_keys:
- print ('Custom targeting key with id \'%s\', name \'%s\', display name '
- '\'%s\', and type \'%s\' was found.'
- %(key['id'], key['name'], key['displayName'], key['type']))
- if key['id'] in key_value_map.keys():
- for value in key_value_map[key['id']]:
- print ('\tCustom targeting value with id \'%s\', name \'%s\', and '
- 'display name \'%s\' was found.'
- % (value['id'], value['name'], value['displayName']))
- else:
- print 'No keys were found.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
-
diff --git a/examples/dfp/v201405/custom_targeting_service/get_custom_targeting_keys_by_statement.py b/examples/dfp/v201405/custom_targeting_service/get_custom_targeting_keys_by_statement.py
deleted file mode 100755
index a6c07bff..00000000
--- a/examples/dfp/v201405/custom_targeting_service/get_custom_targeting_keys_by_statement.py
+++ /dev/null
@@ -1,63 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all predefined custom targeting keys.
-
-To create custom targeting keys, run create_custom_targeting_keys_and_values.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- custom_targeting_service = client.GetService(
- 'CustomTargetingService', version='v201405')
-
- values = [{
- 'key': 'type',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'PREDEFINED'
- }
- }]
- query = 'WHERE type = :type'
- statement = dfp.FilterStatement(query, values)
-
- # Get custom targeting keys by statement.
- while True:
- response = custom_targeting_service.getCustomTargetingKeysByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for key in response['results']:
- print ('Custom targeting key with id \'%s\', name \'%s\', display name '
- '\'%s\', and type \'%s\' was found.'
- % (key['id'], key['name'], key['displayName'], key['type']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/custom_targeting_service/get_custom_targeting_values_by_statement.py b/examples/dfp/v201405/custom_targeting_service/get_custom_targeting_values_by_statement.py
deleted file mode 100755
index 23fd92b8..00000000
--- a/examples/dfp/v201405/custom_targeting_service/get_custom_targeting_values_by_statement.py
+++ /dev/null
@@ -1,67 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets custom targeting values for the given predefined custom
-targeting key.
-
-To create custom targeting values, run
-create_custom_targeting_keys_and_values.py. To determine which custom
-targeting keys exist, run get_all_custom_targeting_keys_and_values.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'
-
-
-def main(client, key_id):
- # Initialize appropriate service.
- custom_targeting_service = client.GetService(
- 'CustomTargetingService', version='v201405')
-
- values = [{
- 'key': 'keyId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': key_id
- }
- }]
- query = 'WHERE customTargetingKeyId = :keyId'
- statement = dfp.FilterStatement(query, values)
-
- # Get custom targeting values by statement.
- while True:
- response = custom_targeting_service.getCustomTargetingValuesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for value in response['results']:
- print ('Custom targeting value with id \'%s\', name \'%s\', and display'
- ' name \'%s\' was found.'
- % (value['id'], value['name'], value['displayName']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CUSTOM_TARGETING_KEY_ID)
diff --git a/examples/dfp/v201405/custom_targeting_service/update_custom_targeting_keys.py b/examples/dfp/v201405/custom_targeting_service/update_custom_targeting_keys.py
deleted file mode 100755
index 07e4325c..00000000
--- a/examples/dfp/v201405/custom_targeting_service/update_custom_targeting_keys.py
+++ /dev/null
@@ -1,72 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates the display name of a single custom targeting key.
-
-To determine which custom targeting keys exist, run
-get_all_custom_targeting_keys_and_values.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'
-
-
-def main(client, key_id):
- # Initialize appropriate service.
- custom_targeting_service = client.GetService(
- 'CustomTargetingService', version='v201405')
-
- values = [{
- 'key': 'keyId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': key_id
- }
- }]
- query = 'WHERE id = :keyId'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get custom targeting keys by statement.
- response = custom_targeting_service.getCustomTargetingKeysByStatement(
- statement.ToStatement())
-
- # Update each local custom targeting key object by changing its display name.
- if 'results' in response:
- updated_keys = []
- for key in response['results']:
- if not key['displayName']:
- key['displayName'] = key['name']
- key['displayName'] += ' (Deprecated)'
- updated_keys.append(key)
- keys = custom_targeting_service.updateCustomTargetingKeys(updated_keys)
-
- # Display results.
- if keys:
- for key in keys:
- print ('Custom targeting key with id \'%s\', name \'%s\', display name '
- '\'%s\', and type \'%s\' was updated.'
- % (key['id'], key['name'], key['displayName'], key['type']))
- else:
- print 'No custom targeting keys were found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CUSTOM_TARGETING_KEY_ID)
diff --git a/examples/dfp/v201405/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201405/custom_targeting_service/update_custom_targeting_values.py
deleted file mode 100755
index 47004023..00000000
--- a/examples/dfp/v201405/custom_targeting_service/update_custom_targeting_values.py
+++ /dev/null
@@ -1,78 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates the display name of the custom targeting values
-belonging to a custom targeting key.
-
-To determine which custom targeting keys exist, run
-get_all_custom_targeting_keys_and_values.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'
-
-
-def main(client, key_id):
- # Initialize appropriate service.
- custom_targeting_service = client.GetService(
- 'CustomTargetingService', version='v201405')
-
- values = [{
- 'key': 'keyId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': key_id
- }
- }]
- query = 'WHERE customTargetingKeyId = :keyId'
- statement = dfp.FilterStatement(query, values)
-
- while True:
- # Get custom targeting values by statement.
- response = custom_targeting_service.getCustomTargetingValuesByStatement(
- statement.ToStatement())
-
- # Update each local custom targeting value object by changing its name.
- if 'results' in response:
- updated_values = []
- for value in response['results']:
- if not value['displayName']:
- value['displayName'] = value['name']
- value['displayName'] += ' (Deprecated)'
- updated_values.append(value)
- values = custom_targeting_service.updateCustomTargetingValues(
- updated_values)
-
- # Display results.
- for value in values:
- print ('Custom targeting value with id \'%s\', name \'%s\', and display'
- ' name \'%s\' was updated.'
- % (value['id'], value['name'], value['displayName']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- if response['totalResultSetSize'] == 0:
- print 'No custom targeting values were updated.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CUSTOM_TARGETING_KEY_ID)
diff --git a/examples/dfp/v201405/forecast_service/get_forecast.py b/examples/dfp/v201405/forecast_service/get_forecast.py
deleted file mode 100755
index b8025e9c..00000000
--- a/examples/dfp/v201405/forecast_service/get_forecast.py
+++ /dev/null
@@ -1,105 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets a forecast for a prospective line item.
-
-To determine which placements exist, run get_all_placements.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-from datetime import date
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the placement that the prospective line item will target.
-TARGET_PLACEMENT_IDS = ['INSERT_PLACEMENT_IDS_HERE']
-
-
-def main(client, target_placement_ids):
- # Initialize appropriate service.
- forecast_service = client.GetService('ForecastService', version='v201405')
-
- # Create prospective line item.
- line_item = {
- 'targeting': {
- 'inventoryTargeting': {
- 'targetedPlacementIds': target_placement_ids
- }
- },
- 'creativePlaceholders': [
- {
- 'size': {
- 'width': '300',
- 'height': '250'
- }
- },
- {
- 'size': {
- 'width': '120',
- 'height': '600'
- }
- }
- ],
- 'lineItemType': 'SPONSORSHIP',
- 'startDateTimeType': 'IMMEDIATELY',
- 'endDateTime': {
- 'date': {
- 'year': str(date.today().year + 1),
- 'month': '9',
- 'day': '30'
- },
- 'hour': '0',
- 'minute': '0',
- 'second': '0'
- },
- 'costType': 'CPM',
- 'costPerUnit': {
- 'currencyCode': 'USD',
- 'microAmount': '2000000'
- },
- 'primaryGoal': {
- 'units': '50',
- 'unitType': 'IMPRESSIONS'
- },
- 'contractedUnitsBought': '100',
- 'creativeRotationType': 'EVEN',
- 'discountType': 'PERCENTAGE',
- }
-
- # Get forecast.
- forecast = forecast_service.getForecast(line_item)
- matched = long(forecast['matchedUnits'])
- available_percent = (((long(forecast['availableUnits'])/
- (matched * 1.0)) * 100)
- if matched != 0 else 0)
- contending_line_items = ([] if 'contendingLineItems' not in forecast
- else forecast['contendingLineItems'])
-
- # Display results.
- print '%s %s matched.' % (matched, forecast['unitType'].lower())
- print '%s%% %s available.' % (available_percent, forecast['unitType'].lower())
- print '%d contending line items.' % len(contending_line_items)
-
- if 'possibleUnits' in forecast:
- possible_percent = (long(forecast['possibleUnits'])/(matched * 1.0)) * 100
- print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower())
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, TARGET_PLACEMENT_IDS)
diff --git a/examples/dfp/v201405/forecast_service/get_forecast_by_id.py b/examples/dfp/v201405/forecast_service/get_forecast_by_id.py
deleted file mode 100755
index 6145f92b..00000000
--- a/examples/dfp/v201405/forecast_service/get_forecast_by_id.py
+++ /dev/null
@@ -1,56 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets a forecast for an existing line item.
-
-To determine which line items exist, run get_all_line_items.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the line item to get a forecast for.
-LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID'
-
-
-def main(client, line_item_id):
- # Initialize appropriate service.
- forecast_service = client.GetService('ForecastService', version='v201405')
-
- # Get forecast for line item.
- forecast = forecast_service.getForecastById(line_item_id)
- matched = long(forecast['matchedUnits'])
- available_percent = (((long(forecast['availableUnits'])/
- (matched * 1.0)) * 100)
- if matched != 0 else 0)
- contending_line_items = ([] if 'contendingLineItems' not in forecast
- else forecast['contendingLineItems'])
-
- # Display results.
- print '%s %s matched.' % (matched, forecast['unitType'].lower())
- print '%s%% %s available.' % (available_percent, forecast['unitType'].lower())
- print '%d contending line items.' % len(contending_line_items)
-
- if 'possibleUnits' in forecast:
- possible_percent = (long(forecast['possibleUnits'])/(matched * 1.0)) * 100
- print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower())
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, LINE_ITEM_ID)
diff --git a/examples/dfp/v201405/inventory_service/__init__.py b/examples/dfp/v201405/inventory_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201405/inventory_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201405/inventory_service/archive_ad_units.py b/examples/dfp/v201405/inventory_service/archive_ad_units.py
deleted file mode 100755
index 3abf0610..00000000
--- a/examples/dfp/v201405/inventory_service/archive_ad_units.py
+++ /dev/null
@@ -1,83 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example archives ad units.
-
-The parent ad unit and all ad units underneath it will be archived. To create ad
-units, run create_ad_units.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: InventoryService.getAdUnitsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-PARENT_AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE'
-
-
-def main(client, parent_id):
- # Initialize appropriate service.
- inventory_service = client.GetService('InventoryService', version='v201405')
-
- # Create a query to select ad units under the parent ad unit and the parent ad
- # unit.
- values = [{
- 'key': 'parentId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': parent_id
- }
- }]
- query = 'WHERE parentId = :parentId or id = :parentId'
- statement = dfp.FilterStatement(query, values)
-
- ad_units_archived = 0
-
- # Get ad units by statement.
- while True:
- response = inventory_service.getAdUnitsByStatement(
- statement.ToStatement())
- if 'results' in response:
- for ad_unit in response['results']:
- print ('Ad unit with ID \'%s\' and name \'%s\' will be archived.'
- % (ad_unit['id'], ad_unit['name']))
- # Perform action.
- result = inventory_service.performAdUnitAction(
- {'xsi_type': 'ArchiveAdUnits'}, statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- ad_units_archived += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Display results.
- if ad_units_archived > 0:
- print 'Number of ad units archived: %s' % ad_units_archived
- else:
- print 'No ad units were archived.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PARENT_AD_UNIT_ID)
diff --git a/examples/dfp/v201405/inventory_service/create_ad_units.py b/examples/dfp/v201405/inventory_service/create_ad_units.py
deleted file mode 100755
index 910aeb01..00000000
--- a/examples/dfp/v201405/inventory_service/create_ad_units.py
+++ /dev/null
@@ -1,74 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new ad units.
-
-To determine which ad units exist, run get_all_ad_units.py
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: InventoryService.createAdUnits
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-PARENT_AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE'
-
-
-def main(client, parent_id):
- # Initialize appropriate service.
- inventory_service = client.GetService('InventoryService', version='v201405')
-
- # Create ad unit size.
- ad_unit_size = {
- 'size': {
- 'width': '300',
- 'height': '250'
- },
- 'environmentType': 'BROWSER'
- }
-
- # Create ad unit objects.
- ad_unit = {
- 'name': 'Ad_unit_%s' % uuid.uuid4(),
- 'parentId': parent_id,
- 'description': 'Ad unit description.',
- 'targetWindow': 'BLANK',
- 'targetPlatform': 'WEB',
- 'adUnitSizes': [ad_unit_size]
- }
-
- # Add ad units.
- ad_units = inventory_service.createAdUnits([ad_unit])
-
- # Display results.
- for ad_unit in ad_units:
- print ('Ad unit with ID \'%s\' and name \'%s\' was created.'
- % (ad_unit['id'], ad_unit['name']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PARENT_AD_UNIT_ID)
diff --git a/examples/dfp/v201405/inventory_service/get_ad_unit_hierarchy.py b/examples/dfp/v201405/inventory_service/get_ad_unit_hierarchy.py
deleted file mode 100755
index 901e36b2..00000000
--- a/examples/dfp/v201405/inventory_service/get_ad_unit_hierarchy.py
+++ /dev/null
@@ -1,118 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code gets the ad unit hierarchy and displays it as a tree.
-
-To create ad units, run create_ad_units.py
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: InventoryService.getAdUnitsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- inventory_service = client.GetService('InventoryService', version='v201405')
- statement = dfp.FilterStatement()
-
- all_ad_units = []
- # Get ad units by statement.
- while True:
- response = inventory_service.getAdUnitsByStatement(
- statement.ToStatement())
- if 'results' in response:
- all_ad_units.extend(response['results'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Find the root ad unit. root_ad_unit can also be set to child unit to only
- # build and display a portion of the tree.
- query = 'WHERE parentId IS NULL'
- root_statement = dfp.FilterStatement(query)
- response = inventory_service.getAdUnitsByStatement(
- root_statement.ToStatement())
- root_ad_unit = response['results']
-
- if root_ad_unit:
- BuildAndDisplayAdUnitTree(root_ad_unit, all_ad_units)
- else:
- print 'Could not build tree. No root ad unit found.'
-
-
-def DisplayAdUnitTree(root_ad_unit, ad_unit_tree, depth=0):
- """Helper for displaying ad unit tree.
-
- Args:
- root_ad_unit: dict the root ad unit.
- ad_unit_tree: dict the tree of ad units.
- [optional]
- depth: int the depth the tree has reached.
- """
- print '%s%s (%s)' % (GenerateTab(depth), root_ad_unit['name'],
- root_ad_unit['id'])
- if root_ad_unit['id'] in ad_unit_tree:
- for child in ad_unit_tree[root_ad_unit['id']]:
- DisplayAdUnitTree(child, ad_unit_tree, depth+1)
-
-
-def GenerateTab(depth):
- """Generate tabs to represent branching to children.
-
- Args:
- depth: int the depth the tree has reached.
-
- Returns:
- string inserted in front of the root unit.
- """
- tab_list = []
- if depth > 0:
- tab_list.append(' ')
- tab_list.append('| ' * depth)
- tab_list.append('+--')
- return ''.join(tab_list)
-
-
-def BuildAndDisplayAdUnitTree(root_ad_unit, all_ad_units):
- """Create an ad unit tree and display it.
-
- Args:
- root_ad_unit: dict the root ad unit to build the tree under.
- all_ad_units: list the list of all ad units to build the tree with.
- """
- tree = {}
- for ad_unit in all_ad_units:
- if 'parentId' in ad_unit:
- if ad_unit['parentId'] not in tree:
- tree[ad_unit['parentId']] = []
- tree[ad_unit['parentId']].append(ad_unit)
-
- DisplayAdUnitTree(root_ad_unit, tree)
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/inventory_service/get_all_ad_unit_sizes.py b/examples/dfp/v201405/inventory_service/get_all_ad_unit_sizes.py
deleted file mode 100755
index e8440f98..00000000
--- a/examples/dfp/v201405/inventory_service/get_all_ad_unit_sizes.py
+++ /dev/null
@@ -1,57 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all ad unit sizes defined in a network.
-
-To create ad units, run create_ad_units.py
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: InventoryService.getAdUnitSizesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- inventory_service = client.GetService('InventoryService', version='v201405')
- statement = dfp.FilterStatement()
-
- # Get ad units by statement.
- while True:
- response = inventory_service.getAdUnitSizesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for ad_unit_size in response['results']:
- print ('Ad unit size of dimensions %s was found.' %
- (ad_unit_size['fullDisplayString']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/inventory_service/get_all_ad_units.py b/examples/dfp/v201405/inventory_service/get_all_ad_units.py
deleted file mode 100755
index ead5f4c8..00000000
--- a/examples/dfp/v201405/inventory_service/get_all_ad_units.py
+++ /dev/null
@@ -1,59 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all ad units within a network.
-
-To create ad units, run create_ad_units.py
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: InventoryService.getAdUnitsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- inventory_service = client.GetService('InventoryService', version='v201405')
- statement = dfp.FilterStatement()
-
- # Get ad units by statement.
- while True:
- response = inventory_service.getAdUnitsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for ad_unit in response['results']:
- print ('Ad unit with ID \'%s\' and name \'%s\' was found.'
- % (ad_unit['id'], ad_unit['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/inventory_service/get_top_level_ad_units.py b/examples/dfp/v201405/inventory_service/get_top_level_ad_units.py
deleted file mode 100755
index 241907a1..00000000
--- a/examples/dfp/v201405/inventory_service/get_top_level_ad_units.py
+++ /dev/null
@@ -1,72 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all child ad units of the effective root ad unit.
-
-To create ad units, run create_ad_units.py
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: InventoryService.getAdUnitsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- inventory_service = client.GetService('InventoryService', version='v201405')
- network_service = client.GetService('NetworkService', version='v201405')
-
- root_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId']
-
- # Create a statement to select the children of the effective root ad unit.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': root_id
- }
- }]
- query = 'WHERE parentId = :id'
- statement = dfp.FilterStatement(query, values)
-
- # Get ad units by statement.
- while True:
- response = inventory_service.getAdUnitsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for ad_unit in response['results']:
- print ('Ad unit with ID \'%s\' and name \'%s\' was found.'
- % (ad_unit['id'], ad_unit['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/inventory_service/update_ad_units.py b/examples/dfp/v201405/inventory_service/update_ad_units.py
deleted file mode 100755
index 18f5556d..00000000
--- a/examples/dfp/v201405/inventory_service/update_ad_units.py
+++ /dev/null
@@ -1,91 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates ad unit sizes by adding a banner ad size.
-
-To determine which ad units exist, run get_all_ad_units.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: InventoryService.getAdUnit
-Tags: InventoryService.updateAdUnits
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-# Set the ID of the ad unit to get.
-AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE'
-
-
-def main(client, ad_unit_id):
- # Initialize appropriate service.
- inventory_service = client.GetService('InventoryService', version='v201405')
-
- # Create a statement to select a single ad unit by ID.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': ad_unit_id
- }
- }]
- query = 'WHERE id = :id'
- statement = dfp.FilterStatement(query, values)
-
- # Get ad units by statement.
- response = inventory_service.getAdUnitsByStatement(
- statement.ToStatement())
-
- # Add the size 468x60 to the ad unit.
- ad_unit_size = {
- 'size': {
- 'width': '468',
- 'height': '60'
- },
- 'environmentType': 'BROWSER'
- }
-
- if 'results' in response:
- updated_ad_units = []
- for ad_unit in response['results']:
- if 'adUnitSizes' not in ad_unit:
- ad_unit['adUnitSizes'] = []
- ad_unit['adUnitSizes'].append(ad_unit_size)
- updated_ad_units.append(ad_unit)
-
- # Update ad unit on the server.
- ad_units = inventory_service.updateAdUnits(updated_ad_units)
-
- # Display results.
- for ad_unit in ad_units:
- ad_unit_sizes = ['{%s x %s}' % (size['size']['width'],
- size['size']['height'])
- for size in ad_unit['adUnitSizes']]
- print ('Ad unit with ID \'%s\', name \'%s\', and sizes [%s] was updated'
- % (ad_unit['id'], ad_unit['name'], ','.join(ad_unit_sizes)))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, AD_UNIT_ID)
diff --git a/examples/dfp/v201405/label_service/__init__.py b/examples/dfp/v201405/label_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201405/label_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201405/label_service/create_labels.py b/examples/dfp/v201405/label_service/create_labels.py
deleted file mode 100755
index fe8dcb84..00000000
--- a/examples/dfp/v201405/label_service/create_labels.py
+++ /dev/null
@@ -1,56 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new labels.
-
-To determine which labels exist, run get_all_labels.py. This feature is only
-available to DFP premium solution networks."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- label_service = client.GetService('LabelService', version='v201405')
-
- # Create label objects.
- labels = []
- for _ in xrange(5):
- label = {
- 'name': 'Label #%s' % uuid.uuid4(),
- 'isActive': 'true',
- 'types': ['COMPETITIVE_EXCLUSION']
- }
- labels.append(label)
-
- # Add Labels.
- labels = label_service.createLabels(labels)
-
- # Display results.
- for label in labels:
- print ('Label with id \'%s\', name \'%s\', and types {%s} was found.'
- % (label['id'], label['name'], ','.join(label['types'])))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/label_service/deactivate_labels.py b/examples/dfp/v201405/label_service/deactivate_labels.py
deleted file mode 100755
index cb6cc5be..00000000
--- a/examples/dfp/v201405/label_service/deactivate_labels.py
+++ /dev/null
@@ -1,71 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example deactivates all active Labels.
-
-To determine which labels exist, run get_all_labels.py. This feature is only
-available to DFP premium solution networks."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- label_service = client.GetService('LabelService', version='v201405')
-
- # Create query.
- values = [{
- 'key': 'isActive',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'true'
- }
- }]
- query = 'WHERE isActive = :isActive'
- statement = dfp.FilterStatement(query, values)
-
- labels_deactivated = 0
-
- # Get labels by statement.
- while True:
- response = label_service.getLabelsByStatement(statement.ToStatement())
- if 'results' in response:
- for label in response['results']:
- print ('Label with id \'%s\' and name \'%s\' will be '
- 'deactivated.' % (label['id'], label['name']))
- # Perform action.
- result = label_service.performLabelAction(
- {'xsi_type': 'DeactivateLabels'}, statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- labels_deactivated += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Display results.
- if labels_deactivated > 0:
- print 'Number of labels deactivated: %s' % labels_deactivated
- else:
- print 'No labels were deactivated.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/label_service/get_all_labels.py b/examples/dfp/v201405/label_service/get_all_labels.py
deleted file mode 100755
index 394b6a66..00000000
--- a/examples/dfp/v201405/label_service/get_all_labels.py
+++ /dev/null
@@ -1,54 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all labels.
-
-To create labels, run create_labels.py. This feature is only available to DFP
-premium solution networks."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- label_service = client.GetService('LabelService', version='v201405')
-
- # Create statement to get all labels
- statement = dfp.FilterStatement()
-
- # Get labels by statement.
- while True:
- response = label_service.getLabelsByStatement(statement.ToStatement())
- if 'results' in response:
- # Display results.
- for label in response['results']:
- print ('Label with id \'%s\' and name \'%s\' was found.'
- % (label['id'], label['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/label_service/get_labels_by_statement.py b/examples/dfp/v201405/label_service/get_labels_by_statement.py
deleted file mode 100755
index e8a156e6..00000000
--- a/examples/dfp/v201405/label_service/get_labels_by_statement.py
+++ /dev/null
@@ -1,55 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all labels ordered by name.
-
-To create a label, run create_label.py. This feature is only available to DFP
-premium solution networks.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- label_service = client.GetService('LabelService', version='v201405')
-
- # Create statement to get all labels
- statement = dfp.FilterStatement('ORDER BY name')
-
- # Get labels by statement.
- while True:
- response = label_service.getLabelsByStatement(statement.ToStatement())
- if 'results' in response:
- # Display results.
- for label in response['results']:
- print ('Label with id \'%s\' and name \'%s\' was found.'
- % (label['id'], label['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/label_service/update_labels.py b/examples/dfp/v201405/label_service/update_labels.py
deleted file mode 100755
index 5d6ab5f1..00000000
--- a/examples/dfp/v201405/label_service/update_labels.py
+++ /dev/null
@@ -1,71 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates the description of a single label.
-
-To determine which labels exist, run get_all_labels.py. This feature is only
-available to DFP premium solution networks."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-LABEL_ID = 'INSERT_LABEL_ID_HERE'
-
-
-def main(client, label_id):
- # Initialize appropriate service.
- label_service = client.GetService('LabelService', version='v201405')
-
- # Create a statement to select only active labels.
- values = [
- {
- 'key': 'labelId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': label_id
- }
- }
- ]
- query = 'WHERE id = :labelId'
- statement = dfp.FilterStatement(query, values)
-
- # Get labels by filter.
- response = label_service.getLabelsByStatement(statement.ToStatement())
-
- if 'results' in response:
- # Update each local label object by changing the description.
- updated_labels = []
- for label in response['results']:
- label['description'] = 'These labels are updated.'
- updated_labels.append(label)
-
- # Update labels remotely.
- labels = label_service.updateLabels(updated_labels)
-
- for label in labels:
- print ('Label with id \'%s\' and name \'%s\' was updated.'
- % (label['id'], label['name']))
- else:
- print 'No labels found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, LABEL_ID)
-
diff --git a/examples/dfp/v201405/line_item_creative_association_service/__init__.py b/examples/dfp/v201405/line_item_creative_association_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201405/line_item_creative_association_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201405/line_item_creative_association_service/create_licas.py b/examples/dfp/v201405/line_item_creative_association_service/create_licas.py
deleted file mode 100755
index 19956e3b..00000000
--- a/examples/dfp/v201405/line_item_creative_association_service/create_licas.py
+++ /dev/null
@@ -1,58 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new line item creative associations (LICAs) for an
-existing line item and a set of creative ids.
-
-To determine which LICAs exist, run get_all_licas.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the line item ID and creative IDs to associate.
-LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
-CREATIVE_IDS = ['INSERT_CREATIVE_IDS_HERE']
-
-
-def main(client, line_item_id, creative_ids):
- # Initialize appropriate service.
- lica_service = client.GetService(
- 'LineItemCreativeAssociationService', version='v201405')
-
- licas = []
- for creative_id in creative_ids:
- licas.append({'creativeId': creative_id,
- 'lineItemId': line_item_id})
-
- # Create the LICAs remotely.
- licas = lica_service.createLineItemCreativeAssociations(licas)
-
- # Display results.
- if licas:
- for lica in licas:
- print ('LICA with line item id \'%s\', creative id \'%s\', and '
- 'status \'%s\' was created.' %
- (lica['lineItemId'], lica['creativeId'], lica['status']))
- else:
- print 'No LICAs created.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, LINE_ITEM_ID, CREATIVE_IDS)
diff --git a/examples/dfp/v201405/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201405/line_item_creative_association_service/deactivate_licas.py
deleted file mode 100755
index 26adbcdb..00000000
--- a/examples/dfp/v201405/line_item_creative_association_service/deactivate_licas.py
+++ /dev/null
@@ -1,84 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example deactivates all LICAs for the line item.
-
-To determine which LICAs exist, run get_all_licas.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the id of the line item in which to deactivate LICAs.
-LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
-
-
-def main(client, line_item_id):
- # Initialize appropriate service.
- lica_service = client.GetService(
- 'LineItemCreativeAssociationService', version='v201405')
-
- # Create query.
- values = [{
- 'key': 'lineItemId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': line_item_id
- }
- }, {
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ACTIVE'
- }
- }]
- query = 'WHERE lineItemId = :lineItemId AND status = :status'
- statement = dfp.FilterStatement(query, values)
-
- num_deactivated_licas = 0
-
- # Get LICAs by statement.
- while True:
- response = lica_service.getLineItemCreativeAssociationsByStatement(
- statement.ToStatement())
- if 'results' in response:
- for lica in response['results']:
- print ('LICA with line item id \'%s\', creative id \'%s\', and status'
- ' \'%s\' will be deactivated.' %
- (lica['lineItemId'], lica['creativeId'], lica['status']))
-
- # Perform action.
- result = lica_service.performLineItemCreativeAssociationAction(
- {'xsi_type': 'DeactivateLineItemCreativeAssociations'},
- statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- num_deactivated_licas += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Display results.
- if num_deactivated_licas > 0:
- print 'Number of LICAs deactivated: %s' % num_deactivated_licas
- else:
- print 'No LICAs were deactivated.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, LINE_ITEM_ID)
diff --git a/examples/dfp/v201405/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201405/line_item_creative_association_service/get_all_licas.py
deleted file mode 100755
index 8d3b2ba1..00000000
--- a/examples/dfp/v201405/line_item_creative_association_service/get_all_licas.py
+++ /dev/null
@@ -1,58 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all line item creative associations (LICA).
-
-To create LICAs, run create_licas.py or associate_creative_set_to_line_item.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- lica_service = client.GetService(
- 'LineItemCreativeAssociationService', version='v201405')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get line items by statement.
- while True:
- response = lica_service.getLineItemCreativeAssociationsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for lica in response['results']:
- if 'creativeSetId' in lica:
- print ('LICA with line item ID \'%s\', creative set ID \'%s\', and '
- 'status \'%s\' was found.' %
- (lica['lineItemId'], lica['creativeSetId'], lica['status']))
- else:
- print ('LICA with line item ID \'%s\', creative ID \'%s\', and status'
- ' \'%s\' was found.' % (lica['lineItemId'], lica['creativeId'],
- lica['status']))
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/line_item_creative_association_service/get_licas_by_statement.py b/examples/dfp/v201405/line_item_creative_association_service/get_licas_by_statement.py
deleted file mode 100755
index 5cfa4119..00000000
--- a/examples/dfp/v201405/line_item_creative_association_service/get_licas_by_statement.py
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all line item creative associations (LICA) for a given
-line item id.
-
-To create LICAs, run create_licas.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the id of the line item to get LICAs by.
-LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
-
-
-def main(client, line_item_id):
- # Initialize appropriate service.
- lica_service = client.GetService(
- 'LineItemCreativeAssociationService', version='v201405')
-
-# Create statement object to only select LICAs for the given line item id.
- values = [{
- 'key': 'lineItemId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': line_item_id
- }
- }]
- query = 'WHERE lineItemId = :lineItemId'
- statement = dfp.FilterStatement(query, values)
-
- while True:
- # Get LICAs by statement.
- response = lica_service.getLineItemCreativeAssociationsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- # Display results.
- for lica in response['results']:
- print ('LICA with line item id \'%s\', creative id \'%s\', and status '
- '\'%s\' was found.' % (lica['lineItemId'], lica['creativeId'],
- lica['status']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, LINE_ITEM_ID)
diff --git a/examples/dfp/v201405/line_item_creative_association_service/update_licas.py b/examples/dfp/v201405/line_item_creative_association_service/update_licas.py
deleted file mode 100755
index 77b06aa4..00000000
--- a/examples/dfp/v201405/line_item_creative_association_service/update_licas.py
+++ /dev/null
@@ -1,67 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates the destination URL of all line item creative
-associations (LICA).
-
-To determine which LICAs exist, run get_all_licas.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- lica_service = client.GetService(
- 'LineItemCreativeAssociationService', version='v201405')
-
- # Create statement object to get all LICAs.
- statement = dfp.FilterStatement()
-
- while True:
- # Get LICAs by statement.
- response = lica_service.getLineItemCreativeAssociationsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- # Update each local LICA object by changing its destination URL.
- updated_licas = []
- for lica in response['results']:
- lica['destinationUrl'] = 'http://news.google.com'
- updated_licas.append(lica)
-
- # Update LICAs remotely.
- licas = lica_service.updateLineItemCreativeAssociations(updated_licas)
-
- # Display results.
- for lica in licas:
- print ('LICA with line item id \'%s\', creative id \'%s\', and status '
- '\'%s\' was updated.' % (lica['lineItemId'], lica['creativeId'],
- lica['status']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- if response['totalResultSetSize'] == 0:
- print 'No LICAs found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/line_item_service/__init__.py b/examples/dfp/v201405/line_item_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201405/line_item_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201405/line_item_service/activate_line_items.py b/examples/dfp/v201405/line_item_service/activate_line_items.py
deleted file mode 100755
index 47f0ba84..00000000
--- a/examples/dfp/v201405/line_item_service/activate_line_items.py
+++ /dev/null
@@ -1,86 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example activates all line items for the given order.
-
-To be activated, line items need to be in the approved state and have at least
-one creative associated with them. To approve line items, approve the order to
-which they belong by running approve_orders.py. To create LICAs, run
-create_licas.py. To determine which line items exist, run
-get_all_line_items.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the id of the order to get line items from.
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-
-
-def main(client, order_id):
- # Initialize appropriate service.
- line_item_service = client.GetService('LineItemService', version='v201405')
-
- # Create query.
- values = [{
- 'key': 'orderId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': order_id
- }
- }, {
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'NEEDS_CREATIVES'
- }
- }]
- query = 'WHERE orderId = :orderId AND status = :status'
- statement = dfp.FilterStatement(query, values)
-
- line_items_activated = 0
-
- # Get line items by statement.
- while True:
- response = line_item_service.getLineItemsByStatement(
- statement.ToStatement())
- if 'results' in response:
- for line_item in response['results']:
- print ('Line item with id \'%s\', belonging to order id \'%s\', and '
- 'name \'%s\' will be activated.' %
- (line_item['id'], line_item['orderId'], line_item['name']))
-
- # Perform action.
- result = line_item_service.performLineItemAction(
- {'xsi_type': 'ActivateLineItems'}, statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- line_items_activated += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Display results.
- if line_items_activated > 0:
- print 'Number of line items activated: %s' % line_items_activated
- else:
- print 'No line items were activated.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID)
diff --git a/examples/dfp/v201405/line_item_service/create_line_items.py b/examples/dfp/v201405/line_item_service/create_line_items.py
deleted file mode 100755
index b48a32b9..00000000
--- a/examples/dfp/v201405/line_item_service/create_line_items.py
+++ /dev/null
@@ -1,171 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new line items.
-
-To determine which line items exist, run get_all_line_items.py. To determine
-which orders exist, run get_all_orders.py. To determine which placements exist,
-run get_all_placements.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-from datetime import date
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set order that the created line item will belong to and add the id of a
-# placement containing ad units to target.
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-TARGETED_PLACEMENT_IDS = ['INSERT_PLACEMENT_IDS_HERE']
-
-
-def main(client, order_id, targeted_placement_ids):
- # Initialize appropriate service.
- line_item_service = client.GetService('LineItemService', version='v201405')
-
- # Create line item objects.
- line_items = []
- for i in xrange(5):
- line_item = {
- 'name': 'Line item #%s' % uuid.uuid4(),
- 'orderId': order_id,
- 'targeting': {
- 'inventoryTargeting': {
- 'targetedPlacementIds': targeted_placement_ids
- },
- 'geoTargeting': {
- 'targetedLocations': [
- {
- 'id': '2840',
- 'displayName': 'US'
- },
- {
- 'id': '20133',
- 'displayName': 'Geneva'
- },
- {
- 'id': '9000093',
- 'displayName': 'B3P',
- }
- ],
- 'excludedLocations': [
- {
- 'id': '1016367',
- 'displayName': 'Chicago',
- },
- {
- 'id': '200501',
- 'displayName': 'New York NY'
- }
- ]
- },
- 'dayPartTargeting': {
- 'dayParts': [
- {
- 'dayOfWeek': 'SATURDAY',
- 'startTime': {
- 'hour': '0',
- 'minute': 'ZERO'
- },
- 'endTime': {
- 'hour': '24',
- 'minute': 'ZERO'
- }
- },
- {
- 'dayOfWeek': 'SUNDAY',
- 'startTime': {
- 'hour': '0',
- 'minute': 'ZERO'
- },
- 'endTime': {
- 'hour': '24',
- 'minute': 'ZERO'
- }
- }
- ],
- 'timeZone': 'BROWSER'
- },
- 'userDomainTargeting': {
- 'domains': ['usa.gov'],
- 'targeted': 'false'
- },
- 'technologyTargeting': {
- 'browserTargeting': {
- 'browsers': [{'id': '500072'}],
- 'isTargeted': 'true'
- }
- }
- },
- 'creativePlaceholders': [
- {
- 'size': {
- 'width': '300',
- 'height': '250'
- }
- },
- {
- 'size': {
- 'width': '120',
- 'height': '600'
- }
- }
- ],
- 'startDateTimeType': 'IMMEDIATELY',
- 'lineItemType': 'STANDARD',
- 'endDateTime': {
- 'date': {
- 'year': str(date.today().year + 1),
- 'month': '9',
- 'day': '30'
- },
- 'hour': '0',
- 'minute': '0',
- 'second': '0'
- },
- 'costType': 'CPM',
- 'costPerUnit': {
- 'currencyCode': 'USD',
- 'microAmount': '2000000'
- },
- 'primaryGoal': {
- 'units': '50',
- 'unitType': 'IMPRESSIONS'
- },
- 'contractedUnitsBought': '100',
- 'creativeRotationType': 'EVEN',
- 'discountType': 'PERCENTAGE',
- 'allowOverbook': 'true'
- }
- line_items.append(line_item)
-
- # Add line items.
- line_items = line_item_service.createLineItems(line_items)
-
- # Display results.
- for line_item in line_items:
- print ('Line item with id \'%s\', belonging to order id \'%s\', and named '
- '\'%s\' was created.' % (line_item['id'], line_item['orderId'],
- line_item['name']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID, TARGETED_PLACEMENT_IDS)
-
diff --git a/examples/dfp/v201405/line_item_service/create_video_line_item.py b/examples/dfp/v201405/line_item_service/create_video_line_item.py
deleted file mode 100755
index bd73c567..00000000
--- a/examples/dfp/v201405/line_item_service/create_video_line_item.py
+++ /dev/null
@@ -1,150 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates a new line item to serve to video content.
-
-This feature is only available to DFP premium solution networks. To determine
-which line items exist, run get_all_line_items.py. To determine which orders
-exist, run get_all_orders.py. To create a video ad unit, run
-create_video_ad_unit.py. To create criteria for categories, run
-create_custom_targeting_keys_and_values.py"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-from datetime import date
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set order that all created line item will belong to and the video ad unit id
-# to target.
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-TARGETED_VIDEO_AD_UNIT_ID = 'INSERT_TARGETED_VIDEO_AD_UNIT_ID_HERE'
-
-# Set the custom targeting key ID and value ID representing the metadata on the
-# content to target. This would typically be a key representing a 'genre' and
-# a value representing something like 'comedy'.
-CONTENT_CUSTOM_TARGETING_KEY_ID = 'INSERT_CONTENT_CUSTOM_TARGETING_KEY_ID_HERE'
-CONTENT_CUSTOM_TARGETING_VALUE_ID = \
- 'INSERT_CONTENT_CUSTOM_TARGETING_VALUE_ID_HERE'
-
-
-def main(client, order_id, targeted_video_ad_unit_id,
- content_custom_targeting_key_id, content_custom_targeting_value_id):
- # Initialize appropriate service.
- line_item_service = client.GetService('LineItemService', version='v201405')
-
- # create custom criteria for the content metadata targeting.
- custom_criteria = {
- 'xsi_type': 'CustomCriteria',
- 'keyId': content_custom_targeting_key_id,
- 'valueIds': [content_custom_targeting_value_id],
- 'operator': 'IS'
- }
-
- # Create the custom criteria set.
- top_set = {
- 'xsi_type': 'CustomCriteriaSet',
- 'logicalOperator': 'OR',
- 'children': [custom_criteria]
- }
-
- # Create line item object.
- line_item = {
- 'name': 'Line item #%s' % uuid.uuid4(),
- 'orderId': order_id,
- 'targeting': {
- 'customTargeting': top_set,
- 'inventoryTargeting': {
- 'targetedAdUnits': [{'adUnitId': targeted_video_ad_unit_id,
- 'includeDescendants': 'true'}]
- },
- 'videoPositionTargeting': {
- 'targetedPositions': [
- {
- 'videoPosition': {
- 'positionType': 'PREROLL'
- }
- }
- ]
- }
- },
- 'creativePlaceholders': [
- {
- 'size': {
- 'width': '400',
- 'height': '300'
- },
- 'companions': [
- {
- 'size': {
- 'width': '300',
- 'height': '250'
- },
- },
- {
- 'size': {
- 'width': '728',
- 'height': '90'
- },
- }
- ]
- }
- ],
- 'environmentType': 'VIDEO_PLAYER',
- 'companionDeliveryOption': 'OPTIONAL',
- 'startDateTimeType': 'IMMEDIATELY',
- 'lineItemType': 'SPONSORSHIP',
- 'endDateTime': {
- 'date': {
- 'year': str(date.today().year + 1),
- 'month': '9',
- 'day': '30'
- },
- 'hour': '0',
- 'minute': '0',
- 'second': '0'
- },
- 'costType': 'CPM',
- 'costPerUnit': {
- 'currencyCode': 'USD',
- 'microAmount': '2000000'
- },
- 'primaryGoal': {
- 'units': '50',
- 'unitType': 'IMPRESSIONS'
- },
- 'contractedUnitsBought': '100',
- 'creativeRotationType': 'OPTIMIZED',
- 'discountType': 'PERCENTAGE',
- 'allowOverbook': 'true'
- }
-
- # Add line item.
- line_item = line_item_service.createLineItem(line_item)
-
- # Display results.
- print ('Video line item with id \'%s\', belonging to order id \'%s\', and '
- 'named \'%s\' was created.' % (line_item['id'], line_item['orderId'],
- line_item['name']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID, TARGETED_VIDEO_AD_UNIT_ID,
- CONTENT_CUSTOM_TARGETING_KEY_ID, CONTENT_CUSTOM_TARGETING_VALUE_ID)
diff --git a/examples/dfp/v201405/line_item_service/get_all_line_items.py b/examples/dfp/v201405/line_item_service/get_all_line_items.py
deleted file mode 100755
index 146f3299..00000000
--- a/examples/dfp/v201405/line_item_service/get_all_line_items.py
+++ /dev/null
@@ -1,54 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all line items.
-
-To create line items, run create_line_items.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- line_item_service = client.GetService('LineItemService', version='v201405')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get line items by statement.
- while True:
- response = line_item_service.getLineItemsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for line_item in response['results']:
- print ('Line item with id \'%s\', belonging to order id \'%s\', and '
- 'named \'%s\' was found.' %
- (line_item['id'], line_item['orderId'], line_item['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/line_item_service/get_line_items_by_statement.py b/examples/dfp/v201405/line_item_service/get_line_items_by_statement.py
deleted file mode 100755
index 49362200..00000000
--- a/examples/dfp/v201405/line_item_service/get_line_items_by_statement.py
+++ /dev/null
@@ -1,76 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all line items that need creatives for the given
-order.
-
-To create line items, run create_line_items.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the id of the order to get line items from.
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-
-
-def main(client, order_id):
- # Initialize appropriate service.
- line_item_service = client.GetService('LineItemService', version='v201405')
-
- # Create statement object to only select line items that need creatives from a
- # given order.
- values = [{
- 'key': 'orderId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': order_id
- }
- }, {
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'NEEDS_CREATIVES'
- }
- }]
- query = 'WHERE orderId = :orderId AND status = :status'
- statement = dfp.FilterStatement(query, values)
-
- while True:
- # Get line items by statement.
- response = line_item_service.getLineItemsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- # Display results.
- for line_item in response['results']:
- print ('Line item with id \'%s\', belonging to order id \'%s\', and '
- 'named \'%s\' was found.' % (line_item['id'],
- line_item['orderId'],
- line_item['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID)
diff --git a/examples/dfp/v201405/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201405/line_item_service/get_recently_updated_line_items.py
deleted file mode 100755
index cd06b15d..00000000
--- a/examples/dfp/v201405/line_item_service/get_recently_updated_line_items.py
+++ /dev/null
@@ -1,76 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example shows how to get recently updated line items.
-
-To create line items, run create_line_items.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import datetime
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-
-
-def main(client, order_id):
- # Initialize appropriate service.
- line_item_service = client.GetService('LineItemService', version='v201405')
-
- # Create statement object to only select line items belonging to the order and
- # have been modified in the last 3 days.
- three_days_ago = datetime.date.today() - datetime.timedelta(days=3)
- values = [{
- 'key': 'dateTimeString',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': three_days_ago.strftime('%Y-%m-%dT%H:%M:%S')
- }
- }, {
- 'key': 'orderId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': order_id
- }
- }]
- query = 'WHERE lastModifiedDateTime >= :dateTimeString AND orderId = :orderId'
- statement = dfp.FilterStatement(query, values)
-
- while True:
- # Get line items by statement.
- response = line_item_service.getLineItemsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- # Display results.
- for line_item in response['results']:
- print ('Line item with id \'%s\', belonging to order id \'%s\', and '
- 'named \'%s\' was found.' % (line_item['id'],
- line_item['orderId'],
- line_item['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID)
diff --git a/examples/dfp/v201405/line_item_service/target_custom_criteria.py b/examples/dfp/v201405/line_item_service/target_custom_criteria.py
deleted file mode 100755
index bc896dd0..00000000
--- a/examples/dfp/v201405/line_item_service/target_custom_criteria.py
+++ /dev/null
@@ -1,115 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates a line item to add custom criteria targeting.
-
-To determine which line items exist, run get_all_line_items.py. To determine
-which custom targeting keys and values exist, run
-get_all_custom_targeting_keys_and_values.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import pprint
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
-KEY_ID1 = 'INSERT_TARGETING_KEY_ID_HERE'
-KEY_ID2 = 'INSERT_TARGETING_KEY_ID_HERE'
-KEY_ID3 = 'INSERT_TARGETING_KEY_ID_HERE'
-
-VALUE_ID1 = 'INSERT_TARGETING_VALUE_ID_HERE'
-VALUE_ID2 = 'INSERT_TARGETING_VALUE_ID_HERE'
-VALUE_ID3 = 'INSERT_TARGETING_VALUE_ID_HERE'
-
-
-def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2,
- value_id3):
- # Initialize appropriate service.
- line_item_service = client.GetService('LineItemService', version='v201405')
-
- # create custom criterias
- custom_criteria1 = {
- 'xsi_type': 'CustomCriteria',
- 'keyId': key_id1,
- 'valueIds': [value_id1],
- 'operator': 'IS'
- }
-
- custom_criteria2 = {
- 'xsi_type': 'CustomCriteria',
- 'keyId': key_id2,
- 'valueIds': [value_id2],
- 'operator': 'IS_NOT'
- }
-
- custom_criteria3 = {
- 'xsi_type': 'CustomCriteria',
- 'keyId': key_id3,
- 'valueIds': [value_id3],
- 'operator': 'IS'
- }
-
- # Create the custom criteria set that will resemble:
- # (custom_criteria1.key == custom_criteria1.value OR
- # (custom_criteria2.key != custom_criteria2.value AND
- # custom_criteria13.key == custom_criteria3.value))
- sub_set = {
- 'xsi_type': 'CustomCriteriaSet',
- 'logicalOperator': 'AND',
- 'children': [custom_criteria2, custom_criteria3]
- }
-
- top_set = {
- 'xsi_type': 'CustomCriteriaSet',
- 'logicalOperator': 'OR',
- 'children': [custom_criteria1, sub_set]
- }
-
- # Create statement to get the line item
- values = [{
- 'key': 'lineItemId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': line_item_id
- }
- }]
- query = 'WHERE id = :lineItemId'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Set custom criteria targeting on the line item.
- line_item = line_item_service.getLineItemsByStatement(
- statement.ToStatement())['results'][0]
- line_item['targeting']['customTargeting'] = top_set
-
- # Update line item.
- line_item = line_item_service.updateLineItems([line_item])[0]
-
- # Display results.
- if line_item:
- print ('Line item with id \'%s\' updated with custom criteria targeting:'
- % line_item['id'])
- pprint.pprint(line_item['targeting']['customTargeting'])
- else:
- print 'No line items were updated.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, LINE_ITEM_ID, KEY_ID1, KEY_ID2, KEY_ID3, VALUE_ID1,
- VALUE_ID2, VALUE_ID3)
diff --git a/examples/dfp/v201405/line_item_service/update_line_items.py b/examples/dfp/v201405/line_item_service/update_line_items.py
deleted file mode 100755
index d2d5f68a..00000000
--- a/examples/dfp/v201405/line_item_service/update_line_items.py
+++ /dev/null
@@ -1,83 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates the delivery rate of all line items in an order.
-
-To determine which line items exist, run get_all_line_items.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set id of the order to get line items from.
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-
-
-def main(client, order_id):
- # Initialize appropriate service.
- line_item_service = client.GetService('LineItemService', version='v201405')
-
- # Create statement object to only select line items with even delivery rates.
- values = [{
- 'key': 'deliveryRateType',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'EVENLY'
- }
- }, {
- 'key': 'orderId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': order_id
- }
- }]
-
- query = 'WHERE deliveryRateType = :deliveryRateType and orderId = :orderId'
- statement = dfp.FilterStatement(query, values, 500)
-
- # Get line items by statement.
- response = line_item_service.getLineItemsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- # Update each local line item by changing its delivery rate type.
- updated_line_items = []
- for line_item in response['results']:
- if not line_item['isArchived']:
- line_item['deliveryRateType'] = 'AS_FAST_AS_POSSIBLE'
- updated_line_items.append(line_item)
-
- # Update line items remotely.
- line_items = line_item_service.updateLineItems(updated_line_items)
-
- # Display results.
- if line_items:
- for line_item in line_items:
- print ('Line item with id \'%s\', belonging to order id \'%s\', named '
- '\'%s\', and delivery rate \'%s\' was updated.'
- % (line_item['id'], line_item['orderId'], line_item['name'],
- line_item['deliveryRateType']))
- else:
- print 'No line items were updated.'
- else:
- print 'No line items found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID)
diff --git a/examples/dfp/v201405/network_service/__init__.py b/examples/dfp/v201405/network_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201405/network_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201405/network_service/get_all_networks.py b/examples/dfp/v201405/network_service/get_all_networks.py
deleted file mode 100755
index d1e2091f..00000000
--- a/examples/dfp/v201405/network_service/get_all_networks.py
+++ /dev/null
@@ -1,46 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all networks that you have access to with the current login
-credentials.
-
-A networkCode should be left out for this request."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- network_service = client.GetService('NetworkService', version='v201405')
-
- # Get all networks that you have access to with the current login credentials.
- networks = network_service.getAllNetworks()
-
- # Display results.
- for network in networks:
- print ('Network with network code \'%s\' and display name \'%s\' was found.'
- % (network['networkCode'], network['displayName']))
-
- print '\nNumber of results found: %s' % len(networks)
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/network_service/get_current_network.py b/examples/dfp/v201405/network_service/get_current_network.py
deleted file mode 100755
index d7d2124b..00000000
--- a/examples/dfp/v201405/network_service/get_current_network.py
+++ /dev/null
@@ -1,40 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets the current network that you can make requests against."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- network_service = client.GetService('NetworkService', version='v201405')
-
- # Get the current network.
- network = network_service.getCurrentNetwork()
-
- # Display results.
- print ('Current network has network code \'%s\' and display name \'%s\'.'
- % (network['networkCode'], network['displayName']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/network_service/make_test_network.py b/examples/dfp/v201405/network_service/make_test_network.py
deleted file mode 100755
index fa4432a9..00000000
--- a/examples/dfp/v201405/network_service/make_test_network.py
+++ /dev/null
@@ -1,53 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates a test network.
-
-You do not need to have a DFP account to run this example, but you do need to
-have a Google account (created at http://www.google.com/accounts/newaccount
-if you currently don't have one) that is not associated with any other DFP test
-networks. Once this network is created, you can supply the network code in your
-settings to make calls to other services.
-
-Alternatively, if you do not wish to run this example, you can create a test
-network at:
-https://dfp-playground.appspot.com
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- network_service = client.GetService('NetworkService', version='v201405')
-
- # Create a test network.
- network = network_service.MakeTestNetwork()
-
- # Display results.
- print ('Test network with network code \'%s\' and display name \'%s\' '
- 'created.' % (network['networkCode'], network['displayName']))
- print ('You may now sign in at http://www.google.com/dfp/main?networkCode=%s'
- % network['networkCode'])
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/order_service/__init__.py b/examples/dfp/v201405/order_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201405/order_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201405/order_service/approve_orders.py b/examples/dfp/v201405/order_service/approve_orders.py
deleted file mode 100755
index eb2ad033..00000000
--- a/examples/dfp/v201405/order_service/approve_orders.py
+++ /dev/null
@@ -1,75 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example approves all eligible draft and pending orders.
-
-To determine which orders exist, run get_all_orders.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import datetime
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- order_service = client.GetService('OrderService', version='v201405')
-
- # Create query.
- values = [{
- 'key': 'today',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': datetime.date.today().strftime('%Y-%m-%dT%H:%M:%S')
- }
- }]
- query = ('WHERE status in (\'DRAFT\', \'PENDING_APPROVAL\')'
- ' AND endDateTime >= :today AND isArchived = FALSE')
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
- orders_approved = 0
-
- # Get orders by statement.
- while True:
- response = order_service.getOrdersByStatement(statement.ToStatement())
- if 'results' in response:
- # Display results.
- for order in response['results']:
- print ('Order with id \'%s\', name \'%s\', and status \'%s\' will be '
- 'approved.' % (order['id'], order['name'], order['status']))
- # Perform action.
- result = order_service.performOrderAction(
- {'xsi_type': 'ApproveOrders'}, statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- orders_approved += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Display results.
- if orders_approved > 0:
- print 'Number of orders approved: %s' % orders_approved
- else:
- print 'No orders were approved.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/order_service/create_orders.py b/examples/dfp/v201405/order_service/create_orders.py
deleted file mode 100755
index 8152dc93..00000000
--- a/examples/dfp/v201405/order_service/create_orders.py
+++ /dev/null
@@ -1,60 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new orders.
-
-To determine which orders exist, run get_all_orders.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
-SALESPERSON_ID = 'INSERT_SALESPERSON_ID_HERE'
-TRAFFICKER_ID = 'INSERT_TRAFFICKER_ID_HERE'
-
-
-def main(client, company_id, salesperson_id, trafficker_id):
- # Initialize appropriate service.
- order_service = client.GetService('OrderService', version='v201405')
-
- # Create order objects.
- orders = []
- for i in xrange(5):
- order = {
- 'name': 'Order #%s' % uuid.uuid4(),
- 'advertiserId': company_id,
- 'salespersonId': salesperson_id,
- 'traffickerId': trafficker_id
- }
- orders.append(order)
-
- # Add orders.
- orders = order_service.createOrders(orders)
-
- # Display results.
- for order in orders:
- print ('Order with id \'%s\' and name \'%s\' was created.'
- % (order['id'], order['name']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, COMPANY_ID, SALESPERSON_ID, TRAFFICKER_ID)
diff --git a/examples/dfp/v201405/order_service/get_all_orders.py b/examples/dfp/v201405/order_service/get_all_orders.py
deleted file mode 100755
index 8d397303..00000000
--- a/examples/dfp/v201405/order_service/get_all_orders.py
+++ /dev/null
@@ -1,54 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all orders.
-
-To create orders, run create_orders.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- order_service = client.GetService('OrderService', version='v201405')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get orders by statement.
- while True:
- response = order_service.getOrdersByStatement(statement.ToStatement())
- if 'results' in response:
- # Display results.
- for order in response['results']:
- print ('Order with id \'%s\', name \'%s\', and advertiser id \'%s\' was'
- ' found.' % (order['id'], order['name'], order['advertiserId']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/order_service/get_orders_by_statement.py b/examples/dfp/v201405/order_service/get_orders_by_statement.py
deleted file mode 100755
index 9cd835ae..00000000
--- a/examples/dfp/v201405/order_service/get_orders_by_statement.py
+++ /dev/null
@@ -1,63 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets an order by an ID.
-
-To create orders, run create_orders.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set id of the order to get.
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-
-
-def main(client, order_id):
- # Initialize appropriate service.
- order_service = client.GetService('OrderService', version='v201405')
-
- # Create statement object to select a single order by an ID.
- values = [{
- 'key': 'orderId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': order_id
- }
- }]
- query = 'WHERE id = :orderId'
-
- statement = dfp.FilterStatement(query, values)
-
- # Get orders by statement.
- response = order_service.getOrdersByStatement(statement.ToStatement())
- orders = []
- if 'results' in response:
- orders = response['results']
-
- # Display results.
- for order in orders:
- print ('Order with id \'%s\' name \'%s\' was found.'
- % (order['id'], order['name']))
-
- print '\nNumber of results found: %s' % len(orders)
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID)
diff --git a/examples/dfp/v201405/order_service/update_orders.py b/examples/dfp/v201405/order_service/update_orders.py
deleted file mode 100755
index 5004019e..00000000
--- a/examples/dfp/v201405/order_service/update_orders.py
+++ /dev/null
@@ -1,77 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates the notes of a single order specified by ID.
-
-To determine which orders exist, run get_all_orders.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-
-
-def main(client, order_id):
- # Initialize appropriate service.
- order_service = client.GetService('OrderService', version='v201405')
-
- # Create statement object to select a single order by an ID.
- values = [{
- 'key': 'orderId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': order_id
- }
- }]
- query = 'WHERE id = :orderId'
-
- statement = dfp.FilterStatement(query, values)
-
- # Get orders by statement.
- response = order_service.getOrdersByStatement(statement.ToStatement())
-
- if 'results' in response:
- # Update each local order object by changing its notes.
- updated_orders = []
- for order in response['results']:
- # Archived orders cannot be updated.
- if not order['isArchived']:
- order['notes'] = 'Spoke to advertiser. All is well.'
- updated_orders.append(order)
-
- # Update orders remotely.
- orders = order_service.updateOrders(updated_orders)
-
- # Display results.
- if orders:
- for order in orders:
- print ('Order with id \'%s\', name \'%s\', advertiser id \'%s\', and '
- 'notes \'%s\' was updated.'
- % (order['id'], order['name'], order['advertiserId'],
- order['notes']))
- else:
- print 'No orders were updated.'
- else:
- print 'No orders found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID)
-
diff --git a/examples/dfp/v201405/placement_service/create_placements.py b/examples/dfp/v201405/placement_service/create_placements.py
deleted file mode 100755
index 59579383..00000000
--- a/examples/dfp/v201405/placement_service/create_placements.py
+++ /dev/null
@@ -1,110 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new placements for various ad unit sizes.
-
-To determine which placements exist, run get_all_placements.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- placement_service = client.GetService('PlacementService', version='v201405')
- inventory_service = client.GetService('InventoryService', version='v201405')
-
- # Create placement object to store medium rectangle ad units.
- medium_rectangle_ad_unit_placement = {
- 'name': 'Medium rectangle AdUnit Placement #%s' % uuid.uuid4(),
- 'description': 'Contains ad units that hold creatives of size 300x250',
- 'targetedAdUnitIds': []
- }
-
- # Create placement object to store skyscraper ad units.
- skyscraper_ad_unit_placement = {
- 'name': 'Skyscraper AdUnit Placement #%s' % uuid.uuid4(),
- 'description': 'Contains ad units that hold creatives of size 120x600',
- 'targetedAdUnitIds': []
- }
-
- # Create placement object to store banner ad units.
- banner_ad_unit_placement = {
- 'name': 'Banner AdUnit Placement #%s' % uuid.uuid4(),
- 'description': 'Contains ad units that hold creatives of size 468x60',
- 'targetedAdUnitIds': []
- }
-
- placement_list = []
-
- # Create statement to get all the ad units.
- statement = dfp.FilterStatement()
-
- while True:
- response = inventory_service.getAdUnitsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- # Separate the ad units by size.
- for ad_unit in response['results']:
- if 'adUnitSizes' in ad_unit:
- for ad_unit_size in ad_unit['adUnitSizes']:
- size = ad_unit_size['size']
- if size['width'] == '300' and size['height'] == '250':
- medium_rectangle_ad_unit_placement['targetedAdUnitIds'].append(
- ad_unit['id'])
- elif size['width'] == '120' and size['height'] == '600':
- skyscraper_ad_unit_placement['targetedAdUnitIds'].append(
- ad_unit['id'])
- elif size['width'] == '468' and size['height'] == '60':
- banner_ad_unit_placement['targetedAdUnitIds'].append(
- ad_unit['id'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Only create placements with one or more ad unit.
- if medium_rectangle_ad_unit_placement['targetedAdUnitIds']:
- placement_list.append(medium_rectangle_ad_unit_placement)
-
- if skyscraper_ad_unit_placement['targetedAdUnitIds']:
- placement_list.append(skyscraper_ad_unit_placement)
-
- if banner_ad_unit_placement['targetedAdUnitIds']:
- placement_list.append(banner_ad_unit_placement)
-
- # Add placements.
- placements = placement_service.createPlacements(placement_list)
-
- # Display results.
- for placement in placements:
- ad_unit_ids = ''
- if 'targetedAdUnitIds' in placement:
- ad_unit_ids = ', '.join(placement['targetedAdUnitIds'])
- print ('A Placement with ID \'%s\', name \'%s\', and containing ad units '
- '{%s} was created.' % (placement['id'], placement['name'],
- ad_unit_ids))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/placement_service/deactivate_placements.py b/examples/dfp/v201405/placement_service/deactivate_placements.py
deleted file mode 100755
index c17ce803..00000000
--- a/examples/dfp/v201405/placement_service/deactivate_placements.py
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example deactivates all active placements.
-
-To determine which placements exist, run get_all_placements.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-PLACEMENT_ID = 'INSERT_PLACEMENT_ID_HERE'
-
-
-def main(client, placement_id):
- # Initialize appropriate service.
- placement_service = client.GetService('PlacementService', version='v201405')
-
- # Create query.
- values = [{
- 'key': 'placementId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': placement_id
- }
- }]
- query = 'WHERE id = :placementId'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get placements by statement.
- placements = placement_service.getPlacementsByStatement(
- statement.ToStatement())
-
- for placement in placements:
- print ('Placement with id \'%s\', name \'%s\', and status \'%s\' will be '
- 'deactivated.' % (placement['id'], placement['name'],
- placement['status']))
-
- # Perform action.
- result = placement_service.performPlacementAction(
- {'xsi_type': 'DeactivatePlacements'}, statement.ToStatement())
-
- # Display results.
- if result and int(result['numChanges']) > 0:
- print 'Number of placements deactivated: %s' % result['numChanges']
- else:
- print 'No placements were deactivated.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PLACEMENT_ID)
diff --git a/examples/dfp/v201405/placement_service/get_all_placements.py b/examples/dfp/v201405/placement_service/get_all_placements.py
deleted file mode 100755
index ed6a8be9..00000000
--- a/examples/dfp/v201405/placement_service/get_all_placements.py
+++ /dev/null
@@ -1,54 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all placements.
-
-To create placements, run create_placement.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- placement_service = client.GetService('PlacementService', version='v201405')
-
- # Create statement to fetch all placements.
- statement = dfp.FilterStatement()
-
- # Get placements by statement.
- while True:
- response = placement_service.getPlacementsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for placement in response['results']:
- print ('Placement with id \'%s\' and name \'%s\' was found.'
- % (placement['id'], placement['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/placement_service/get_placements_by_statement.py b/examples/dfp/v201405/placement_service/get_placements_by_statement.py
deleted file mode 100755
index aa6cf237..00000000
--- a/examples/dfp/v201405/placement_service/get_placements_by_statement.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all active placements by using a statement.
-
-To create a placement, run create_placements.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- placement_service = client.GetService('PlacementService', version='v201405')
-
- # Create a statement to only select active placements.
- values = [{
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ACTIVE'
- }
- }]
- query = 'WHERE status = :status'
- statement = dfp.FilterStatement(query, values)
-
- # Get placements by statement.
- while True:
- response = placement_service.getPlacementsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for placement in response['results']:
- print ('Placement with id \'%s\' and name \'%s\' was found.'
- % (placement['id'], placement['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/placement_service/update_placements.py b/examples/dfp/v201405/placement_service/update_placements.py
deleted file mode 100755
index 5d8cacee..00000000
--- a/examples/dfp/v201405/placement_service/update_placements.py
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates a single placement to allow for AdSense targeting.
-
-To determine which placements exist, run get_all_placements.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-PLACEMENT_ID = 'INSERT_PLACEMENT_ID_HERE'
-
-
-def main(client, placement_id):
- # Initialize appropriate service.
- placement_service = client.GetService('PlacementService', version='v201405')
-# Create query.
- values = [{
- 'key': 'placementId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': placement_id
- }
- }]
- query = 'WHERE id = :placementId'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get placements by statement.
- placements = placement_service.getPlacementsByStatement(
- statement.ToStatement())
-
- for placement in placements:
- if not placement['targetingDescription']:
- placement['targetingDescription'] = 'Generic description'
- placement['targetingAdLocation'] = 'All images on sports pages.'
- placement['targetingSiteName'] = 'http://code.google.com'
- placement['isAdSenseTargetingEnabled'] = 'true'
-
- # Update placements remotely.
- placements = placement_service.updatePlacements(placements)
-
- for placement in placements:
- print ('Placement with id \'%s\', name \'%s\', and AdSense targeting '
- 'enabled \'%s\' was updated.'
- % (placement['id'], placement['name'],
- placement['isAdSenseTargetingEnabled']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PLACEMENT_ID)
diff --git a/examples/dfp/v201405/publisher_query_language_service/__init__.py b/examples/dfp/v201405/publisher_query_language_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201405/publisher_query_language_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201405/publisher_query_language_service/fetch_match_tables.py b/examples/dfp/v201405/publisher_query_language_service/fetch_match_tables.py
deleted file mode 100755
index eaab1613..00000000
--- a/examples/dfp/v201405/publisher_query_language_service/fetch_match_tables.py
+++ /dev/null
@@ -1,57 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example fetches data from PQL tables and creates match table files."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import tempfile
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize a report downloader.
- report_downloader = client.GetDataDownloader(version='v201405')
-
- line_items_file = tempfile.NamedTemporaryFile(
- prefix='line_items_', suffix='.csv', mode='w', delete=False)
- ad_units_file = tempfile.NamedTemporaryFile(
- prefix='ad_units_', suffix='.csv', mode='w', delete=False)
-
- line_items_pql_query = ('SELECT Name, Id, Status FROM Line_Item ORDER BY Id '
- 'ASC')
- ad_units_pql_query = 'SELECT Name, Id FROM Ad_Unit ORDER BY Id ASC'
-
- # Downloads the response from PQL select statement to the specified file
- report_downloader.DownloadPqlResultToCsv(
- line_items_pql_query, line_items_file)
- report_downloader.DownloadPqlResultToCsv(
- ad_units_pql_query, ad_units_file)
-
- line_items_file.close()
- ad_units_file.close()
-
- print ('Saved line items to... %s' % line_items_file.name)
- print ('Saved ad units to... %s' % ad_units_file.name)
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/publisher_query_language_service/get_geo_targets.py b/examples/dfp/v201405/publisher_query_language_service/get_geo_targets.py
deleted file mode 100755
index 89af2842..00000000
--- a/examples/dfp/v201405/publisher_query_language_service/get_geo_targets.py
+++ /dev/null
@@ -1,65 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets geographic criteria from the Geo_Target table.
-
-The types available to filter on include 'City', 'Country', 'Region', 'State',
-'Postal_Code', and 'DMA_Region' (i.e. Metro).
-
-A full list of available geo target types can be found at
-https://developers.google.com/doubleclick-publishers/docs/reference/v201405/PublisherQueryLanguageService
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import tempfile
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize a report downloader.
- report_downloader = client.GetDataDownloader(version='v201405')
-
- output_file = tempfile.NamedTemporaryFile(
- prefix='geo_target_type_', suffix='.csv', mode='w', delete=False)
-
- # Create bind value to select geo-targets of type 'City'.
- values = [{
- 'key': 'type',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'City'
- }
- }]
-
- pql_query = ('SELECT Name, Id FROM Geo_Target '
- 'WHERE targetable = true AND Type = :type')
-
- # Downloads the response from PQL select statement to the specified file
- report_downloader.DownloadPqlResultToCsv(
- pql_query, output_file, values)
- output_file.close()
-
- print ('Saved geo targets to... %s' % output_file.name)
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/publisher_query_language_service/get_line_items_named_like.py b/examples/dfp/v201405/publisher_query_language_service/get_line_items_named_like.py
deleted file mode 100755
index 0ad3e7d1..00000000
--- a/examples/dfp/v201405/publisher_query_language_service/get_line_items_named_like.py
+++ /dev/null
@@ -1,58 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all line items with names starting with 'line item'."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import tempfile
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize a report downloader.
- report_downloader = client.GetDataDownloader(version='v201405')
-
- output_file = tempfile.NamedTemporaryFile(
- prefix='line_items_named_like_', suffix='.csv', mode='w', delete=False)
-
- # Create bind value to select line items with names starting with 'line item'.
- values = [{
- 'key': 'name',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'line item%'
- }
- }]
-
- pql_query = ('SELECT Name, Id, Status FROM Line_Item '
- 'WHERE Name LIKE :name')
-
- # Downloads the response from PQL select statement to the specified file
- report_downloader.DownloadPqlResultToCsv(
- pql_query, output_file, values)
- output_file.close()
-
- print ('Saved line items to... %s' % output_file.name)
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/report_service/__init__.py b/examples/dfp/v201405/report_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201405/report_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201405/report_service/run_delivery_report.py b/examples/dfp/v201405/report_service/run_delivery_report.py
deleted file mode 100755
index 859262da..00000000
--- a/examples/dfp/v201405/report_service/run_delivery_report.py
+++ /dev/null
@@ -1,85 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example runs a report similar to the "Orders report" on the DFP
-website with additional attributes and can filter to include just one order.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-import tempfile
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-from googleads import errors
-
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-
-
-def main(client, order_id):
- # Initialize a DataDownloader.
- report_downloader = client.GetDataDownloader(version='v201405')
-
- # Create statement object to filter for an order.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': order_id
- }
- }]
- filter_statement = {'query': 'WHERE ORDER_ID = :id',
- 'values': values}
-
- # Create report job.
- report_job = {
- 'reportQuery': {
- 'dimensions': ['ORDER_ID', 'ORDER_NAME'],
- 'dimensionAttributes': ['ORDER_TRAFFICKER', 'ORDER_START_DATE_TIME',
- 'ORDER_END_DATE_TIME'],
- 'statement': filter_statement,
- 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS',
- 'AD_SERVER_CTR', 'AD_SERVER_CPM_AND_CPC_REVENUE',
- 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'],
- 'dateRangeType': 'LAST_MONTH'
- }
- }
-
- try:
- # Run the report and wait for it to finish.
- report_job_id = report_downloader.WaitForReport(report_job)
- except errors.DfpReportError, e:
- print 'Failed to generate report. Error was: %s' % e
-
- # Change to your preferred export format.
- export_format = 'CSV_DUMP'
-
- report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
-
- # Download report data.
- report_downloader.DownloadReportToFile(
- report_job_id, export_format, report_file)
-
- report_file.close()
-
- # Display results.
- print 'Report job with id \'%s\' downloaded to:\n%s' % (
- report_job_id, report_file.name)
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID)
diff --git a/examples/dfp/v201405/report_service/run_inventory_report.py b/examples/dfp/v201405/report_service/run_inventory_report.py
deleted file mode 100755
index 00d278a4..00000000
--- a/examples/dfp/v201405/report_service/run_inventory_report.py
+++ /dev/null
@@ -1,90 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example runs a report equal to the "Whole network report" on the
-DFP website.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-import tempfile
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-from googleads import errors
-
-
-def main(client):
- # Initialize appropriate service.
- network_service = client.GetService('NetworkService', version='v201405')
- # Initialize a DataDownloader.
- report_downloader = client.GetDataDownloader(version='v201405')
-
- # Get root ad unit id for network.
- root_ad_unit_id = (
- network_service.getCurrentNetwork()['effectiveRootAdUnitId'])
-
- # Set filter statement and bind value for reportQuery.
- values = [{
- 'key': 'parent_ad_unit_id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': root_ad_unit_id
- }
- }]
- filter_statement = {'query': 'WHERE PARENT_AD_UNIT_ID = :parent_ad_unit_id',
- 'values': values}
-
- # Create report job.
- report_job = {
- 'reportQuery': {
- 'dimensions': ['DATE', 'AD_UNIT_NAME'],
- 'adUnitView': 'HIERARCHICAL',
- 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS',
- 'DYNAMIC_ALLOCATION_INVENTORY_LEVEL_IMPRESSIONS',
- 'DYNAMIC_ALLOCATION_INVENTORY_LEVEL_CLICKS',
- 'TOTAL_INVENTORY_LEVEL_IMPRESSIONS',
- 'TOTAL_INVENTORY_LEVEL_CPM_AND_CPC_REVENUE'],
- 'dateRangeType': 'LAST_WEEK',
- 'statement': filter_statement
- }
- }
-
- try:
- # Run the report and wait for it to finish.
- report_job_id = report_downloader.WaitForReport(report_job)
- except errors.DfpReportError, e:
- print 'Failed to generate report. Error was: %s' % e
-
- # Change to your preferred export format.
- export_format = 'CSV_DUMP'
-
- report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
-
- # Download report data.
- report_downloader.DownloadReportToFile(
- report_job_id, export_format, report_file)
-
- report_file.close()
-
- # Display results.
- print 'Report job with id \'%s\' downloaded to:\n%s' % (
- report_job_id, report_file.name)
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/report_service/run_merged_delivery_report.py b/examples/dfp/v201405/report_service/run_merged_delivery_report.py
deleted file mode 100755
index e1feec25..00000000
--- a/examples/dfp/v201405/report_service/run_merged_delivery_report.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example runs a report that an upgraded publisher would use to
-include statistics before the upgrade.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-import tempfile
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-from googleads import errors
-
-
-def main(client):
- # Initialize a DataDownloader.
- report_downloader = client.GetDataDownloader(version='v201405')
-
- # Create report job.
- report_job = {
- 'reportQuery': {
- 'dimensions': ['ORDER_ID', 'ORDER_NAME'],
- 'columns': ['MERGED_AD_SERVER_IMPRESSIONS', 'MERGED_AD_SERVER_CLICKS',
- 'MERGED_AD_SERVER_CTR',
- 'MERGED_AD_SERVER_CPM_AND_CPC_REVENUE',
- 'MERGED_AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'],
- 'dateRangeType': 'LAST_MONTH'
- }
- }
-
- try:
- # Run the report and wait for it to finish.
- report_job_id = report_downloader.WaitForReport(report_job)
- except errors.DfpReportError, e:
- print 'Failed to generate report. Error was: %s' % e
-
- # Change to your preferred export format.
- export_format = 'CSV_DUMP'
-
- report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
-
- # Download report data.
- report_downloader.DownloadReportToFile(
- report_job_id, export_format, report_file)
-
- report_file.close()
-
- # Display results.
- print 'Report job with id \'%s\' downloaded to:\n%s' % (
- report_job_id, report_file.name)
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/report_service/run_reach_report.py b/examples/dfp/v201405/report_service/run_reach_report.py
deleted file mode 100755
index ff626d4b..00000000
--- a/examples/dfp/v201405/report_service/run_reach_report.py
+++ /dev/null
@@ -1,66 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example runs a reach report."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-import tempfile
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-from googleads import errors
-
-
-def main(client):
- # Initialize a DataDownloader.
- report_downloader = client.GetDataDownloader(version='v201405')
-
- # Create report job.
- report_job = {
- 'reportQuery': {
- 'dimensions': ['LINE_ITEM_ID', 'LINE_ITEM_NAME'],
- 'columns': ['REACH_FREQUENCY', 'REACH_AVERAGE_REVENUE', 'REACH'],
- 'dateRangeType': 'REACH_LIFETIME'
- }
- }
-
- try:
- # Run the report and wait for it to finish.
- report_job_id = report_downloader.WaitForReport(report_job)
- except errors.DfpReportError, e:
- print 'Failed to generate report. Error was: %s' % e
-
- # Change to your preferred export format.
- export_format = 'CSV_DUMP'
-
- report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
-
- # Download report data.
- report_downloader.DownloadReportToFile(
- report_job_id, export_format, report_file)
-
- report_file.close()
-
- # Display results.
- print 'Report job with id \'%s\' downloaded to:\n%s' % (
- report_job_id, report_file.name)
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/report_service/run_report_with_custom_fields.py b/examples/dfp/v201405/report_service/run_report_with_custom_fields.py
deleted file mode 100755
index d1d776fe..00000000
--- a/examples/dfp/v201405/report_service/run_report_with_custom_fields.py
+++ /dev/null
@@ -1,107 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example runs a report that with custom fields found in the line
-items of an order.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-import tempfile
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-from googleads import errors
-
-# Set the ID of the order to get line items from.
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-
-
-def main(client, order_id):
- # Initialize appropriate service.
- line_item_service = client.GetService('LineItemService', version='v201405')
- # Initialize a DataDownloader.
- report_downloader = client.GetDataDownloader(version='v201405')
-
- # Filter for line items of a given order.
- values = [{
- 'key': 'orderId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': order_id
- }
- }]
- query = 'WHERE orderId = :orderId'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Collect all line item custom field IDs for an order.
- custom_field_ids = set()
-
- # Get users by statement.
- while True:
- response = line_item_service.getLineItemsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Get custom field IDs from the line items of an order.
- for line_item in response['results']:
- if 'customFieldValues' in line_item:
- for custom_field_value in line_item['customFieldValues']:
- custom_field_ids.add(custom_field_value['customFieldId'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Create statement object to filter for an order.
- filter_statement = {'query': query, 'values': values}
-
- # Create report job.
- report_job = {
- 'reportQuery': {
- 'dimensions': ['LINE_ITEM_ID', 'LINE_ITEM_NAME'],
- 'statement': filter_statement,
- 'columns': ['AD_SERVER_IMPRESSIONS'],
- 'dateRangeType': 'LAST_MONTH',
- 'customFieldIds': list(custom_field_ids)
- }
- }
-
- try:
- # Run the report and wait for it to finish.
- report_job_id = report_downloader.WaitForReport(report_job)
- except errors.DfpReportError, e:
- print 'Failed to generate report. Error was: %s' % e
-
- # Change to your preferred export format.
- export_format = 'CSV_DUMP'
-
- report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
-
- # Download report data.
- report_downloader.DownloadReportToFile(
- report_job_id, export_format, report_file)
-
- report_file.close()
-
- # Display results.
- print 'Report job with id \'%s\' downloaded to:\n%s' % (
- report_job_id, report_file.name)
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID)
diff --git a/examples/dfp/v201405/report_service/run_sales_report.py b/examples/dfp/v201405/report_service/run_sales_report.py
deleted file mode 100755
index c3ee6b3c..00000000
--- a/examples/dfp/v201405/report_service/run_sales_report.py
+++ /dev/null
@@ -1,67 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example runs a report equal to the "Sales by salespersons report."
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-import tempfile
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-from googleads import errors
-
-
-def main(client):
- # Initialize a DataDownloader.
- report_downloader = client.GetDataDownloader(version='v201405')
-
- # Create report job.
- report_job = {
- 'reportQuery': {
- 'dimensions': ['SALESPERSON_ID', 'SALESPERSON_NAME'],
- 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CPM_AND_CPC_REVENUE',
- 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'],
- 'dateRangeType': 'LAST_MONTH'
- }
- }
-
- try:
- # Run the report and wait for it to finish.
- report_job_id = report_downloader.WaitForReport(report_job)
- except errors.DfpReportError, e:
- print 'Failed to generate report. Error was: %s' % e
-
- # Change to your preferred export format.
- export_format = 'CSV_DUMP'
-
- report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
-
- # Download report data.
- report_downloader.DownloadReportToFile(
- report_job_id, export_format, report_file)
-
- report_file.close()
-
- # Display results.
- print 'Report job with id \'%s\' downloaded to:\n%s' % (
- report_job_id, report_file.name)
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/suggested_ad_unit_service/__init__.py b/examples/dfp/v201405/suggested_ad_unit_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201405/suggested_ad_unit_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201405/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/dfp/v201405/suggested_ad_unit_service/approve_all_suggested_ad_units.py
deleted file mode 100755
index cc2f450e..00000000
--- a/examples/dfp/v201405/suggested_ad_unit_service/approve_all_suggested_ad_units.py
+++ /dev/null
@@ -1,80 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example approves all suggested ad units with 50 or more requests.
-
-This feature is only available to DFP premium solution networks.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-THRESHOLD_NUMBER_OF_REQUESTS = '50'
-
-
-def main(client):
- # Initialize appropriate service.
- suggested_ad_unit_service = client.GetService(
- 'SuggestedAdUnitService', version='v201405')
-
- values = [{
- 'key': 'numRequests',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': THRESHOLD_NUMBER_OF_REQUESTS
- }
- }]
-
- query = 'WHERE numRequests > :numRequests'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
- num_approved_suggested_ad_units = 0
-
- # Get suggested ad units by statement.
- while True:
- response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Print suggested ad units that will be approved.
- for suggested_ad_unit in response['results']:
- print ('Suggested ad unit with id \'%s\', and number of requests \'%s\''
- ' will be approved.' % (suggested_ad_unit['id'],
- suggested_ad_unit['numRequests']))
-
- # Approve suggested ad units.
- result = suggested_ad_unit_service.performSuggestedAdUnitAction(
- {'xsi_type': 'ApproveSuggestedAdUnit'},
- statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- num_approved_suggested_ad_units += int(result['numChanges'])
- else:
- break
-
- if num_approved_suggested_ad_units > 0:
- print ('Number of suggested ad units approved: %s' %
- num_approved_suggested_ad_units)
- else:
- print 'No suggested ad units were approved.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
-
diff --git a/examples/dfp/v201405/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/dfp/v201405/suggested_ad_unit_service/get_all_suggested_ad_units.py
deleted file mode 100755
index d8d588fc..00000000
--- a/examples/dfp/v201405/suggested_ad_unit_service/get_all_suggested_ad_units.py
+++ /dev/null
@@ -1,56 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all suggested ad units.
-
-To approve suggested ad units, run approve_suggested_ad_units.py. This feature
-is only available to DFP premium solution networks.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- suggested_ad_unit_service = client.GetService(
- 'SuggestedAdUnitService', version='v201405')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get suggested ad units by statement.
- while True:
- response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for suggested_ad_unit in response['results']:
- print ('Ad unit with id \'%s\' and number of requests \'%s\' was found.'
- % (suggested_ad_unit['id'], suggested_ad_unit['numRequests']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py b/examples/dfp/v201405/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py
deleted file mode 100755
index 1634a7bb..00000000
--- a/examples/dfp/v201405/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py
+++ /dev/null
@@ -1,65 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets suggested ad units that have more than 50 requests.
-
-This feature is only available to DFP premium solution networks.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- suggested_ad_unit_service = client.GetService(
- 'SuggestedAdUnitService', version='v201405')
-
- values = [{
- 'key': 'numRequests',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': '50'
- }
- }]
-
- query = 'WHERE numRequests > :numRequests'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Get suggested ad units by statement.
- while True:
- response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for suggested_ad_unit in response['results']:
- print ('Ad unit with id \'%s\' and number of requests \'%s\' was found.'
- % (suggested_ad_unit['id'], suggested_ad_unit['numRequests']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/team_service/__init__.py b/examples/dfp/v201405/team_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201405/team_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201405/team_service/create_teams.py b/examples/dfp/v201405/team_service/create_teams.py
deleted file mode 100755
index 13e76d8e..00000000
--- a/examples/dfp/v201405/team_service/create_teams.py
+++ /dev/null
@@ -1,64 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates new teams.
-
-To determine which teams exist, run get_all_teams.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: TeamService.createTeams
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- team_service = client.GetService('TeamService', version='v201405')
-
- # Create team objects.
- teams = []
- for i in xrange(5):
- team = {
- 'name': 'Team %s' % uuid.uuid4(),
- 'hasAllCompanies': 'false',
- 'hasAllInventory': 'false',
- 'teamAccessType': 'READ_WRITE'
- }
- teams.append(team)
-
- # Add Teams.
- teams = team_service.createTeams(teams)
-
- # Display results.
- for team in teams:
- print ('Team with ID \'%s\' and name \'%s\' was created.'
- % (team['id'], team['name']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/team_service/get_all_teams.py b/examples/dfp/v201405/team_service/get_all_teams.py
deleted file mode 100755
index 25b21756..00000000
--- a/examples/dfp/v201405/team_service/get_all_teams.py
+++ /dev/null
@@ -1,60 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all teams.
-
-To create teams, run create_teams.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: TeamService.getTeamsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- team_service = client.GetService('TeamService', version='v201405')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get users by statement.
- while True:
- response = team_service.getTeamsByStatement(statement.ToStatement())
- if 'results' in response:
- # Display results.
- for team in response['results']:
- print ('Team with ID \'%s\' and name \'%s\' was found.'
- % (team['id'], team['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/team_service/get_teams_by_statement.py b/examples/dfp/v201405/team_service/get_teams_by_statement.py
deleted file mode 100755
index 9780c17a..00000000
--- a/examples/dfp/v201405/team_service/get_teams_by_statement.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets a single team by ID.
-
-To create teams, run create_teams.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: TeamService.getTeamsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-TEAM_ID = 'INSERT_TEAM_ID_HERE'
-
-
-def main(client, team_id):
- # Initialize appropriate service.
- team_service = client.GetService('TeamService', version='v201405')
-
- # Create a filter statement to select a single team by ID.
- values = [{
- 'key': 'teamId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': team_id
- }
- }]
- query = 'WHERE id = :teamId'
- statement = dfp.FilterStatement(query, values)
-
- while True:
- # Get teams by statement.
- response = team_service.getTeamsByStatement(statement.ToStatement())
- if 'results' in response:
- # Display results.
- for team in response['results']:
- print ('Team with id \'%s\' and name \'%s\' was found.'
- % (team['id'], team['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, TEAM_ID)
diff --git a/examples/dfp/v201405/team_service/update_teams.py b/examples/dfp/v201405/team_service/update_teams.py
deleted file mode 100755
index 418df851..00000000
--- a/examples/dfp/v201405/team_service/update_teams.py
+++ /dev/null
@@ -1,84 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates teams by adding an ad unit to a team.
-
-To determine which teams exist, run get_all_teams.py. To determine which ad
-units exist, run get_all_ad_units.py
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: TeamService.getTeamsByStatement, TeamService.updateTeams
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE'
-TEAM_ID = 'INSERT_TEAM_ID_HERE'
-
-
-def main(client, ad_unit_id, team_id):
- # Initialize appropriate service.
- team_service = client.GetService('TeamService', version='v201405')
-
- # Create a filter statement to select a single team by ID.
- values = [{
- 'key': 'teamId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': team_id
- }
- }]
- query = 'WHERE id = :teamId'
- statement = dfp.FilterStatement(query, values)
-
- # Get teams by statement.
- response = team_service.getTeamsByStatement(statement.ToStatement())
-
- if 'results' in response:
- updated_teams = []
- # Update each local team object by adding the ad unit to it.
- for team in response['results']:
- ad_unit_ids = []
- if 'adUnitIds' in team:
- ad_unit_ids = team['adUnitIds']
- # Don't add the ad unit if the team has all inventory already.
- if not team['hasAllInventory']:
- ad_unit_ids.append(ad_unit_id)
- team['adUnitIds'] = ad_unit_ids
- updated_teams.append(team)
-
- # Update teams on the server.
- teams = team_service.updateTeams(updated_teams)
-
- # Display results.
- for team in teams:
- print ('Team with id \'%s\' and name \'%s\' was updated.'
- % (team['id'], team['name']))
- else:
- print 'No teams found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, AD_UNIT_ID, TEAM_ID)
diff --git a/examples/dfp/v201405/user_service/__init__.py b/examples/dfp/v201405/user_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201405/user_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201405/user_service/create_users.py b/examples/dfp/v201405/user_service/create_users.py
deleted file mode 100755
index 2a432563..00000000
--- a/examples/dfp/v201405/user_service/create_users.py
+++ /dev/null
@@ -1,59 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new users.
-
-To determine which users exist, run get_all_users.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-NEW_USER_EMAIL_ADDRESS = 'INSERT_EMAIL_ADDRESS_HERE'
-NEW_USER_NAME = 'INSERT_NAME_HERE'
-
-
-def main(client, email, name):
- # Initialize appropriate service.
- user_service = client.GetService('UserService', version='v201405')
-
- # Create user objects.
- users = [
- {
- 'email': email,
- 'name': name,
- 'preferredLocale': 'en_US'
- }
- ]
- for user in users:
- # Set the system defined ID of the trafficker role.
- # To determine what other roles exist, run get_all_roles.py.
- user['roleId'] = '-7'
-
- # Add users.
- users = user_service.createUsers(users)
-
- # Display results.
- for user in users:
- print ('User with id \'%s\', email \'%s\', and role \'%s\' was created.'
- % (user['id'], user['email'], user['roleName']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, NEW_USER_EMAIL_ADDRESS, NEW_USER_NAME)
diff --git a/examples/dfp/v201405/user_service/deactivate_users.py b/examples/dfp/v201405/user_service/deactivate_users.py
deleted file mode 100755
index 6bbd4224..00000000
--- a/examples/dfp/v201405/user_service/deactivate_users.py
+++ /dev/null
@@ -1,73 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example deactivates a user.
-
-Deactivated users can no longer make requests to the API. The user making the
-request cannot deactivate itself. To determine which users exist, run
-get_all_users.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-USER_ID = 'INSERT_USER_ID_TO_DEACTIVATE_HERE'
-
-
-def main(client, user_id):
- # Initialize appropriate service.
- user_service = client.GetService('UserService', version='v201405')
-
- # Create query.
- values = [{
- 'key': 'userId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': user_id
- }
- }]
- query = 'WHERE id = :userId'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Get users by statement.
- response = user_service.getUsersByStatement(statement.ToStatement())
- users = response['results'] if 'results' in response else []
-
- for user in users:
- print ('User with id \'%s\', email \'%s\', and status \'%s\' will be '
- 'deactivated.'
- % (user['id'], user['email'],
- {'true': 'ACTIVE', 'false': 'INACTIVE'}[user['isActive']]))
- print 'Number of users to be deactivated: %s' % len(users)
-
- # Perform action.
- result = user_service.performUserAction({'xsi_type': 'DeactivateUsers'},
- statement.ToStatement())
-
- # Display results.
- if result and int(result['numChanges']) > 0:
- print 'Number of users deactivated: %s' % result['numChanges']
- else:
- print 'No users were deactivated.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, USER_ID)
diff --git a/examples/dfp/v201405/user_service/get_all_roles.py b/examples/dfp/v201405/user_service/get_all_roles.py
deleted file mode 100755
index fe260859..00000000
--- a/examples/dfp/v201405/user_service/get_all_roles.py
+++ /dev/null
@@ -1,46 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all roles.
-
-This sample can be used to determine which role id is needed when getting and
-creating users."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- user_service = client.GetService('UserService', version='v201405')
-
- # Get all roles.
- roles = user_service.getAllRoles()
-
- # Display results.
- for role in roles:
- print ('Role with id \'%s\' and name \'%s\' was found.'
- % (role['id'], role['name']))
-
- print '\nNumber of results found: %s' % len(roles)
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/user_service/get_all_users.py b/examples/dfp/v201405/user_service/get_all_users.py
deleted file mode 100755
index 6ca0c61a..00000000
--- a/examples/dfp/v201405/user_service/get_all_users.py
+++ /dev/null
@@ -1,50 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all users. To create users, run create_users.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- user_service = client.GetService('UserService', version='v201405')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get users by statement.
- while True:
- response = user_service.getUsersByStatement(statement.ToStatement())
- if 'results' in response:
- # Display results.
- for user in response['results']:
- print ('User with id \'%s\', email \'%s\', and role \'%s\' was found.'
- % (user['id'], user['email'], user['roleName']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/user_service/get_current_user.py b/examples/dfp/v201405/user_service/get_current_user.py
deleted file mode 100755
index 9669a5e7..00000000
--- a/examples/dfp/v201405/user_service/get_current_user.py
+++ /dev/null
@@ -1,40 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets the current user."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- user_service = client.GetService('UserService', version='v201405')
-
- # Get current user.
- user = user_service.getCurrentUser()
-
- # Display results.
- print ('User with id \'%s\', email \'%s\', and role \'%s\' was found.'
- % (user['id'], user['email'], user['roleName']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/user_service/get_users_by_statement.py b/examples/dfp/v201405/user_service/get_users_by_statement.py
deleted file mode 100755
index 9ed23fed..00000000
--- a/examples/dfp/v201405/user_service/get_users_by_statement.py
+++ /dev/null
@@ -1,59 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets a user by its id.
-
-To create users, run create_user.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-USER_ID = 'INSERT_USER_ID_TO_FIND_HERE'
-
-
-def main(client, user_id):
- # Initialize appropriate service.
- user_service = client.GetService('UserService', version='v201405')
-
- # Create query.
- values = [{
- 'key': 'userId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': user_id
- }
- }]
- query = 'WHERE id = :userId'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Get users by statement.
- response = user_service.getUsersByStatement(statement.ToStatement())
- users = response['results'] if 'results' in response else []
-
- for user in users:
- # Display results.
- print ('User with id \'%s\', email \'%s\', and role \'%s\' was found.'
- % (user['id'], user['email'], user['roleName']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, USER_ID)
diff --git a/examples/dfp/v201405/user_service/update_users.py b/examples/dfp/v201405/user_service/update_users.py
deleted file mode 100755
index 65fab866..00000000
--- a/examples/dfp/v201405/user_service/update_users.py
+++ /dev/null
@@ -1,66 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates a user by adding " Sr." to the end of their name.
-
-To determine which users exist, run get_all_users.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-USER_ID = 'INSERT_USER_ID_TO_UPDATE_HERE'
-
-
-def main(client, user_id):
- # Initialize appropriate service.
- user_service = client.GetService('UserService', version='v201405')
-
- # Create query.
- values = [{
- 'key': 'userId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': user_id
- }
- }]
- query = 'WHERE id = :userId'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Get users by statement.
- response = user_service.getUsersByStatement(statement.ToStatement())
-
- if 'results' in response:
- users = response['results']
- for user in users:
- user['name'] += ' Sr.'
-
- # Update users on server.
- users = user_service.updateUsers(users)
- for user in users:
- print ('User with id \'%s\' and name \'%s\' was updated.'
- % (user['id'], user['name']))
- else:
- print 'No users found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, USER_ID)
diff --git a/examples/dfp/v201405/user_team_association_service/__init__.py b/examples/dfp/v201405/user_team_association_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201405/user_team_association_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201405/user_team_association_service/create_user_team_associations.py b/examples/dfp/v201405/user_team_association_service/create_user_team_associations.py
deleted file mode 100755
index 4587fcd6..00000000
--- a/examples/dfp/v201405/user_team_association_service/create_user_team_associations.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds a user to a team by creating an association between them.
-
-To determine which teams exists, run get_all_teams.py. To determine which
-users exist, run get_all_users.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: UserTeamAssociationService.createUserTeamAssociations
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-TEAM_ID = 'INSERT_TEAM_ID_HERE'
-USER_IDS = ['INSERT_USER_IDS_TO_ASSOCIATE_TO_TEAM_HERE']
-
-
-def main(client, team_id, user_ids):
- # Initialize appropriate service.
- user_team_association_service = client.GetService(
- 'UserTeamAssociationService', version='v201405')
-
- user_team_associations = []
- for user_id in user_ids:
- user_team_associations.append(
- {
- 'teamId': team_id,
- 'userId': user_id
- })
-
- # Create the user team association on the server.
- user_team_associations = (
- user_team_association_service.createUserTeamAssociations(
- user_team_associations))
-
- # Display results.
- if user_team_associations:
- for user_team_association in user_team_associations:
- print ('A user team association between user with ID \'%s\' and team with'
- ' ID \'%s\'was created.' % (user_team_association['userId'],
- user_team_association['teamId']))
- else:
- print 'No user team associations created.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, TEAM_ID, USER_IDS)
diff --git a/examples/dfp/v201405/user_team_association_service/delete_user_team_associations.py b/examples/dfp/v201405/user_team_association_service/delete_user_team_associations.py
deleted file mode 100755
index adebf479..00000000
--- a/examples/dfp/v201405/user_team_association_service/delete_user_team_associations.py
+++ /dev/null
@@ -1,83 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example removes the user from all its teams.
-
-To determine which users exist, run get_all_users.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: UserTeamAssociationService.performUserTeamAssociationAction
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-USER_ID = 'INSERT_USER_ID_HERE'
-
-
-def main(client, user_id):
- # Initialize appropriate service.
- user_team_association_service = client.GetService(
- 'UserTeamAssociationService', version='v201405')
-
- # Create filter text to select user team associations by the user ID.
- values = [{
- 'key': 'userId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': user_id
- }
- }]
- query = 'WHERE userId = :userId'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Get user team associations by statement.
- response = user_team_association_service.getUserTeamAssociationsByStatement(
- statement.ToStatement())
- user_team_associations = response['results'] if 'results' in response else []
-
- for user_team_association in user_team_associations:
- print ('User team association between user with ID \'%s\' and team with '
- 'ID \'%s\' will be deleted.' % (user_team_association['userId'],
- user_team_association['teamId']))
- print ('Number of teams that the user will be removed from: %s' %
- len(user_team_associations))
-
- # Perform action.
- result = user_team_association_service.performUserTeamAssociationAction(
- {'xsi_type': 'DeleteUserTeamAssociations'},
- {'query': query, 'values': values})
-
- # Display results.
- if result and int(result['numChanges']) > 0:
- print ('Number of teams that the user was removed from: %s'
- % result['numChanges'])
- else:
- print 'No user team associations were deleted.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, USER_ID)
diff --git a/examples/dfp/v201405/user_team_association_service/get_all_user_team_associations.py b/examples/dfp/v201405/user_team_association_service/get_all_user_team_associations.py
deleted file mode 100755
index 1b034a74..00000000
--- a/examples/dfp/v201405/user_team_association_service/get_all_user_team_associations.py
+++ /dev/null
@@ -1,64 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all user team associations.
-
-To create user team associations, run create_user_team_assocations.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: UserTeamAssociationService.getUserTeamAssociationsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- user_team_association_service = client.GetService(
- 'UserTeamAssociationService', version='v201405')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get user team associations by statement.
- while True:
- response = user_team_association_service.getUserTeamAssociationsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for user_team_association in response['results']:
- print ('User team association between user with ID \'%s\' and team with'
- ' ID \'%s\' was found.' % (user_team_association['userId'],
- user_team_association['teamId']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201405/user_team_association_service/get_user_team_associations_for_user.py b/examples/dfp/v201405/user_team_association_service/get_user_team_associations_for_user.py
deleted file mode 100755
index ef6ef0bb..00000000
--- a/examples/dfp/v201405/user_team_association_service/get_user_team_associations_for_user.py
+++ /dev/null
@@ -1,75 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all user team associations for a single user.
-
-To determine which users exist, run get_all_users.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: UserTeamAssociationService.getUserTeamAssociation
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-USER_ID = 'INSERT_USER_ID_HERE'
-
-
-def main(client, user_id):
- # Initialize appropriate service.
- user_team_association_service = client.GetService(
- 'UserTeamAssociationService', version='v201405')
-
- # Create query.
- values = [{
- 'key': 'userId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': user_id
- }
- }]
- query = 'WHERE userId = :userId'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Get user team associations by statement.
- while True:
- response = user_team_association_service.getUserTeamAssociationsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for user_team_association in response['results']:
- print ('User team association between user with ID \'%s\' and team with'
- ' ID \'%s\' was found.' % (user_team_association['userId'],
- user_team_association['teamId']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, USER_ID)
diff --git a/examples/dfp/v201405/user_team_association_service/update_user_team_associations.py b/examples/dfp/v201405/user_team_association_service/update_user_team_associations.py
deleted file mode 100755
index faa6041f..00000000
--- a/examples/dfp/v201405/user_team_association_service/update_user_team_associations.py
+++ /dev/null
@@ -1,89 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates user team associations.
-
-It updates a user team association by setting the overridden access type to read
-only for all teams that the user belongs to. To determine which users exists,
-run get_all_users.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: UserTeamAssociationService.getUserTeamAssociationsByStatement
-Tags: UserTeamAssociationService.updateUserTeamAssociations
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-USER_ID = 'INSERT_USER_ID_TO_UPDATE_HERE'
-
-
-def main(client, user_id):
- # Initialize appropriate service.
- user_team_association_service = client.GetService(
- 'UserTeamAssociationService', version='v201405')
-
- # Create filter text to select user team associations by the user ID.
- values = [{
- 'key': 'userId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': user_id
- }
- }]
- query = 'WHERE userId = :userId'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Get user team associations by statement.
- response = user_team_association_service.getUserTeamAssociationsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- updated_user_team_associations = []
- # Update each local user team association to read only access.
- for user_team_association in response['results']:
- user_team_association['overriddenTeamAccessType'] = 'READ_ONLY'
- updated_user_team_associations.append(user_team_association)
-
- # Update user team associations on the server.
- user_team_associations = (
- user_team_association_service.updateUserTeamAssociations(
- updated_user_team_associations))
-
- # Display results.
- if user_team_associations:
- for user_team_association in user_team_associations:
- print ('User team association between user with ID \'%s\' and team with'
- ' ID \'%s\' was updated.' % (user_team_association['userId'],
- user_team_association['teamId']))
- else:
- print 'No user team associations were updated.'
- else:
- print 'No user team associations found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, USER_ID)
diff --git a/examples/dfp/v201408/activity_group_service/__init__.py b/examples/dfp/v201408/activity_group_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201408/activity_group_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201408/activity_group_service/create_activity_groups.py b/examples/dfp/v201408/activity_group_service/create_activity_groups.py
deleted file mode 100755
index 6021486d..00000000
--- a/examples/dfp/v201408/activity_group_service/create_activity_groups.py
+++ /dev/null
@@ -1,74 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new activity groups.
-
-To determine which activity groups exist, run get_all_activity_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ActivityGroupService.createActivityGroups
-"""
-
-__author__ = ('Vincent Tsao',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the advertiser company this activity group is associated with.
-ADVERTISER_COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
-
-
-def main(client, advertiser_company_id):
- # Initialize appropriate service.
- activity_group_service = client.GetService('ActivityGroupService',
- version='v201408')
-
- # Create a short-term activity group.
- short_term_activity_group = {
- 'name': 'Short-term activity group #%s' % uuid.uuid4(),
- 'companyIds': [advertiser_company_id],
- 'clicksLookback': '1',
- 'impressionsLookback': '1'
- }
-
- # Create a long-term activity group.
- long_term_activity_group = {
- 'name': 'Long-term activity group #%s' % uuid.uuid4(),
- 'companyIds': [advertiser_company_id],
- 'clicksLookback': '30',
- 'impressionsLookback': '30'
- }
-
- # Create the activity groups on the server.
- activity_groups = activity_group_service.createActivityGroups([
- short_term_activity_group, long_term_activity_group])
-
- # Display results.
- for activity_group in activity_groups:
- print ('Activity group with ID \'%s\' and name \'%s\' was created.'
- % (activity_group['id'], activity_group['name']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ADVERTISER_COMPANY_ID)
diff --git a/examples/dfp/v201408/activity_group_service/get_active_activity_groups.py b/examples/dfp/v201408/activity_group_service/get_active_activity_groups.py
deleted file mode 100755
index 81fcb5bf..00000000
--- a/examples/dfp/v201408/activity_group_service/get_active_activity_groups.py
+++ /dev/null
@@ -1,72 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all active activity groups.
-
-To create activity groups, run create_activity_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ActivityGroupService.getActivityGroupsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- activity_group_service = client.GetService('ActivityGroupService',
- version='v201408')
-
- # Create statement object to only select active activity groups.
- values = [{
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ACTIVE'
- }
- }]
- query = 'WHERE status = :status'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Get activity groups by statement.
- while True:
- response = activity_group_service.getActivityGroupsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for activity_group in response['results']:
- print ('Activity group with ID \'%s\' and name \'%s\' was found.'
- % (activity_group['id'], activity_group['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/activity_group_service/get_all_activity_groups.py b/examples/dfp/v201408/activity_group_service/get_all_activity_groups.py
deleted file mode 100755
index a4d34c55..00000000
--- a/examples/dfp/v201408/activity_group_service/get_all_activity_groups.py
+++ /dev/null
@@ -1,63 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all activity groups.
-
-To create activity groups, run create_activity_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ActivityGroupService.getActivityGroupsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- activity_group_service = client.GetService('ActivityGroupService',
- version='v201408')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get activity groups by statement.
- while True:
- response = activity_group_service.getActivityGroupsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for activity_group in response['results']:
- print ('Activity group with ID \'%s\' and name \'%s\' was found.'
- % (activity_group['id'], activity_group['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/activity_group_service/update_activity_groups.py b/examples/dfp/v201408/activity_group_service/update_activity_groups.py
deleted file mode 100755
index d1a065c8..00000000
--- a/examples/dfp/v201408/activity_group_service/update_activity_groups.py
+++ /dev/null
@@ -1,80 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates activity groups.
-
-To determine which activity groups exist, run get_all_activity_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ActivityGroupService.getActivityGroup
-Tags: ActivityGroupService.updateActivityGroups
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the activity group and the company to update it with.
-ACTIVITY_GROUP_ID = 'INSERT_ACTIVITY_GROUP_ID_HERE'
-ADVERTISER_COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
-
-
-def main(client, activity_group_id, advertiser_company_id):
- # Initialize appropriate service.
- activity_group_service = client.GetService('ActivityGroupService',
- version='v201408')
-
- # Create statement object to select a single activity groups by ID.
- values = [{
- 'key': 'activityGroupId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': activity_group_id
- }
- }]
- query = 'WHERE id = :activityGroupId'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get activity groups by statement.
- response = activity_group_service.getActivityGroupsByStatement(
- statement.ToStatement())
- if 'results' in response:
- updated_activity_groups = []
- for activity_group in response['results']:
- activity_group['companyIds'].append(advertiser_company_id)
- updated_activity_groups.append(activity_group)
- # Update the activity groups on the server.
- activity_groups = activity_group_service.updateActivityGroups(
- updated_activity_groups)
-
- for activity_group in activity_groups:
- print (('Activity group with ID \'%s\' and name \'%s\' was updated.')
- % (activity_group['id'], activity_group['name']))
- else:
- print 'No activity groups found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ACTIVITY_GROUP_ID, ADVERTISER_COMPANY_ID)
diff --git a/examples/dfp/v201408/activity_service/__init__.py b/examples/dfp/v201408/activity_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201408/activity_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201408/activity_service/create_activities.py b/examples/dfp/v201408/activity_service/create_activities.py
deleted file mode 100755
index 36783f82..00000000
--- a/examples/dfp/v201408/activity_service/create_activities.py
+++ /dev/null
@@ -1,71 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new activities.
-
-To determine which activities groups exist, run get_all_activities.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ActivityService.createActivities
-"""
-
-__author__ = ('Vincent Tsao',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the activity group this activity is associated with.
-ACTIVITY_GROUP_ID = 'INSERT_ACTIVITY_GROUP_ID_HERE'
-
-
-def main(client, activity_group_id):
- # Initialize appropriate service.
- activity_service = client.GetService('ActivityService', version='v201408')
-
- # Create a daily visits activity.
- daily_visits_activity = {
- 'name': 'Activity #%s' % uuid.uuid4(),
- 'activityGroupId': activity_group_id,
- 'type': 'DAILY_VISITS'
- }
-
- # Create a custom activity.
- custom_activity = {
- 'name': 'Activity #%s' % uuid.uuid4(),
- 'activityGroupId': activity_group_id,
- 'type': 'CUSTOM'
- }
-
- # Create the activities on the server.
- activities = activity_service.createActivities([
- daily_visits_activity, custom_activity])
-
- # Display results.
- for activity in activities:
- print ('An activity with ID \'%s\', name \'%s\', and type \'%s\' was '
- 'created.' % (activity['id'], activity['name'], activity['type']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ACTIVITY_GROUP_ID)
diff --git a/examples/dfp/v201408/activity_service/get_active_activities.py b/examples/dfp/v201408/activity_service/get_active_activities.py
deleted file mode 100755
index 19dc569c..00000000
--- a/examples/dfp/v201408/activity_service/get_active_activities.py
+++ /dev/null
@@ -1,69 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all active activities.
-
-To create activities, run create_activities.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ActivityService.getActivitiesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- activity_service = client.GetService('ActivityService', version='v201408')
-
- # Create statement object to only select active activities.
- values = [{
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ACTIVE'
- }
- }]
- query = 'WHERE status = :status'
- statement = dfp.FilterStatement(query, values)
-
- # Get activities by statement.
- while True:
- response = activity_service.getActivitiesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for activity in response['results']:
- print ('Activity with ID \'%s\', name \'%s\', and type \'%s\' was '
- 'found.' % (activity['id'], activity['name'], activity['type']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/activity_service/get_all_activities.py b/examples/dfp/v201408/activity_service/get_all_activities.py
deleted file mode 100755
index 9622e5a3..00000000
--- a/examples/dfp/v201408/activity_service/get_all_activities.py
+++ /dev/null
@@ -1,61 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all activities.
-
-To create activities, run create_activities.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ActivityService.getActivitiesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- activity_service = client.GetService('ActivityService', version='v201408')
-
- # Create statement object to select only all activities.
- statement = dfp.FilterStatement()
-
- # Get activities by statement.
- while True:
- response = activity_service.getActivitiesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for activity in response['results']:
- print ('Activity with ID \'%s\', name \'%s\', and type \'%s\' was '
- 'found.' % (activity['id'], activity['name'], activity['type']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/activity_service/update_activities.py b/examples/dfp/v201408/activity_service/update_activities.py
deleted file mode 100755
index 4db4254a..00000000
--- a/examples/dfp/v201408/activity_service/update_activities.py
+++ /dev/null
@@ -1,76 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates activities.
-
-To determine which activities exist, run get_all_activities.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ActivityService.updateActivities
- ActivityService.getActivitiesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the activity to update.
-ACTIVITY_ID = 'INSERT_ACTIVITY_ID_HERE'
-
-
-def main(client, activity_id):
- # Initialize appropriate service.
- activity_service = client.GetService('ActivityService', version='v201408')
-
- # Create statement object to select one activity by ID to update.
- values = [{
- 'key': 'activityId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': activity_id
- }
- }]
- query = 'WHERE id = :activityId'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get activities by statement.
- response = activity_service.getActivitiesByStatement(
- statement.ToStatement())
- if 'results' in response:
- updated_activities = []
- for activity in response['results']:
- # Update the expected URL.
- activity['expectedURL'] = 'https://google.com'
- updated_activities.append(activity)
- # Update the activity on the server.
- activities = activity_service.updateActivities(updated_activities)
-
- for updated_activity in activities:
- print (('Activity with ID \'%s\' and name \'%s\' was updated.')
- % (updated_activity['id'], updated_activity['name']))
- else:
- print 'No activities found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ACTIVITY_ID)
diff --git a/examples/dfp/v201408/audience_segment_service/__init__.py b/examples/dfp/v201408/audience_segment_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201408/audience_segment_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201408/audience_segment_service/create_audience_segments.py b/examples/dfp/v201408/audience_segment_service/create_audience_segments.py
deleted file mode 100755
index 547b6ff5..00000000
--- a/examples/dfp/v201408/audience_segment_service/create_audience_segments.py
+++ /dev/null
@@ -1,100 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates a new rule based first party audience segment."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the IDs of the custom criteria to be used in the segment rule.
-CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'
-CUSTOM_TARGETING_VALUE_ID = 'INSERT_CUSTOM_TARGETING_VALUE_ID_HERE'
-
-def main(client, custom_targeting_key_id, custom_targeting_value_id):
- # Initialize client object.
- client = dfp.DfpClient.LoadFromStorage()
-
- # Initialize appropriate services.
- audience_segment_service = client.GetService(
- 'AudienceSegmentService', version='v201408')
- network_service = client.GetService('NetworkService', version='v201408')
-
- # Get the root ad unit ID used to target the entire network.
- root_ad_unit_id = (
- network_service.getCurrentNetwork()['effectiveRootAdUnitId'])
-
- # Create inventory targeting (pointed at root ad unit i.e. the whole network)
- inventory_targeting = {
- 'targetedAdUnits': [
- {'adUnitId': root_ad_unit_id}
- ]
- }
-
- # Create custom criteria.
- custom_criteria = [
- {
- 'xsi_type': 'CustomCriteria',
- 'keyId': CUSTOM_TARGETING_KEY_ID,
- 'valueIds': [CUSTOM_TARGETING_VALUE_ID],
- 'operator': 'IS'
- }
- ]
-
- # Create the custom criteria set.
- top_custom_criteria_set = {
- 'logicalOperator': 'AND',
- 'children': custom_criteria
- }
-
- # Create the audience segment rule.
- rule = {
- 'inventoryRule': inventory_targeting,
- 'customCriteriaRule': top_custom_criteria_set
- }
-
- # Create an audience segment.
- audience_segment = [
- {
- 'xsi_type': 'RuleBasedFirstPartyAudienceSegment',
- 'name': ('Sports enthusiasts audience segment %s' %
- uuid.uuid4()),
- 'description': 'Sports enthusiasts between the ages of 20 and 30',
- 'pageViews': '6',
- 'recencyDays': '6',
- 'membershipExpirationDays': '88',
- 'rule': rule
- }
- ]
-
- audience_segments = (
- audience_segment_service.createAudienceSegments(audience_segment))
-
- for created_audience_segment in audience_segments:
- print ('An audience segment with ID \'%s\', name \'%s\', and type \'%s\' '
- 'was created.' % (created_audience_segment['id'],
- created_audience_segment['name'],
- created_audience_segment['type']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CUSTOM_TARGETING_KEY_ID, CUSTOM_TARGETING_VALUE_ID)
diff --git a/examples/dfp/v201408/audience_segment_service/get_all_audience_segments.py b/examples/dfp/v201408/audience_segment_service/get_all_audience_segments.py
deleted file mode 100755
index 81f37df6..00000000
--- a/examples/dfp/v201408/audience_segment_service/get_all_audience_segments.py
+++ /dev/null
@@ -1,60 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all audience segments.
-
-To create audience segments, run create_audience_segments.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize client object.
- client = dfp.DfpClient.LoadFromStorage()
-
- # Initialize appropriate service.
- audience_segment_service = client.GetService(
- 'AudienceSegmentService', version='v201408')
-
- # Create statement object to select all audience segments.
- statement = dfp.FilterStatement()
-
- # Get audience segments by statement.
- while True:
- response = audience_segment_service.getAudienceSegmentsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for segment in response['results']:
- print ('Audience segment with id \'%s\' and name '
- '\'%s\' of size %s was found.' %
- (segment['id'], segment['name'], segment['size']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/audience_segment_service/get_first_party_audience_segments.py b/examples/dfp/v201408/audience_segment_service/get_first_party_audience_segments.py
deleted file mode 100755
index d3fd3952..00000000
--- a/examples/dfp/v201408/audience_segment_service/get_first_party_audience_segments.py
+++ /dev/null
@@ -1,69 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all first party audience segments.
-
-To create first party audience segments, run create_audience_segments.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize client object.
- client = dfp.DfpClient.LoadFromStorage()
-
- # Initialize appropriate service.
- audience_segment_service = client.GetService(
- 'AudienceSegmentService', version='v201408')
-
- # Create statement object to only select first party audience segments.
- values = [{
- 'key': 'type',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'FIRST_PARTY'
- }
- }]
- query = 'WHERE Type = :type'
- statement = dfp.FilterStatement(query, values)
-
- # Get audience segments by statement.
- while True:
- response = audience_segment_service.getAudienceSegmentsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- segments = response['results']
- for segment in segments:
- print ('Audience segment with id \'%s\' and name \'%s\' of size '
- '%s was found. ' %
- (segment['id'], segment['name'], segment['size']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201408/audience_segment_service/populate_first_party_audience_segments.py
deleted file mode 100755
index f9115285..00000000
--- a/examples/dfp/v201408/audience_segment_service/populate_first_party_audience_segments.py
+++ /dev/null
@@ -1,84 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example populates a specific first party audience segment.
-
-To determine which first party audience segments exist, run
-get_first_party_audience_segments.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-AUDIENCE_SEGMENT_ID = 'INSERT_AUDIENCE_SEGMENT_ID_HERE'
-
-
-def main(client, audience_segment_id):
- # Initialize client object.
- client = dfp.DfpClient.LoadFromStorage()
-
- # Initialize appropriate service.
- audience_segment_service = client.GetService(
- 'AudienceSegmentService', version='v201408')
-
- # Create statement object to get the specified first party audience segment.
- values = (
- [{'key': 'type',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'FIRST_PARTY'
- }
- },
- {'key': 'audience_segment_id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': AUDIENCE_SEGMENT_ID
- }
- }])
- query = 'WHERE Type = :type AND Id = :audience_segment_id'
- statement = dfp.FilterStatement(query, values, 1)
-
- response = audience_segment_service.getAudienceSegmentsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- segments = response['results']
-
- for segment in segments:
- print ('Audience segment with id \'%s\' and name \'%s\' will be populated.'
- % (segment['id'], segment['name']))
-
- action = {
- 'xsi_type': 'PopulateAudienceSegments'
- }
-
- populated_audience_segments = (
- audience_segment_service.performAudienceSegmentAction(
- action, statement.ToStatement()))
-
- print ('%s audience segment populated' %
- populated_audience_segments['numChanges'])
- else:
- print 'No Results Found'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, AUDIENCE_SEGMENT_ID)
diff --git a/examples/dfp/v201408/audience_segment_service/update_audience_segments.py b/examples/dfp/v201408/audience_segment_service/update_audience_segments.py
deleted file mode 100755
index 0cbd7bc4..00000000
--- a/examples/dfp/v201408/audience_segment_service/update_audience_segments.py
+++ /dev/null
@@ -1,82 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates rule based first party audience segments.
-
-To determine which audience segments exist, run get_all_audience_segments.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-AUDIENCE_SEGMENT_ID = 'INSERT_AUDIENCE_SEGMENT_ID_HERE'
-
-
-def main(client, audience_segment_id):
- # Initialize client object.
- client = dfp.DfpClient.LoadFromStorage()
-
- # Initialize appropriate service.
- audience_segment_service = client.GetService(
- 'AudienceSegmentService', version='v201408')
-
- # Create statement object to get the specified first party audience segment.
- values = (
- [{'key': 'type',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'FIRST_PARTY'
- }
- },
- {'key': 'audience_segment_id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': AUDIENCE_SEGMENT_ID
- }
- }])
- query = 'WHERE Type = :type AND Id = :audience_segment_id'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get audience segments by statement.
- response = audience_segment_service.getAudienceSegmentsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- updated_audience_segments = []
- for audience_segment in response['results']:
- print ('Audience segment with id \'%s\' and name \'%s\' will be updated.'
- % (audience_segment['id'], audience_segment['name']))
-
- audience_segment['membershipExpirationDays'] = '180'
- updated_audience_segments.append(audience_segment)
-
- audience_segments = audience_segment_service.updateAudienceSegments(
- updated_audience_segments)
-
- for audience_segment in audience_segments:
- print ('Audience segment with id \'%s\' and name \'%s\' was updated' %
- (audience_segment['id'], audience_segment['name']))
- else:
- print 'No audience segment found to update.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, AUDIENCE_SEGMENT_ID)
diff --git a/examples/dfp/v201408/company_service/__init__.py b/examples/dfp/v201408/company_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201408/company_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201408/company_service/create_companies.py b/examples/dfp/v201408/company_service/create_companies.py
deleted file mode 100755
index ff233ef8..00000000
--- a/examples/dfp/v201408/company_service/create_companies.py
+++ /dev/null
@@ -1,65 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new companies.
-
-To determine which companies exist, run get_all_companies.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CompanyService.createCompanies
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- company_service = client.GetService('CompanyService', version='v201408')
-
- # Create company objects.
- companies = [
- {
- 'name': 'Advertiser #%s' % uuid.uuid4(),
- 'type': 'ADVERTISER'
- },
- {
- 'name': 'Agency #%s' % uuid.uuid4(),
- 'type': 'AGENCY'
- }
- ]
-
- # Add companies.
- companies = company_service.createCompanies(companies)
-
- # Display results.
- for company in companies:
- print ('Company with ID \'%s\', name \'%s\', and type \'%s\' was created.'
- % (company['id'], company['name'], company['type']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/company_service/get_advertisers.py b/examples/dfp/v201408/company_service/get_advertisers.py
deleted file mode 100755
index 7d359119..00000000
--- a/examples/dfp/v201408/company_service/get_advertisers.py
+++ /dev/null
@@ -1,69 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all companies that are advertisers.
-
-To create companies, run create_companies.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CompanyService.getCompaniesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- company_service = client.GetService('CompanyService', version='v201408')
-
- # Create statement object to only select companies that are advertisers.
- values = [{
- 'key': 'type',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ADVERTISER'
- }
- }]
- query = 'WHERE type = :type'
- statement = dfp.FilterStatement(query, values)
-
- # Get companies by statement.
- while True:
- response = company_service.getCompaniesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for company in response['results']:
- print ('Company with ID \'%s\', name \'%s\', and type \'%s\' was found.'
- % (company['id'], company['name'], company['type']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/company_service/get_all_companies.py b/examples/dfp/v201408/company_service/get_all_companies.py
deleted file mode 100755
index e5b4f560..00000000
--- a/examples/dfp/v201408/company_service/get_all_companies.py
+++ /dev/null
@@ -1,61 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all companies.
-
-To create companies, run create_companies.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CompanyService.getCompaniesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- company_service = client.GetService('CompanyService', version='v201408')
-
- # Create statement object to select all companies.
- statement = dfp.FilterStatement()
-
- # Get companies by statement.
- while True:
- response = company_service.getCompaniesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for company in response['results']:
- print ('Company with ID \'%s\', name \'%s\', and type \'%s\' was found.'
- % (company['id'], company['name'], company['type']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/company_service/update_companies.py b/examples/dfp/v201408/company_service/update_companies.py
deleted file mode 100755
index fb986270..00000000
--- a/examples/dfp/v201408/company_service/update_companies.py
+++ /dev/null
@@ -1,77 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates company comments.
-
-To determine which companies exist, run get_all_companies.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CompanyService.updateCompanies
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the company to update.
-COMPANY_ID = 'INSERT_COMPANY_ID_HERE'
-
-
-def main(client, company_id):
- # Initialize appropriate service.
- company_service = client.GetService('CompanyService', version='v201408')
-
- # Create statement object to only select a single company by ID.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': company_id
- }
- }]
- query = 'WHERE id = :id'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get companies by statement.
- response = company_service.getCompaniesByStatement(
- statement.ToStatement())
- if 'results' in response:
- updated_companies = []
- for company in response['results']:
- company['comment'] += ' Updated.'
- updated_companies.append(company)
-
- # Update the companies on the server.
- companies = company_service.updateCompanies(updated_companies)
-
- # Display results.
- for company in companies:
- print (('Company with ID \'%s\', name \'%s\', and comment \'%s\''
- 'was updated.')
- % (company['id'], company['name'], company['comment']))
- else:
- print 'No companies found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, COMPANY_ID)
diff --git a/examples/dfp/v201408/contact_service/__init__.py b/examples/dfp/v201408/contact_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201408/contact_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201408/contact_service/create_contacts.py b/examples/dfp/v201408/contact_service/create_contacts.py
deleted file mode 100755
index b453eae9..00000000
--- a/examples/dfp/v201408/contact_service/create_contacts.py
+++ /dev/null
@@ -1,74 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new contacts.
-
-To determine which contacts exist, run get_all_contacts.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContactService.createContacts
-"""
-
-__author__ = ('Vincent Tsao',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the advertiser company this contact is associated with.
-ADVERTISER_COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
-
-# Set the ID of the agency company this contact is associated with.
-AGENCY_COMPANY_ID = 'INSERT_AGENCY_COMPANY_ID_HERE'
-
-
-def main(client, advertiser_company_id, agency_company_id):
- # Initialize appropriate service.
- contact_service = client.GetService('ContactService', version='v201408')
-
- # Create an advertiser contact.
- advertiser_contact = {
- 'name': 'Mr. Advertiser #%s' % uuid.uuid4(),
- 'email': 'advertiser@advertising.com',
- 'companyId': advertiser_company_id
- }
-
- # Create an agency contact.
- agency_contact = {
- 'name': 'Ms. Agency #%s' % uuid.uuid4(),
- 'email': 'agency@agencies.com',
- 'companyId': agency_company_id
- }
-
- # Create the contacts on the server.
- contacts = contact_service.createContacts([advertiser_contact,
- agency_contact])
-
- # Display results.
- for contact in contacts:
- print ('Contact with ID \'%s\' name \'%s\' was created.'
- % (contact['id'], contact['name']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ADVERTISER_COMPANY_ID, AGENCY_COMPANY_ID)
diff --git a/examples/dfp/v201408/contact_service/get_all_contacts.py b/examples/dfp/v201408/contact_service/get_all_contacts.py
deleted file mode 100755
index d258a5f0..00000000
--- a/examples/dfp/v201408/contact_service/get_all_contacts.py
+++ /dev/null
@@ -1,61 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all contacts.
-
-To create contacts, run create_contacts.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContactService.getContactsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- contact_service = client.GetService('ContactService', version='v201408')
-
- # Create statement object to get all contacts.
- statement = dfp.FilterStatement()
-
- # Get contacts by statement.
- while True:
- response = contact_service.getContactsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for contact in response['results']:
- print ('Contact with ID \'%s\' and name \'%s\' was found.'
- % (contact['id'], contact['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/contact_service/get_uninvited_contacts.py b/examples/dfp/v201408/contact_service/get_uninvited_contacts.py
deleted file mode 100755
index 42765bff..00000000
--- a/examples/dfp/v201408/contact_service/get_uninvited_contacts.py
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all contacts that aren't invited yet.
-
-To create contacts, run create_contacts.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContactService.getContactsByStatement
-"""
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- contact_service = client.GetService('ContactService', version='v201408')
-
- # Create statement object to only select contacts that are uninvited.
- values = [{
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'UNINVITED'
- }
- }]
- query = 'WHERE status = :status'
- statement = dfp.FilterStatement(query, values)
-
- # Get contacts by statement.
- while True:
- response = contact_service.getContactsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for contact in response['results']:
- print ('Contact with ID \'%s\' and name \'%s\' was found.'
- % (contact['id'], contact['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/contact_service/update_contacts.py b/examples/dfp/v201408/contact_service/update_contacts.py
deleted file mode 100755
index 9d6adea4..00000000
--- a/examples/dfp/v201408/contact_service/update_contacts.py
+++ /dev/null
@@ -1,79 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates contact addresses.
-
-To determine which contacts exist, run get_all_contacts.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContactService.updateContacts
- ContactService.getContactsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the contact to update.
-CONTACT_ID = 'INSERT_CONTACT_ID_HERE'
-
-
-def main(client, contact_id):
- # Initialize appropriate service.
- contact_service = client.GetService('ContactService', version='v201408')
-
- # Create statement object to select the single contact by ID.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': contact_id
- }
- }]
- query = 'WHERE id = :id'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get contacts by statement.
- response = contact_service.getContactsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- updated_contacts = []
- for contact in response['results']:
- contact['address'] = '123 New Street, New York, NY, 10011'
- updated_contacts.append(contact)
-
- # Update the contact on the server.
- contacts = contact_service.updateContacts(updated_contacts)
-
- # Display results.
- for contact in contacts:
- print (('Contact with ID \'%s\', name \'%s\', and address \'%s\' '
- 'was updated.')
- % (contact['id'], contact['name'], contact['address']))
- else:
- print 'No contacts found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CONTACT_ID)
diff --git a/examples/dfp/v201408/content_metadata_key_hierarchy_service/__init__.py b/examples/dfp/v201408/content_metadata_key_hierarchy_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201408/content_metadata_key_hierarchy_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201408/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/dfp/v201408/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py
deleted file mode 100755
index 31864b23..00000000
--- a/examples/dfp/v201408/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py
+++ /dev/null
@@ -1,81 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new content metadata key hierarchies.
-
-To determine which content metadata key hierarchies exist, run
-get_all_content_metadata_key_hierarchies.py.
-
-This feature is only available to DFP video publishers.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContentMetadataKeyHierarchyService.createContentMetadataKeyHierarchies
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the IDs of the custom targeting keys for the hierarchy.
-HIERARCHY_LEVEL_ONE_KEY_ID = 'INSERT_LEVEL_ONE_CUSTOM_TARGETING_KEY_ID_HERE'
-HIERARCHY_LEVEL_TWO_KEY_ID = 'INSERT_LEVEL_TWO_CUSTOM_TARGETING_KEY_ID_HERE'
-
-
-def main(client, hierarchy_level_one_key_id, hierarchy_level_two_key_id):
- # Initialize appropriate service.
- content_metadata_key_hierarchy_service = client.GetService(
- 'ContentMetadataKeyHierarchyService', version='v201408')
-
- hierarchy_level_1 = {
- 'customTargetingKeyId': hierarchy_level_one_key_id,
- 'hierarchyLevel': '1'
- }
-
- hierarchy_level_2 = {
- 'customTargetingKeyId': hierarchy_level_two_key_id,
- 'hierarchyLevel': '2'
- }
-
- hierarchy_levels = [hierarchy_level_1, hierarchy_level_2]
-
- # Create content metadata key hierarchy object.
- content_metadata_key_hierarchy = {
- 'name': 'Content Metadata Key Hierarchy #%s' % uuid.uuid4(),
- 'hierarchyLevels': hierarchy_levels
- }
-
- content_metadata_key_hierarchies = (
- content_metadata_key_hierarchy_service
- .createContentMetadataKeyHierarchies([content_metadata_key_hierarchy]))
-
- # Display results.
- for content_metadata_key_hierarchy in content_metadata_key_hierarchies:
- print ('Content metadata key hierarchy with id \'%s\' and name \'%s\''
- ' was created.' % (content_metadata_key_hierarchy['id'],
- content_metadata_key_hierarchy['name']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, HIERARCHY_LEVEL_ONE_KEY_ID, HIERARCHY_LEVEL_TWO_KEY_ID)
diff --git a/examples/dfp/v201408/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py b/examples/dfp/v201408/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py
deleted file mode 100755
index 171915fb..00000000
--- a/examples/dfp/v201408/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py
+++ /dev/null
@@ -1,88 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example deletes content metadata key hierarchies.
-
-To determine which content metadata key hierarchies exist, run
-get_all_content_metadata_key_hierarchies.py.
-
-This feature is only available to DFP video publishers.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContentMetadataKeyHierarchyService.getContentMetadataKeyHierarchiesByStatement
- ContentMetadataKeyHierarchyService.perfomContentMetadataKeyHierarchyAction
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the content metadata key hierarchy to delete.
-CONTENT_METADATA_KEY_HIERARCHY_ID = (
- 'INSERT_CONTENT_METADATA_KEY_HIERARCHY_ID_HERE')
-
-
-def main(client, content_metadata_key_hierarchy_id):
- # Initialize appropriate service.
- content_metadata_key_hierarchy_service = client.GetService(
- 'ContentMetadataKeyHierarchyService', version='v201408')
-
- # Create a query to select a single content metadata key hierarchy.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': content_metadata_key_hierarchy_id
- }
- }]
-
- query = 'WHERE id = :id ORDER BY id ASC'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get a single content metadata key hierarchy by statement.
- response = (content_metadata_key_hierarchy_service
- .getContentMetadataKeyHierarchiesByStatement(
- statement.ToStatement())[0])
- content_metadata_key_hierarchies = (response['results']
- if 'results' in response else None)
-
- # Display results.
- if content_metadata_key_hierarchies:
- for content_metadata_key_hierarchy in content_metadata_key_hierarchies:
- print ('Content metadata key hierarchy with ID \'%s\' and name \'%s\' '
- 'will be deleted.' % (content_metadata_key_hierarchy['id'],
- content_metadata_key_hierarchy['name']))
-
- # Perform action.
- result = (content_metadata_key_hierarchy_service
- .performContentMetadataKeyHierarchyAction(
- {'type': 'DeleteContentMetadataKeyHierarchies'},
- statement.ToStatement()))[0]
-
- # Display results.
- print ('Number of content metadata key hierarchies deleted: %s' %
- result['numChanges'])
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CONTENT_METADATA_KEY_HIERARCHY_ID)
diff --git a/examples/dfp/v201408/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/dfp/v201408/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py
deleted file mode 100755
index 09dbd412..00000000
--- a/examples/dfp/v201408/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py
+++ /dev/null
@@ -1,66 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all content metadata key hierarchies.
-
-This feature is only available to DFP video publishers.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContentMetadataKeyHierarchyService.getContentMetadataKeyHierarchiesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- content_metadata_key_hierarchy_service = client.GetService(
- 'ContentMetadataKeyHierarchyService', version='v201408')
-
- # Create statement object to select all content.
- statement = dfp.FilterStatement()
-
- # Get content by statement.
- while True:
- response = (content_metadata_key_hierarchy_service
- .getContentMetadataKeyHierarchiesByStatement(
- statement.ToStatement())[0])
- content_metadata_key_hierarchies = (response['results']
- if 'results' in response else None)
- if content_metadata_key_hierarchies:
- # Display results.
- for content_metadata_key_hierarchy in content_metadata_key_hierarchies:
- print ('Content metadata key hierarchyy with id \'%s\' and name \'%s\''
- ' was found.' % (content_metadata_key_hierarchy['id'],
- content_metadata_key_hierarchy['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/dfp/v201408/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py
deleted file mode 100755
index 17bdab6f..00000000
--- a/examples/dfp/v201408/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py
+++ /dev/null
@@ -1,100 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates content metadata key hierarchies.
-
-To determine which content metadata key hierarchies exist, run
-get_all_content_metadata_key_hierarchies.py.
-
-This feature is only available to DFP video publishers.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContentMetadataKeyHierarchyService.getContentMetadataKeyHierarchiesByStatement
- ContentMetadataKeyHierarchyService.updateContentMetadataKeyHierarchies
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the content metadata key hierarchy to update.
-CONTENT_METADATA_KEY_HIERARCHY_ID = (
- 'INSERT_CONTENT_METADATA_KEY_HIERARCHY_ID_HERE')
-# Set the ID of the custom targeting key to be added as a hierarchy level.
-CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'
-
-
-def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id):
- # Initialize appropriate service.
- content_metadata_key_hierarchy_service = client.GetService(
- 'ContentMetadataKeyHierarchyService', version='v201408')
-
- # Create a query to select a single content metadata key hierarchy.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': content_metadata_key_hierarchy_id
- }
- }]
-
- query = 'WHERE id = :id ORDER BY id ASC'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get a single content metadata key hierarchy by statement.
- response = (content_metadata_key_hierarchy_service
- .getContentMetadataKeyHierarchiesByStatement(
- statement.ToStatement()))[0]
- content_metadata_key_hierarchies = (response['results']
- if 'results' in response else None)
-
- if content_metadata_key_hierarchies:
- content_metadata_key_hierarchy = content_metadata_key_hierarchies[0]
-
- # Update the content metadata key hierarchy by adding a hierarchy level.
- hierarchy_levels = content_metadata_key_hierarchy['hierarchyLevels']
-
- hierarchy_level = {
- 'customTargetingKeyId': custom_targeting_key_id,
- 'hierarchyLevel': str(len(hierarchy_levels) + 1)
- }
-
- content_metadata_key_hierarchy['hierarchyLevels'] = (
- hierarchy_levels.append(hierarchy_level))
-
- content_metadata_key_hierarchies = (
- content_metadata_key_hierarchy_service
- .updateContentMetadataKeyHierarchies(content_metadata_key_hierarchies))
-
- # Display results.
- for content_metadata_key_hierarchy in content_metadata_key_hierarchies:
- print ('Content metadata key hierarchy with id \'%s\' and name \'%s\''
- ' was updated.' % (content_metadata_key_hierarchy['id'],
- content_metadata_key_hierarchy['name']))
-
- else:
- print 'No content metadata key hierarchies were found'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CONTENT_METADATA_KEY_HIERARCHY_ID, CUSTOM_TARGETING_KEY_ID)
diff --git a/examples/dfp/v201408/content_service/__init__.py b/examples/dfp/v201408/content_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201408/content_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201408/content_service/get_all_content.py b/examples/dfp/v201408/content_service/get_all_content.py
deleted file mode 100755
index 589a8c78..00000000
--- a/examples/dfp/v201408/content_service/get_all_content.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all content.
-
-This feature is only available to DFP video publishers.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContentService.getContentByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- content_service = client.GetService('ContentService', version='v201408')
-
- # Create statement object to select all content.
- statement = dfp.FilterStatement()
-
- # Get content by statement.
- while True:
- response = content_service.getContentByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for content_item in response['results']:
- print ('Content with id \'%s\', name \'%s\', and status \'%s\' was '
- 'found.' % (content_item['id'], content_item['name'],
- content_item['status']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/content_service/get_content_by_category.py b/examples/dfp/v201408/content_service/get_content_by_category.py
deleted file mode 100755
index fb8beb68..00000000
--- a/examples/dfp/v201408/content_service/get_content_by_category.py
+++ /dev/null
@@ -1,112 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all active content categorized as a "comedy" using the
-network's content browse custom targeting key.
-
-This feature is only available to DFP video publishers.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContentService.getContentByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- content_service = client.GetService('ContentService', version='v201408')
- network_service = client.GetService('NetworkService', version='v201408')
- custom_targeting_service = client.GetService(
- 'CustomTargetingService', version='v201408')
-
- # Get the network's content browse custom targeting key.
- network = network_service.getCurrentNetwork()
- key_id = network['contentBrowseCustomTargetingKeyId']
-
- # Create a statement to select the categories matching the name comedy.
- values = [
- {
- 'key': 'contentBrowseCustomTargetingKeyId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': key_id
- }
- },
- {
- 'key': 'category',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'comedy'
- }
- }
- ]
- category_filter_query = ('WHERE customTargetingKeyId = '
- ':contentBrowseCustomTargetingKeyId and name = '
- ':category')
- category_filter_statement = dfp.FilterStatement(
- category_filter_query, values, 1)
-
- # Get categories matching the filter statement.
- response = custom_targeting_service.getCustomTargetingValuesByStatement(
- category_filter_statement.ToStatement())
-
- # Get the custom targeting value ID for the comedy category.
- if 'results' in response:
- category_custom_targeting_value_id = (response['results']['id'])
-
- # Create a statement to select the active content.
- content_values = [
- {
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ACTIVE'
- }
- }
- ]
- content_query = 'WHERE status = :status'
- content_statement = dfp.FilterStatement(content_query, content_values)
-
- while True:
- # Get the content by statement and custom targeting value.
- response = content_service.getContentByStatementAndCustomTargetingValue(
- content_statement.ToStatement(),
- category_custom_targeting_value_id)
- if 'results' in response:
- # Display results.
- for content_item in response['results']:
- print ('Content with id \'%s\', name \'%s\', and status \'%s\' was '
- 'found.' % (content_item['id'], content_item['name'],
- content_item['status']))
- content_statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/creative_service/__init__.py b/examples/dfp/v201408/creative_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201408/creative_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201408/creative_service/create_creative_from_template.py b/examples/dfp/v201408/creative_service/create_creative_from_template.py
deleted file mode 100755
index b340d78a..00000000
--- a/examples/dfp/v201408/creative_service/create_creative_from_template.py
+++ /dev/null
@@ -1,104 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates a new template creative for a given advertiser.
-
-To determine which companies are advertisers, run get_advertisers.py.
-To determine which creative templates exist, run
-get_all_creative_templates.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeService.createCreative
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import base64
-import os
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set id of the advertiser (company) that the creative will be assigned to.
-ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
-
-
-def main(client, advertiser_id):
- # Initialize appropriate service.
- creative_service = client.GetService('CreativeService', version='v201408')
-
- # Use the image banner with optional third party tracking template.
- creative_template_id = '10000680'
-
- image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data',
- 'medium_rectangle.jpg'), 'r').read()
- image_data = base64.encodestring(image_data)
- # Create creative from templates.
- creative = {
- 'xsi_type': 'TemplateCreative',
- 'name': 'Template Creative #%s' % uuid.uuid4(),
- 'advertiserId': advertiser_id,
- 'size': {'width': '300', 'height': '250'},
- 'creativeTemplateId': creative_template_id,
- 'creativeTemplateVariableValues': [
- {
- 'xsi_type': 'AssetCreativeTemplateVariableValue',
- 'uniqueName': 'Imagefile',
- 'assetByteArray': image_data,
- 'fileName': 'image%s.jpg' % uuid.uuid4()
- },
- {
- 'xsi_type': 'LongCreativeTemplateVariableValue',
- 'uniqueName': 'Imagewidth',
- 'value': '300'
- },
- {
- 'xsi_type': 'LongCreativeTemplateVariableValue',
- 'uniqueName': 'Imageheight',
- 'value': '250'
- },
- {
- 'xsi_type': 'UrlCreativeTemplateVariableValue',
- 'uniqueName': 'ClickthroughURL',
- 'value': 'www.google.com'
- },
- {
- 'xsi_type': 'StringCreativeTemplateVariableValue',
- 'uniqueName': 'Targetwindow',
- 'value': '_blank'
- }
- ]
- }
-
- # Call service to create the creative.
- creative = creative_service.createCreative(creative)
-
- # Display results.
- print ('Template creative with id \'%s\', name \'%s\', and type \'%s\' was '
- 'created and can be previewed at %s.'
- % (creative['id'], creative['name'], creative['Creative.Type'],
- creative['previewUrl']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ADVERTISER_ID)
diff --git a/examples/dfp/v201408/creative_service/create_creatives.py b/examples/dfp/v201408/creative_service/create_creatives.py
deleted file mode 100755
index e0cbc5ee..00000000
--- a/examples/dfp/v201408/creative_service/create_creatives.py
+++ /dev/null
@@ -1,94 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new image creatives for a given advertiser.
-
-To determine which companies are advertisers, run get_advertisers.py.
-To determine which creatives already exist, run get_all_creatives.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeService.createCreatives
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import base64
-import os
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set id of the advertiser (company) that all creatives will be assigned to.
-ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
-
-
-def main(client, advertiser_id):
- # Initialize appropriate service.
- creative_service = client.GetService('CreativeService', version='v201408')
-
- # Create creative objects.
- creatives = []
- with open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data',
- 'medium_rectangle.jpg'), 'r') as image:
- image_data = base64.encodestring(image.read())
-
- for i in xrange(5):
- # Create creative size.
- size = {
- 'width': '300',
- 'height': '250'
- }
-
- # Create image asset.
- creative_asset = {
- 'xsi_type': 'CreativeAsset',
- 'fileName': 'image.jpg',
- 'assetByteArray': image_data,
- 'size': size
- }
-
- # Create an image creative.
- creative = {
- 'xsi_type': 'ImageCreative',
- 'name': 'Image Creative #%s' % uuid.uuid4(),
- 'advertiserId': advertiser_id,
- 'destinationUrl': 'http://google.com',
- 'size': size,
- 'primaryImageAsset': creative_asset
- }
-
- creatives.append(creative)
-
- # Add creatives.
- creatives = creative_service.createCreatives(creatives)
-
- # Display results.
- for creative in creatives:
- print ('Image creative with id \'%s\', name \'%s\', and type \'%s\' was '
- 'created and can be previewed at %s.'
- % (creative['id'], creative['name'], creative['Creative.Type'],
- creative['previewUrl']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ADVERTISER_ID)
diff --git a/examples/dfp/v201408/creative_service/create_custom_creative.py b/examples/dfp/v201408/creative_service/create_custom_creative.py
deleted file mode 100755
index 2ac6f38f..00000000
--- a/examples/dfp/v201408/creative_service/create_custom_creative.py
+++ /dev/null
@@ -1,90 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates a custom creative for a given advertiser.
-
-This feature is only available to DFP premium solution networks. To determine
-which companies are advertisers, run get_advertisers.py. To determine
-which creative templates exist, run get_all_creative_templates.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeService.createCreative
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import base64
-import os
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set id of the advertiser (company) that the creative will be assigned to.
-ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
-
-
-def main(client, advertiser_id):
- # Initialize appropriate service.
- creative_service = client.GetService('CreativeService', version='v201408')
-
- # Get the image data for the creative.
- image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data',
- 'medium_rectangle.jpg'), 'r').read()
- image_data = base64.encodestring(image_data)
-
- # Create the HTML snippet used in the custom creative.
- html_snippet = (' Click above for '
- 'great deals!') % ('%%CLICK_URL_UNESC%%', '%%DEST_URL%%',
- '%%FILE:IMAGE_ASSET%%')
-
- # Create custom creative.
- creative = {
- 'xsi_type': 'CustomCreative',
- 'name': 'Custom Creative #%s' % uuid.uuid4(),
- 'advertiserId': advertiser_id,
- 'size': {'width': '300', 'height': '250'},
- 'destinationUrl': 'http://google.com',
- 'customCreativeAssets': [
- {
- 'xsi_type': 'CustomCreativeAsset',
- 'macroName': 'IMAGE_ASSET',
- 'assetByteArray': image_data,
- 'fileName': 'image%s.jpg' % uuid.uuid4()
- }
- ],
- 'htmlSnippet': html_snippet
- }
-
- # Call service to create the creative.
- creative = creative_service.createCreative(creative)
-
- # Display results.
- if creative:
- print ('Template creative with id \'%s\', name \'%s\', and type \'%s\' was '
- 'created and can be previewed at %s.'
- % (creative['id'], creative['name'], creative['Creative.Type'],
- creative['previewUrl']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ADVERTISER_ID)
diff --git a/examples/dfp/v201408/creative_service/get_all_creatives.py b/examples/dfp/v201408/creative_service/get_all_creatives.py
deleted file mode 100755
index 40c2eecf..00000000
--- a/examples/dfp/v201408/creative_service/get_all_creatives.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all creatives.
-
-To create creatives, run create_creatives.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeService.getCreativesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- creative_service = client.GetService('CreativeService', version='v201408')
-
- # Create statement object to select all creatives.
- statement = dfp.FilterStatement()
-
- # Get creatives by statement.
- while True:
- response = creative_service.getCreativesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for creative in response['results']:
- print ('Creative with id \'%s\', name \'%s\', and type \'%s\' was '
- 'found.' % (creative['id'], creative['name'],
- creative['Creative.Type']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/creative_service/get_creatives_by_statement.py b/examples/dfp/v201408/creative_service/get_creatives_by_statement.py
deleted file mode 100755
index 8f7eeb90..00000000
--- a/examples/dfp/v201408/creative_service/get_creatives_by_statement.py
+++ /dev/null
@@ -1,72 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all image creatives.
-
-To create an image creative, run create_creatives.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeService.getCreativesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- creative_service = client.GetService('CreativeService', version='v201408')
-
- # Create statement object to only select image creatives.
- values = [{
- 'key': 'creativeType',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ImageCreative'
- }
- }]
- query = 'WHERE creativeType = :creativeType'
- statement = dfp.FilterStatement(query, values)
-
- # Get creatives by statement.
- while True:
- response = creative_service.getCreativesByStatement(
- statement.ToStatement())
- creatives = response['results']
-
- if creatives:
- # Display results.
- for creative in creatives:
- print ('Creative with id \'%s\', name \'%s\', and type \'%s\' was '
- 'found.' % (creative['id'], creative['name'],
- creative['Creative.Type']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/creative_service/update_creatives.py b/examples/dfp/v201408/creative_service/update_creatives.py
deleted file mode 100755
index 66d44519..00000000
--- a/examples/dfp/v201408/creative_service/update_creatives.py
+++ /dev/null
@@ -1,84 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates the destination URL of a single image creative.
-
-To determine which image creatives exist, run get_all_creatives.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeService.updateCreatives
- CreativeService.getCreativesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-IMAGE_CREATIVE_ID = 'INSERT_IMAGE_CREATIVE_ID_HERE'
-
-
-def main(client, image_creative_id):
- # Initialize appropriate service.
- creative_service = client.GetService('CreativeService', version='v201408')
-
- # Create statement object to get all image creatives.
- values = [{
- 'key': 'type',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ImageCreative'
- }
- }, {
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': image_creative_id
- }
- }]
- query = 'WHERE creativeType = :type AND id = :id'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get creatives by statement.
- response = creative_service.getCreativesByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- # Update each local creative object by changing its destination URL.
- updated_creatives = []
- for creative in response['results']:
- creative['destinationUrl'] = 'http://news.google.com'
- updated_creatives.append(creative)
-
- # Update creatives remotely.
- creatives = creative_service.updateCreatives(updated_creatives)
-
- # Display results.
- for creative in creatives:
- print ('Image creative with id \'%s\' and destination URL \'%s\' was '
- 'updated.' % (creative['id'], creative['destinationUrl']))
- else:
- print 'No creatives found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, IMAGE_CREATIVE_ID)
diff --git a/examples/dfp/v201408/creative_set_service/__init__.py b/examples/dfp/v201408/creative_set_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201408/creative_set_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201408/creative_set_service/associate_creative_set_to_line_item.py b/examples/dfp/v201408/creative_set_service/associate_creative_set_to_line_item.py
deleted file mode 100755
index 1a518581..00000000
--- a/examples/dfp/v201408/creative_set_service/associate_creative_set_to_line_item.py
+++ /dev/null
@@ -1,59 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates a line item creative association for a creative
-set.
-
-To create creative sets, run create_creative_set.py. To create creatives, run
-create_creatives.py. To determine which LICAs exist, run get_all_licas.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: LineItemCreativeAssociationService.createLineItemCreativeAssociations
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-CREATIVE_SET_ID = 'INSERT_CREATIVE_SET_ID_HERE'
-LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
-
-
-def main(client, creative_set_id, line_item_id):
- # Initialize appropriate service.
- lica_service = client.GetService(
- 'LineItemCreativeAssociationService', version='v201408')
-
- # Create LICA for a creative set.
- lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id}
-
- # Add LICA.
- lica = lica_service.createLineItemCreativeAssociations([lica])
-
- # Display results.
- print (('LICA with line item ID \'%s\' and creative set ID \'%s\' was '
- 'created.') % (lica['lineItemId'], lica['creativeSetId']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CREATIVE_SET_ID, LINE_ITEM_ID)
diff --git a/examples/dfp/v201408/creative_set_service/create_creative_set.py b/examples/dfp/v201408/creative_set_service/create_creative_set.py
deleted file mode 100755
index 9ece07f8..00000000
--- a/examples/dfp/v201408/creative_set_service/create_creative_set.py
+++ /dev/null
@@ -1,64 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new creative sets.
-
-To determine which creative sets exist, run get_all_creative_sets.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeSetService.createCreativeSet
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-MASTER_CREATIVE_ID = 'INSERT_MASTER_CREATIVE_ID_HERE'
-COMPANION_CREATIVE_ID = 'INSERT_COMPANION_CREATIVE_ID_HERE'
-
-
-def main(client, master_creative_id, companion_creative_id):
- # Initialize appropriate service.
- creative_set_service = client.GetService('CreativeSetService',
- version='v201408')
-
- # Create creative set objects.
- creative_set = {'name': 'Creative set #%s' % uuid.uuid4(),
- 'masterCreativeId': master_creative_id,
- 'companionCreativeIds': [companion_creative_id]}
-
- # Add creative sets.
- creative_set = creative_set_service.createCreativeSet(creative_set)
-
- # Display results.
- if creative_set:
- print (('Creative set with ID \'%s\', master creative ID \'%s\', and '
- 'companion creative IDs {%s} was created.')
- % (creative_set['id'], creative_set['masterCreativeId'],
- ','.join(creative_set['companionCreativeIds'])))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, MASTER_CREATIVE_ID, COMPANION_CREATIVE_ID)
diff --git a/examples/dfp/v201408/creative_set_service/get_all_creative_sets.py b/examples/dfp/v201408/creative_set_service/get_all_creative_sets.py
deleted file mode 100755
index 701e9c98..00000000
--- a/examples/dfp/v201408/creative_set_service/get_all_creative_sets.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all creative sets.
-
-To create creative sets, run create_creative_sets.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeSetService.getCreativeSetsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- creative_set_service = client.GetService('CreativeSetService',
- version='v201408')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get creative sets by statement.
- while True:
- response = creative_set_service.getCreativeSetsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for creative_set in response['results']:
- print ('Creative set with ID \'%s\' and name \'%s\' was found.'
- % (creative_set['id'], creative_set['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/creative_set_service/get_creative_sets_by_statement.py b/examples/dfp/v201408/creative_set_service/get_creative_sets_by_statement.py
deleted file mode 100755
index 5c668485..00000000
--- a/examples/dfp/v201408/creative_set_service/get_creative_sets_by_statement.py
+++ /dev/null
@@ -1,75 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all creative sets for a master creative.
-
-To create creative sets, run create_creative_sets.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeSetService.getCreativeSetsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-MASTER_CREATIVE_ID = 'INSERT_MASTER_CREATIVE_ID_HERE'
-
-
-def main(client, master_creative_id):
- # Initialize appropriate service.
- creative_set_service = client.GetService('CreativeSetService',
- version='v201408')
-
- # Create statement object to only select creative sets that have the given
- # master creative.
- values = [{
- 'key': 'masterCreativeId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': master_creative_id
- }
- }]
- query = 'WHERE masterCreativeId = :masterCreativeId'
- statement = dfp.FilterStatement(query, values)
-
- # Get creative sets by statement.
- while True:
- response = creative_set_service.getCreativeSetsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for creative_set in response['results']:
- print (('Creative set with ID \'%s\', master creative ID \'%s\', and '
- 'companion creative IDs {%s} was found.')
- % (creative_set['id'], creative_set['masterCreativeId'],
- ','.join(creative_set['companionCreativeIds'])))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, MASTER_CREATIVE_ID)
diff --git a/examples/dfp/v201408/creative_set_service/update_creative_set.py b/examples/dfp/v201408/creative_set_service/update_creative_set.py
deleted file mode 100755
index 963213d2..00000000
--- a/examples/dfp/v201408/creative_set_service/update_creative_set.py
+++ /dev/null
@@ -1,82 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates a creative set by adding a companion creative.
-
-To determine which creative sets exist, run get_all_creative_sets.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeSetService.updateCreativeSet
- CreativeSetService.getCreativeSetsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the creative set to update.
-CREATIVE_SET_ID = 'INSERT_CREATIVE_SET_ID_HERE'
-COMPANION_CREATIVE_ID = 'INSERT_COMPANION_CREATIVE_ID_HERE'
-
-
-def main(client, creative_set_id, companion_creative_id):
- # Initialize appropriate service.
- creative_set_service = client.GetService('CreativeSetService',
- version='v201408')
-
- # Create statement to select a single creative set by ID.
- values = [{
- 'key': 'creativeSetId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': creative_set_id
- }
- }]
- query = 'WHERE id = :creativeSetId'
- statement = dfp.FilterStatement(query, values)
-
- # Get creative set.
- response = creative_set_service.getCreativeSetsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- updated_created_sets = []
- for creative_set in response['results']:
- creative_set['companionCreativeIds'].append(companion_creative_id)
- updated_created_sets.append(creative_set)
-
- # Update the creative sets on the server.
- creative_sets = creative_set_service.updateCreativeSet(updated_created_sets)
-
- # Display results.
- for creative_set in creative_sets:
- print (('Creative set with ID \'%s\', master creative ID \'%s\', and '
- 'companion creative IDs {%s} was updated.')
- % (creative_set['id'], creative_set['masterCreativeId'],
- ','.join(creative_set['companionCreativeIds'])))
- else:
- print 'No creative sets found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CREATIVE_SET_ID, COMPANION_CREATIVE_ID)
diff --git a/examples/dfp/v201408/creative_template_service/__init__.py b/examples/dfp/v201408/creative_template_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201408/creative_template_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201408/creative_template_service/get_all_creative_templates.py b/examples/dfp/v201408/creative_template_service/get_all_creative_templates.py
deleted file mode 100755
index dc055d22..00000000
--- a/examples/dfp/v201408/creative_template_service/get_all_creative_templates.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all creative templates.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeTemplateService.getCreativeTemplatesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- creative_template_service = client.GetService(
- 'CreativeTemplateService', version='v201408')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get creative templates by statement.
- while True:
- response = creative_template_service.getCreativeTemplatesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for template in response['results']:
- print ('Creative template with id \'%s\', name \'%s\', and type \'%s\' '
- 'was found.' % (template['id'],
- template['name'],
- template['type']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/creative_template_service/get_creative_templates_by_statement.py b/examples/dfp/v201408/creative_template_service/get_creative_templates_by_statement.py
deleted file mode 100755
index 49095751..00000000
--- a/examples/dfp/v201408/creative_template_service/get_creative_templates_by_statement.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all system defined creative templates.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeTemplateService.getCreativeTemplatesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- creative_template_service = client.GetService(
- 'CreativeTemplateService', version='v201408')
-
- # Create statement object to only select system defined creative templates.
- values = [{
- 'key': 'creativeTemplateType',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'SYSTEM_DEFINED'
- }
- }]
- query = 'WHERE type = :creativeTemplateType'
- statement = dfp.FilterStatement(query, values)
-
- # Get creative templates by statement.
- while True:
- response = creative_template_service.getCreativeTemplatesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for template in response['results']:
- print ('Creative template with id \'%s\', name \'%s\', and type \'%s\' '
- 'was found.' % (template['id'],
- template['name'],
- template['type']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/creative_wrapper_service/create_creative_wrappers.py b/examples/dfp/v201408/creative_wrapper_service/create_creative_wrappers.py
deleted file mode 100755
index a214487a..00000000
--- a/examples/dfp/v201408/creative_wrapper_service/create_creative_wrappers.py
+++ /dev/null
@@ -1,66 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates a new creative wrapper.
-
-Creative wrappers must be associated with a LabelType.CREATIVE_WRAPPER label and
-applied to ad units by AdUnit.appliedLabels. To determine which creative
-wrappers exist, run get_all_creative_wrappers.py
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeWrapperService.createCreativeWrappers
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-LABEL_ID = 'INSERT_CREATIVE_WRAPPER_LABEL_ID_HERE'
-
-
-def main(client, label_id):
- # Initialize appropriate service.
- creative_wrapper_service = client.GetService('CreativeWrapperService',
- version='v201408')
-
- # Create creative wrapper objects.
- creative_wrapper = {
- # A label can only be associated with one creative wrapper.
- 'labelId': label_id,
- 'ordering': 'INNER',
- 'header': {'htmlSnippet': 'My creative wrapper header'},
- 'footer': {'htmlSnippet': 'My creative wrapper footer'}
- }
-
- # Add creative wrapper.
- creative_wrappers = creative_wrapper_service.createCreativeWrappers(
- [creative_wrapper])
-
- # Display results.
- for creative_wrapper in creative_wrappers:
- print ('Creative wrapper with ID \'%s\' applying to label \'%s\' was '
- 'created.' % (creative_wrapper['id'], creative_wrapper['labelId']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, LABEL_ID)
diff --git a/examples/dfp/v201408/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201408/creative_wrapper_service/deactivate_creative_wrapper.py
deleted file mode 100755
index e17cd42c..00000000
--- a/examples/dfp/v201408/creative_wrapper_service/deactivate_creative_wrapper.py
+++ /dev/null
@@ -1,92 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example deactivates a creative wrapper belonging to a label.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeWrapperService.getCreativeWrapperByStatement
-Tags: CreativeWrapperService.performCreativeWrapperAction
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-LABEL_ID = 'INSERT_LABEL_ID_HERE'
-
-
-def main(client, label_id):
- # Initialize appropriate service.
- creative_wrapper_service = client.GetService('CreativeWrapperService',
- version='v201408')
-
- # Create a query to select the active creative wrappers for the given label.
- values = [{
- 'key': 'labelId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': label_id
- }
- }, {
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ACTIVE'
- }
- }]
- query = 'WHERE status = :status AND labelId = :labelId'
- statement = dfp.FilterStatement(query, values)
-
- creative_wrappers_deactivated = 0
-
- # Get creative wrappers by statement.
- while True:
- response = creative_wrapper_service.getCreativeWrappersByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for creative_wrapper in response['results']:
- print ('Creative wrapper with ID \'%s\' applying to label \'%s\' with '
- 'status \'%s\' will be deactivated.' %
- (creative_wrapper['id'],
- creative_wrapper['labelId'],
- creative_wrapper['status']))
- # Perform action.
- result = creative_wrapper_service.performCreativeWrapperAction(
- {'xsi_type': 'DeactivateCreativeWrappers'}, statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- creative_wrappers_deactivated += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Display results.
- if creative_wrappers_deactivated > 0:
- print ('Number of creative wrappers deactivated: %s' %
- creative_wrappers_deactivated)
- else:
- print 'No creative wrappers were deactivated.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, LABEL_ID)
diff --git a/examples/dfp/v201408/creative_wrapper_service/get_active_creative_wrappers.py b/examples/dfp/v201408/creative_wrapper_service/get_active_creative_wrappers.py
deleted file mode 100755
index 08e1271e..00000000
--- a/examples/dfp/v201408/creative_wrapper_service/get_active_creative_wrappers.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all active creative wrappers.
-
-To create creative wrappers, run create_creative_wrappers.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeWrapperService.getCreativeWrappersByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- creative_wrapper_service = client.GetService('CreativeWrapperService',
- version='v201408')
-
- # Create statement object to only select active creative wrappers.
- values = [{
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ACTIVE'
- }
- }]
- query = 'WHERE status = :status'
- statement = dfp.FilterStatement(query, values)
-
- # Get creative wrappers by statement.
- while True:
- response = creative_wrapper_service.getCreativeWrappersByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for creative_wrapper in response['results']:
- print ('Creative wrapper with ID \'%s\' applying to label \'%s\' was '
- 'found.' % (creative_wrapper['id'], creative_wrapper['labelId']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/creative_wrapper_service/get_all_creative_wrappers.py b/examples/dfp/v201408/creative_wrapper_service/get_all_creative_wrappers.py
deleted file mode 100755
index 04db6e88..00000000
--- a/examples/dfp/v201408/creative_wrapper_service/get_all_creative_wrappers.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all creative wrappers.
-
-To create creative wrappers, run create_creative_wrappers.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeWrapperService.getCreativeWrappersByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- creative_wrapper_service = client.GetService('CreativeWrapperService',
- version='v201408')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get creative wrappers by statement.
- while True:
- response = creative_wrapper_service.getCreativeWrappersByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for creative_wrapper in response['results']:
- print ('Creative wrapper with ID \'%s\' applying to label \'%s\' was '
- 'found.' % (creative_wrapper['id'], creative_wrapper['labelId']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/creative_wrapper_service/update_creative_wrappers.py b/examples/dfp/v201408/creative_wrapper_service/update_creative_wrappers.py
deleted file mode 100755
index 230fc1e3..00000000
--- a/examples/dfp/v201408/creative_wrapper_service/update_creative_wrappers.py
+++ /dev/null
@@ -1,81 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates a creative wrapper to the 'OUTER' wrapping order.
-
-To determine which creative wrappers exist, run get_all_creative_wrappers.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeWrapperService.getCreativeWrappersByStatement
-Tags: CreativeWrapperService.updateCreativeWrappers
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the creative wrapper to update.
-CREATIVE_WRAPPER_ID = 'INSERT_CREATIVE_WRAPPER_ID_HERE'
-
-
-def main(client, creative_wrapper_id):
- # Initialize appropriate service.
- creative_wrapper_service = client.GetService('CreativeWrapperService',
- version='v201408')
-
- # Create statement to get a creative wrapper by ID.
- values = [{
- 'key': 'creativeWrapperId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': creative_wrapper_id
- }
- }]
- query = 'WHERE id = :creativeWrapperId'
- statement = dfp.FilterStatement(query, values)
-
- # Get creative wrappers.
- response = creative_wrapper_service.getCreativeWrappersByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- updated_creative_wrappers = []
- for creative_wrapper in response['results']:
- creative_wrapper['ordering'] = 'OUTER'
- updated_creative_wrappers.append(creative_wrapper)
-
- # Update the creative wrappers on the server.
- creative_wrappers = creative_wrapper_service.updateCreativeWrappers(
- updated_creative_wrappers)
-
- # Display results.
- for creative_wrapper in creative_wrappers:
- print (('Creative wrapper with ID \'%s\' and wrapping order \'%s\' '
- 'was updated.') % (creative_wrapper['id'],
- creative_wrapper['ordering']))
- else:
- print 'No creative wrappers found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CREATIVE_WRAPPER_ID)
diff --git a/examples/dfp/v201408/custom_field_service/__init__.py b/examples/dfp/v201408/custom_field_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201408/custom_field_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201408/custom_field_service/create_custom_field_options.py b/examples/dfp/v201408/custom_field_service/create_custom_field_options.py
deleted file mode 100755
index c26ab0e6..00000000
--- a/examples/dfp/v201408/custom_field_service/create_custom_field_options.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates custom field options for a drop-down custom field.
-
-Once created, custom field options can be found under the options fields of the
-drop-down custom field and they cannot be deleted. To determine which custom
-fields exist, run get_all_custom_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomFieldService.createCustomFieldOptions
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the drop-down custom field to create options for.
-CUSTOM_FIELD_ID = 'INSERT_DROP_DOWN_CUSTOM_FIELD_ID_HERE'
-
-
-def main(client, custom_field_id):
- # Initialize appropriate service.
- custom_field_service = client.GetService(
- 'CustomFieldService', version='v201408')
-
- # Create custom field options.
- custom_field_options = [
- {
- 'displayName': 'Approved',
- 'customFieldId': custom_field_id
- },
- {
- 'displayName': 'Unapproved',
- 'customFieldId': custom_field_id
- }
- ]
-
- # Add custom field options.
- custom_field_options = custom_field_service.createCustomFieldOptions(
- custom_field_options)
-
- # Display results.
- for custom_field_option in custom_field_options:
- print ('Custom field option with ID \'%s\' and name \'%s\' was created.'
- % (custom_field_option['id'], custom_field_option['displayName']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CUSTOM_FIELD_ID)
diff --git a/examples/dfp/v201408/custom_field_service/create_custom_fields.py b/examples/dfp/v201408/custom_field_service/create_custom_fields.py
deleted file mode 100755
index 3c3c0dee..00000000
--- a/examples/dfp/v201408/custom_field_service/create_custom_fields.py
+++ /dev/null
@@ -1,69 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates custom fields.
-
-To determine which custom fields exist, run get_all_custom_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomFieldService.createCustomFields
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- custom_field_service = client.GetService(
- 'CustomFieldService', version='v201408')
-
- # Create custom field objects.
- custom_fields = [
- {
- 'name': 'Customer comments #%s' % uuid.uuid4(),
- 'entityType': 'LINE_ITEM',
- 'dataType': 'STRING',
- 'visibility': 'FULL'
- }, {
- 'name': 'Internal approval status #%s' % uuid.uuid4(),
- 'entityType': 'LINE_ITEM',
- 'dataType': 'DROP_DOWN',
- 'visibility': 'FULL'
- }
- ]
-
- # Add custom fields.
- custom_fields = custom_field_service.createCustomFields(custom_fields)
-
- # Display results.
- for custom_field in custom_fields:
- print ('Custom field with ID \'%s\' and name \'%s\' was created.'
- % (custom_field['id'], custom_field['name']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201408/custom_field_service/deactivate_all_line_item_custom_fields.py
deleted file mode 100755
index 556949d3..00000000
--- a/examples/dfp/v201408/custom_field_service/deactivate_all_line_item_custom_fields.py
+++ /dev/null
@@ -1,89 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example deactivates all active line items custom fields.
-
-To determine which custom fields exist, run get_all_custom_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomFieldService.getCustomFieldsByStatement
-Tags: CustomFieldService.performCustomFieldAction
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- custom_field_service = client.GetService(
- 'CustomFieldService', version='v201408')
-
- # Create statement to select only active custom fields that apply to
- # line items.
- values = [
- {
- 'key': 'entityType',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'LINE_ITEM'
- }
- }, {
- 'key': 'isActive',
- 'value': {
- 'xsi_type': 'BooleanValue',
- 'value': 'true'
- }
- }
- ]
- query = 'WHERE entityType = :entityType and isActive = :isActive'
- statement = dfp.FilterStatement(query, values)
-
- custom_fields_deactivated = 0
-
- # Get custom fields by statement.
- while True:
- response = custom_field_service.getCustomFieldsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for custom_field in response['results']:
- print ('Custom field with ID \'%s\' and name \'%s\' will'
- ' be deactivated.' % (custom_field['id'], custom_field['name']))
- result = custom_field_service.performCustomFieldAction(
- {'xsi_type': 'DeactivateCustomFields'}, statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- custom_fields_deactivated += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- if custom_fields_deactivated > 0:
- print 'Number of custom fields deactivated: %s' % custom_fields_deactivated
- else:
- print 'No custom fields were deactivated.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/custom_field_service/get_all_custom_fields.py b/examples/dfp/v201408/custom_field_service/get_all_custom_fields.py
deleted file mode 100755
index 0a239cf8..00000000
--- a/examples/dfp/v201408/custom_field_service/get_all_custom_fields.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all custom fields.
-
-To create custom fields, run create_custom_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomFieldService.getCustomFieldsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- custom_field_service = client.GetService(
- 'CustomFieldService', version='v201408')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get custom fields by statement.
- while True:
- response = custom_field_service.getCustomFieldsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for custom_field in response['results']:
- print ('Custom field with ID \'%s\' and name \'%s\' was found.'
- % (custom_field['id'], custom_field['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/custom_field_service/get_all_line_item_custom_fields.py b/examples/dfp/v201408/custom_field_service/get_all_line_item_custom_fields.py
deleted file mode 100755
index 303e0dc3..00000000
--- a/examples/dfp/v201408/custom_field_service/get_all_line_item_custom_fields.py
+++ /dev/null
@@ -1,72 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all custom fields that apply to line items.
-
-To create custom fields, run create_custom_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomFieldService.getCustomFieldsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- custom_field_service = client.GetService(
- 'CustomFieldService', version='v201408')
-
- # Create statement to select only custom fields that apply to line items.
- values = [{
- 'key': 'entityType',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'LINE_ITEM'
- }
- }]
- query = 'WHERE entityType = :entityType'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Get custom fields by statement.
- while True:
- response = custom_field_service.getCustomFieldsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for custom_field in response['results']:
- print ('Custom field with ID \'%s\' and name \'%s\' was found.'
- % (custom_field['id'], custom_field['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/custom_field_service/set_line_item_custom_field_value.py b/examples/dfp/v201408/custom_field_service/set_line_item_custom_field_value.py
deleted file mode 100755
index 205d147b..00000000
--- a/examples/dfp/v201408/custom_field_service/set_line_item_custom_field_value.py
+++ /dev/null
@@ -1,160 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example sets custom field values on a line item.
-
-To determine which custom fields exist, run get_all_custom_fields.py.
-To determine which line item exist, run get_all_line_items.py.
-To create custom field options, run create_custom_field_options.py
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomFieldService.getCustomFieldsByStatement
- LineItemService.getLineItemsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the custom fields, custom field option, and line item.
-CUSTOM_FIELD_ID = 'INSERT_CUSTOM_FIELD_ID_HERE'
-DROP_DOWN_CUSTOM_FIELD_ID = 'INSERT_DROP_DOWN_CUSTOM_FIELD_ID_HERE'
-CUSTOM_FIELD_OPTION_ID = 'INSERT_CUSTOM_FIELD_OPTION_ID_HERE'
-LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
-
-
-def main(client, custom_field_id, drop_down_custom_field_id,
- custom_field_option_id, line_item_id):
- # Initialize appropriate services.
- custom_field_service = client.GetService(
- 'CustomFieldService', version='v201408')
-
- line_item_service = client.GetService('LineItemService', version='v201408')
-
- # Create statement to get a custom field.
- custom_field_values = [{
- 'key': 'customFieldId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': custom_field_id
- }
- }]
- custom_field_query = 'WHERE id = :customFieldId'
- custom_field_statement = dfp.FilterStatement(
- custom_field_query, custom_field_values, 1)
-
- # Get custom field.
- custom_field = custom_field_service.getCustomFieldsByStatement(
- custom_field_statement.ToStatement())['results'][0]
-
- # Create statement to get a drop down custom field.
- drop_down_custom_field_values = [{
- 'key': 'dropDownCustomFieldId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': drop_down_custom_field_id
- }
- }]
- drop_down_custom_field_query = 'WHERE id = :dropDownCustomFieldId'
- drop_down_custom_field_statement = dfp.FilterStatement(
- drop_down_custom_field_query, drop_down_custom_field_values, 1)
-
- # Get drop-down custom field.
- drop_down_custom_field = custom_field_service.getCustomFieldsByStatement(
- drop_down_custom_field_statement.ToStatement())['results'][0]
-
- # Create statement to get a line item.
- line_item_values = [{
- 'key': 'lineItemId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': line_item_id
- }
- }]
- line_item_query = 'WHERE id = :lineItemId'
- line_item_statement = dfp.FilterStatement(
- line_item_query, line_item_values, 1)
-
- # Get line item.
- line_item = line_item_service.getLineItemsByStatement(
- line_item_statement.ToStatement())['results'][0]
-
- if custom_field and line_item:
- # Create custom field values.
- custom_field_value = {
- 'customFieldId': custom_field['id'],
- 'xsi_type': 'CustomFieldValue',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'Custom field value'
- }
- }
-
- drop_down_custom_field_value = {
- 'customFieldId': drop_down_custom_field['id'],
- 'xsi_type': 'DropDownCustomFieldValue',
- 'customFieldOptionId': custom_field_option_id,
- }
-
- custom_field_values = [custom_field_value, drop_down_custom_field_value]
-
- old_custom_field_values = []
- if 'customFieldValues' in line_item:
- old_custom_field_values = line_item['customFieldValues']
-
- # Only add existing custom field values for different custom fields than the
- # ones you are setting.
- for old_custom_field_value in old_custom_field_values:
- if (old_custom_field_value['customFieldId'] !=
- custom_field_value['customFieldId']
- and old_custom_field_value['customFieldId'] !=
- drop_down_custom_field_value['customFieldId']):
- custom_field_values.append(old_custom_field_value)
-
- line_item['customFieldValues'] = custom_field_values
-
- # Update the line item on the server.
- line_items = line_item_service.updateLineItems([line_item])
-
- # Display results.
- for line_item in line_items:
- custom_field_value_strings = []
- for value in line_item['customFieldValues']:
- if value['BaseCustomFieldValue.Type'] == 'CustomFieldValue':
- custom_field_value_string = (
- '{ID: \'%s\', value: \'%s\'}'
- % (value['customFieldId'], value['value']['value']))
- elif value['BaseCustomFieldValue.Type'] == 'DropDownCustomFieldValue':
- custom_field_value_string = (
- '{ID: \'%s\', custom field option ID: \'%s\'}'
- % (value['customFieldId'], value['customFieldOptionId']))
- custom_field_value_strings.append(custom_field_value_string)
- print ('Line item with ID \'%s\' set with custom field values %s.'
- % (line_item['id'], ','.join(custom_field_value_strings)))
- else:
- print 'Line item or custom field not found.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CUSTOM_FIELD_ID, DROP_DOWN_CUSTOM_FIELD_ID,
- CUSTOM_FIELD_OPTION_ID, LINE_ITEM_ID)
diff --git a/examples/dfp/v201408/custom_field_service/update_custom_fields.py b/examples/dfp/v201408/custom_field_service/update_custom_fields.py
deleted file mode 100755
index 01620256..00000000
--- a/examples/dfp/v201408/custom_field_service/update_custom_fields.py
+++ /dev/null
@@ -1,79 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates custom field descriptions.
-
-To determine which custom fields exist, run get_all_custom_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomFieldService.updateCustomFields
- CustomFieldService.getCustomFieldByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the custom field to update.
-CUSTOM_FIELD_ID = 'INSERT_CUSTOM_FIELD_ID_HERE'
-
-
-def main(client, custom_field_id):
- # Initialize appropriate service.
- custom_field_service = client.GetService(
- 'CustomFieldService', version='v201408')
-
- # Create statement to get a custom field.
- values = [{
- 'key': 'customFieldId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': custom_field_id
- }
- }]
- query = 'WHERE id = :customFieldId'
- statement = dfp.FilterStatement(query, values)
-
- # Get custom field.
- custom_fields = custom_field_service.getCustomsFieldByStatement(
- statement.ToStatement())
-
- if custom_fields:
- for custom_field in custom_fields:
- custom_field['description'] += ' Updated.'
-
- # Update the custom field on the server.
- custom_fields = custom_field_service.updateCustomFields(custom_fields)
-
- # Display results.
- for custom_field in custom_fields:
- print (('Custom field with ID \'%s\', name \'%s\', and '
- 'description \'%s\' was updated.')
- % (custom_field['id'], custom_field['name'],
- custom_field['description']))
- else:
- print 'No custom fields found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CUSTOM_FIELD_ID)
diff --git a/examples/dfp/v201408/custom_targeting_service/__init__.py b/examples/dfp/v201408/custom_targeting_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201408/custom_targeting_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201408/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/dfp/v201408/custom_targeting_service/create_custom_targeting_keys_and_values.py
deleted file mode 100755
index 5e5468b3..00000000
--- a/examples/dfp/v201408/custom_targeting_service/create_custom_targeting_keys_and_values.py
+++ /dev/null
@@ -1,136 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates new custom targeting keys and values.
-
-To determine which custom targeting keys and values exist, run
-get_all_custom_targeting_keys_and_values.py. To target these custom targeting
-keys and values, run target_custom_criteria_example.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomTargetingService.createCustomTargetingKeys
- CustomTargetingService.createCustomTargetingValues
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- custom_targeting_service = client.GetService(
- 'CustomTargetingService', version='v201408')
-
- # Create custom targeting key objects.
- keys = [
- {
- 'displayName': 'gender',
- 'name': 'g',
- 'type': 'PREDEFINED'
- },
- {
- 'displayName': 'car model',
- 'name': 'c',
- 'type': 'FREEFORM'
- },
- # Add predefined key that may be use for content targeting.
- {
- 'displayName': 'genre',
- 'name': 'genre',
- 'type': 'PREDEFINED'
- }
- ]
-
- # Add custom targeting keys.
- keys = custom_targeting_service.createCustomTargetingKeys(keys)
-
- # Display results.
- if keys:
- for key in keys:
- print ('A custom targeting key with id \'%s\', name \'%s\', and display '
- 'name \'%s\' was created.' % (key['id'], key['name'],
- key['displayName']))
- else:
- print 'No keys were created.'
-
- # Create custom targeting value objects.
- values = [
- {
- 'customTargetingKeyId': keys['id'],
- 'displayName': 'male',
- # Name is set to 1 so that the actual name can be hidden from website
- # users.
- 'name': '1',
- 'matchType': 'EXACT'
- },
- {
- 'customTargetingKeyId': keys['id'],
- 'displayName': 'female',
- # Name is set to 2 so that the actual name can be hidden from website
- # users.
- 'name': '2',
- 'matchType': 'EXACT'
- },
- {
- 'customTargetingKeyId': keys[1]['id'],
- 'displayName': 'honda civic',
- 'name': 'honda civic',
- 'matchType': 'EXACT'
- },
- {
- 'customTargetingKeyId': keys[1]['id'],
- 'displayName': 'toyota',
- 'name': 'toyota',
- 'matchType': 'EXACT'
- },
- {
- 'customTargetingKeyId': keys[2]['id'],
- 'displayName': 'comedy',
- 'name': 'comedy',
- 'matchType': 'EXACT'
- },
- {
- 'customTargetingKeyId': keys[2]['id'],
- 'displayName': 'drama',
- 'name': 'drama',
- 'matchType': 'EXACT'
- }
- ]
-
- # Add custom targeting values.
- values = custom_targeting_service.createCustomTargetingValues(values)
-
- # Display results.
- if values:
- for value in values:
- print ('A custom targeting value with id \'%s\', belonging to key with id'
- ' \'%s\', name \'%s\', and display name \'%s\' was created.'
- % (value['id'], value['customTargetingKeyId'], value['name'],
- value['displayName']))
- else:
- print 'No values were created.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/custom_targeting_service/delete_custom_targeting_keys.py b/examples/dfp/v201408/custom_targeting_service/delete_custom_targeting_keys.py
deleted file mode 100755
index 3e53a959..00000000
--- a/examples/dfp/v201408/custom_targeting_service/delete_custom_targeting_keys.py
+++ /dev/null
@@ -1,85 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example deletes a custom targeting key by its name.
-
-To determine which custom targeting keys exist, run
-get_all_custom_targeting_keys_and_values.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomTargetingService.getCustomTargetingKeysByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-KEY_NAME = 'INSERT_CUSTOM_TARGETING_KEY_NAME_HERE'
-
-
-def main(client, key_name):
- # Initialize appropriate service.
- custom_targeting_service = client.GetService(
- 'CustomTargetingService', version='v201408')
-
- values = [{
- 'key': 'name',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': key_name
- }
- }]
- query = 'WHERE name = :name'
- statement = dfp.FilterStatement(query, values)
-
- deleted_custom_targeting_keys = 0
-
- # Get custom targeting keys.
- while True:
- response = custom_targeting_service.getCustomTargetingKeysByStatement(
- statement.ToStatement())
- if 'results' in response:
- key_ids = [key['id'] for key in response['results']]
- action = {'xsi_type': 'DeleteCustomTargetingKeys'}
- key_query = 'WHERE id IN (%s)' % ', '.join(key_ids)
- key_statement = dfp.FilterStatement(key_query)
-
- # Delete custom targeting keys.
- result = custom_targeting_service.performCustomTargetingKeyAction(
- action, key_statement.ToStatement())
-
- if result and int(result['numChanges']) > 0:
- deleted_custom_targeting_keys += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- if deleted_custom_targeting_keys > 0:
- print ('Number of custom targeting keys deleted: %s'
- % deleted_custom_targeting_keys)
- else:
- print 'No custom targeting keys were deleted.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, KEY_NAME)
diff --git a/examples/dfp/v201408/custom_targeting_service/delete_custom_targeting_values.py b/examples/dfp/v201408/custom_targeting_service/delete_custom_targeting_values.py
deleted file mode 100755
index c7b3ba97..00000000
--- a/examples/dfp/v201408/custom_targeting_service/delete_custom_targeting_values.py
+++ /dev/null
@@ -1,86 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example deletes custom targeting values for a given custom targeting
-key.
-
-To determine which custom targeting keys and values exist, run
-get_all_custom_targeting_keys_and_values.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomTargetingService.getCustomTargetingValuesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'
-
-
-def main(client, key_id):
- # Initialize appropriate service.
- custom_targeting_service = client.GetService(
- 'CustomTargetingService', version='v201408')
-
- filter_values = [{
- 'key': 'keyId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': key_id
- }
- }]
- query = 'WHERE customTargetingKeyId = :keyId'
- statement = dfp.FilterStatement(query, filter_values)
-
- deleted_custom_targeting_values = 0
-
- # Get custom targeting values.
- while True:
- response = custom_targeting_service.getCustomTargetingValuesByStatement(
- statement.ToStatement())
- if 'results' in response:
- value_ids = [value['id'] for value in response['results']]
- action = {'xsi_type': 'DeleteCustomTargetingValues'}
- value_query = ('WHERE customTargetingKeyId = :keyId '
- 'AND id IN (%s)' % ', '.join(value_ids))
- value_statement = dfp.FilterStatement(value_query, filter_values)
-
- # Delete custom targeting values.
- result = custom_targeting_service.performCustomTargetingValueAction(
- action, value_statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- deleted_custom_targeting_values += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- if deleted_custom_targeting_values > 0:
- print ('Number of custom targeting values deleted: %s'
- % deleted_custom_targeting_values)
- else:
- print 'No custom targeting values were deleted.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, KEY_ID)
diff --git a/examples/dfp/v201408/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201408/custom_targeting_service/get_all_custom_targeting_keys_and_values.py
deleted file mode 100755
index a2955679..00000000
--- a/examples/dfp/v201408/custom_targeting_service/get_all_custom_targeting_keys_and_values.py
+++ /dev/null
@@ -1,90 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all custom targeting keys and the values.
-
-To create custom targeting keys and values, run
-create_custom_targeting_keys_and_values.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- custom_targeting_service = client.GetService(
- 'CustomTargetingService', version='v201408')
-
- # Create statement to get all targeting keys.
- targeting_key_statement = dfp.FilterStatement()
-
- all_keys = []
-
- # Get custom targeting keys by statement.
- while True:
- response = custom_targeting_service.getCustomTargetingKeysByStatement(
- targeting_key_statement.ToStatement())
- if 'results' in response:
- all_keys.extend(response['results'])
- targeting_key_statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- if all_keys:
- # Create map of custom targeting key id to custom targeting values.
- key_value_map = {}
-
- # Create statement to get all targeting values.
- query = ('WHERE customTargetingKeyId IN (%s)'
- % ', '.join([key['id'] for key in all_keys]))
- targeting_value_statement = dfp.FilterStatement(query)
-
- # Get custom targeting values by statement.
- while True:
- response = custom_targeting_service.getCustomTargetingValuesByStatement(
- targeting_value_statement.ToStatement())
- if 'results' in response:
- for key in all_keys:
- for value in response['results']:
- if key['id'] == value['customTargetingKeyId']:
- if key['id'] not in key_value_map.keys():
- key_value_map[key['id']] = []
- key_value_map[key['id']].append(value)
- targeting_value_statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Display results.
- for key in all_keys:
- print ('Custom targeting key with id \'%s\', name \'%s\', display name '
- '\'%s\', and type \'%s\' was found.'
- %(key['id'], key['name'], key['displayName'], key['type']))
- if key['id'] in key_value_map.keys():
- for value in key_value_map[key['id']]:
- print ('\tCustom targeting value with id \'%s\', name \'%s\', and '
- 'display name \'%s\' was found.'
- % (value['id'], value['name'], value['displayName']))
- else:
- print 'No keys were found.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
-
diff --git a/examples/dfp/v201408/custom_targeting_service/get_custom_targeting_keys_by_statement.py b/examples/dfp/v201408/custom_targeting_service/get_custom_targeting_keys_by_statement.py
deleted file mode 100755
index f108e71f..00000000
--- a/examples/dfp/v201408/custom_targeting_service/get_custom_targeting_keys_by_statement.py
+++ /dev/null
@@ -1,63 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all predefined custom targeting keys.
-
-To create custom targeting keys, run create_custom_targeting_keys_and_values.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- custom_targeting_service = client.GetService(
- 'CustomTargetingService', version='v201408')
-
- values = [{
- 'key': 'type',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'PREDEFINED'
- }
- }]
- query = 'WHERE type = :type'
- statement = dfp.FilterStatement(query, values)
-
- # Get custom targeting keys by statement.
- while True:
- response = custom_targeting_service.getCustomTargetingKeysByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for key in response['results']:
- print ('Custom targeting key with id \'%s\', name \'%s\', display name '
- '\'%s\', and type \'%s\' was found.'
- % (key['id'], key['name'], key['displayName'], key['type']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/custom_targeting_service/get_custom_targeting_values_by_statement.py b/examples/dfp/v201408/custom_targeting_service/get_custom_targeting_values_by_statement.py
deleted file mode 100755
index 04eed247..00000000
--- a/examples/dfp/v201408/custom_targeting_service/get_custom_targeting_values_by_statement.py
+++ /dev/null
@@ -1,67 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets custom targeting values for the given predefined custom
-targeting key.
-
-To create custom targeting values, run
-create_custom_targeting_keys_and_values.py. To determine which custom
-targeting keys exist, run get_all_custom_targeting_keys_and_values.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'
-
-
-def main(client, key_id):
- # Initialize appropriate service.
- custom_targeting_service = client.GetService(
- 'CustomTargetingService', version='v201408')
-
- values = [{
- 'key': 'keyId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': key_id
- }
- }]
- query = 'WHERE customTargetingKeyId = :keyId'
- statement = dfp.FilterStatement(query, values)
-
- # Get custom targeting values by statement.
- while True:
- response = custom_targeting_service.getCustomTargetingValuesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for value in response['results']:
- print ('Custom targeting value with id \'%s\', name \'%s\', and display'
- ' name \'%s\' was found.'
- % (value['id'], value['name'], value['displayName']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CUSTOM_TARGETING_KEY_ID)
diff --git a/examples/dfp/v201408/custom_targeting_service/update_custom_targeting_keys.py b/examples/dfp/v201408/custom_targeting_service/update_custom_targeting_keys.py
deleted file mode 100755
index 6adfc325..00000000
--- a/examples/dfp/v201408/custom_targeting_service/update_custom_targeting_keys.py
+++ /dev/null
@@ -1,72 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates the display name of a single custom targeting key.
-
-To determine which custom targeting keys exist, run
-get_all_custom_targeting_keys_and_values.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'
-
-
-def main(client, key_id):
- # Initialize appropriate service.
- custom_targeting_service = client.GetService(
- 'CustomTargetingService', version='v201408')
-
- values = [{
- 'key': 'keyId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': key_id
- }
- }]
- query = 'WHERE id = :keyId'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get custom targeting keys by statement.
- response = custom_targeting_service.getCustomTargetingKeysByStatement(
- statement.ToStatement())
-
- # Update each local custom targeting key object by changing its display name.
- if 'results' in response:
- updated_keys = []
- for key in response['results']:
- if not key['displayName']:
- key['displayName'] = key['name']
- key['displayName'] += ' (Deprecated)'
- updated_keys.append(key)
- keys = custom_targeting_service.updateCustomTargetingKeys(updated_keys)
-
- # Display results.
- if keys:
- for key in keys:
- print ('Custom targeting key with id \'%s\', name \'%s\', display name '
- '\'%s\', and type \'%s\' was updated.'
- % (key['id'], key['name'], key['displayName'], key['type']))
- else:
- print 'No custom targeting keys were found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CUSTOM_TARGETING_KEY_ID)
diff --git a/examples/dfp/v201408/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201408/custom_targeting_service/update_custom_targeting_values.py
deleted file mode 100755
index a0e444bc..00000000
--- a/examples/dfp/v201408/custom_targeting_service/update_custom_targeting_values.py
+++ /dev/null
@@ -1,78 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates the display name of the custom targeting values
-belonging to a custom targeting key.
-
-To determine which custom targeting keys exist, run
-get_all_custom_targeting_keys_and_values.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'
-
-
-def main(client, key_id):
- # Initialize appropriate service.
- custom_targeting_service = client.GetService(
- 'CustomTargetingService', version='v201408')
-
- values = [{
- 'key': 'keyId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': key_id
- }
- }]
- query = 'WHERE customTargetingKeyId = :keyId'
- statement = dfp.FilterStatement(query, values)
-
- while True:
- # Get custom targeting values by statement.
- response = custom_targeting_service.getCustomTargetingValuesByStatement(
- statement.ToStatement())
-
- # Update each local custom targeting value object by changing its name.
- if 'results' in response:
- updated_values = []
- for value in response['results']:
- if not value['displayName']:
- value['displayName'] = value['name']
- value['displayName'] += ' (Deprecated)'
- updated_values.append(value)
- values = custom_targeting_service.updateCustomTargetingValues(
- updated_values)
-
- # Display results.
- for value in values:
- print ('Custom targeting value with id \'%s\', name \'%s\', and display'
- ' name \'%s\' was updated.'
- % (value['id'], value['name'], value['displayName']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- if response['totalResultSetSize'] == 0:
- print 'No custom targeting values were updated.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CUSTOM_TARGETING_KEY_ID)
diff --git a/examples/dfp/v201408/forecast_service/get_forecast.py b/examples/dfp/v201408/forecast_service/get_forecast.py
deleted file mode 100755
index c5909472..00000000
--- a/examples/dfp/v201408/forecast_service/get_forecast.py
+++ /dev/null
@@ -1,106 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets a forecast for a prospective line item.
-
-To determine which placements exist, run get_all_placements.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-from datetime import date
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the placement that the prospective line item will target.
-TARGET_PLACEMENT_IDS = ['INSERT_PLACEMENT_IDS_HERE']
-
-
-def main(client, target_placement_ids):
- # Initialize appropriate service.
- forecast_service = client.GetService('ForecastService', version='v201408')
-
- # Create prospective line item.
- line_item = {
- 'targeting': {
- 'inventoryTargeting': {
- 'targetedPlacementIds': target_placement_ids
- }
- },
- 'creativePlaceholders': [
- {
- 'size': {
- 'width': '300',
- 'height': '250'
- }
- },
- {
- 'size': {
- 'width': '120',
- 'height': '600'
- }
- }
- ],
- 'lineItemType': 'SPONSORSHIP',
- 'startDateTimeType': 'IMMEDIATELY',
- 'endDateTime': {
- 'date': {
- 'year': str(date.today().year + 1),
- 'month': '9',
- 'day': '30'
- },
- 'hour': '0',
- 'minute': '0',
- 'second': '0'
- },
- 'costType': 'CPM',
- 'costPerUnit': {
- 'currencyCode': 'USD',
- 'microAmount': '2000000'
- },
- 'primaryGoal': {
- 'units': '50',
- 'unitType': 'IMPRESSIONS',
- 'goalType': 'DAILY'
- },
- 'contractedUnitsBought': '100',
- 'creativeRotationType': 'EVEN',
- 'discountType': 'PERCENTAGE',
- }
-
- # Get forecast.
- forecast = forecast_service.getForecast(line_item)
- matched = long(forecast['matchedUnits'])
- available_percent = (((long(forecast['availableUnits'])/
- (matched * 1.0)) * 100)
- if matched != 0 else 0)
- contending_line_items = ([] if 'contendingLineItems' not in forecast
- else forecast['contendingLineItems'])
-
- # Display results.
- print '%s %s matched.' % (matched, forecast['unitType'].lower())
- print '%s%% %s available.' % (available_percent, forecast['unitType'].lower())
- print '%d contending line items.' % len(contending_line_items)
-
- if 'possibleUnits' in forecast:
- possible_percent = (long(forecast['possibleUnits'])/(matched * 1.0)) * 100
- print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower())
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, TARGET_PLACEMENT_IDS)
diff --git a/examples/dfp/v201408/forecast_service/get_forecast_by_id.py b/examples/dfp/v201408/forecast_service/get_forecast_by_id.py
deleted file mode 100755
index c8d4263c..00000000
--- a/examples/dfp/v201408/forecast_service/get_forecast_by_id.py
+++ /dev/null
@@ -1,56 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets a forecast for an existing line item.
-
-To determine which line items exist, run get_all_line_items.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the line item to get a forecast for.
-LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID'
-
-
-def main(client, line_item_id):
- # Initialize appropriate service.
- forecast_service = client.GetService('ForecastService', version='v201408')
-
- # Get forecast for line item.
- forecast = forecast_service.getForecastById(line_item_id)
- matched = long(forecast['matchedUnits'])
- available_percent = (((long(forecast['availableUnits'])/
- (matched * 1.0)) * 100)
- if matched != 0 else 0)
- contending_line_items = ([] if 'contendingLineItems' not in forecast
- else forecast['contendingLineItems'])
-
- # Display results.
- print '%s %s matched.' % (matched, forecast['unitType'].lower())
- print '%s%% %s available.' % (available_percent, forecast['unitType'].lower())
- print '%d contending line items.' % len(contending_line_items)
-
- if 'possibleUnits' in forecast:
- possible_percent = (long(forecast['possibleUnits'])/(matched * 1.0)) * 100
- print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower())
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, LINE_ITEM_ID)
diff --git a/examples/dfp/v201408/inventory_service/__init__.py b/examples/dfp/v201408/inventory_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201408/inventory_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201408/inventory_service/archive_ad_units.py b/examples/dfp/v201408/inventory_service/archive_ad_units.py
deleted file mode 100755
index 86518875..00000000
--- a/examples/dfp/v201408/inventory_service/archive_ad_units.py
+++ /dev/null
@@ -1,83 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example archives ad units.
-
-The parent ad unit and all ad units underneath it will be archived. To create ad
-units, run create_ad_units.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: InventoryService.getAdUnitsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-PARENT_AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE'
-
-
-def main(client, parent_id):
- # Initialize appropriate service.
- inventory_service = client.GetService('InventoryService', version='v201408')
-
- # Create a query to select ad units under the parent ad unit and the parent ad
- # unit.
- values = [{
- 'key': 'parentId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': parent_id
- }
- }]
- query = 'WHERE parentId = :parentId or id = :parentId'
- statement = dfp.FilterStatement(query, values)
-
- ad_units_archived = 0
-
- # Get ad units by statement.
- while True:
- response = inventory_service.getAdUnitsByStatement(
- statement.ToStatement())
- if 'results' in response:
- for ad_unit in response['results']:
- print ('Ad unit with ID \'%s\' and name \'%s\' will be archived.'
- % (ad_unit['id'], ad_unit['name']))
- # Perform action.
- result = inventory_service.performAdUnitAction(
- {'xsi_type': 'ArchiveAdUnits'}, statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- ad_units_archived += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Display results.
- if ad_units_archived > 0:
- print 'Number of ad units archived: %s' % ad_units_archived
- else:
- print 'No ad units were archived.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PARENT_AD_UNIT_ID)
diff --git a/examples/dfp/v201408/inventory_service/create_ad_units.py b/examples/dfp/v201408/inventory_service/create_ad_units.py
deleted file mode 100755
index 1061837d..00000000
--- a/examples/dfp/v201408/inventory_service/create_ad_units.py
+++ /dev/null
@@ -1,74 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new ad units.
-
-To determine which ad units exist, run get_all_ad_units.py
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: InventoryService.createAdUnits
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-PARENT_AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE'
-
-
-def main(client, parent_id):
- # Initialize appropriate service.
- inventory_service = client.GetService('InventoryService', version='v201408')
-
- # Create ad unit size.
- ad_unit_size = {
- 'size': {
- 'width': '300',
- 'height': '250'
- },
- 'environmentType': 'BROWSER'
- }
-
- # Create ad unit objects.
- ad_unit = {
- 'name': 'Ad_unit_%s' % uuid.uuid4(),
- 'parentId': parent_id,
- 'description': 'Ad unit description.',
- 'targetWindow': 'BLANK',
- 'targetPlatform': 'WEB',
- 'adUnitSizes': [ad_unit_size]
- }
-
- # Add ad units.
- ad_units = inventory_service.createAdUnits([ad_unit])
-
- # Display results.
- for ad_unit in ad_units:
- print ('Ad unit with ID \'%s\' and name \'%s\' was created.'
- % (ad_unit['id'], ad_unit['name']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PARENT_AD_UNIT_ID)
diff --git a/examples/dfp/v201408/inventory_service/get_ad_unit_hierarchy.py b/examples/dfp/v201408/inventory_service/get_ad_unit_hierarchy.py
deleted file mode 100755
index b3469245..00000000
--- a/examples/dfp/v201408/inventory_service/get_ad_unit_hierarchy.py
+++ /dev/null
@@ -1,118 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code gets the ad unit hierarchy and displays it as a tree.
-
-To create ad units, run create_ad_units.py
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: InventoryService.getAdUnitsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- inventory_service = client.GetService('InventoryService', version='v201408')
- statement = dfp.FilterStatement()
-
- all_ad_units = []
- # Get ad units by statement.
- while True:
- response = inventory_service.getAdUnitsByStatement(
- statement.ToStatement())
- if 'results' in response:
- all_ad_units.extend(response['results'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Find the root ad unit. root_ad_unit can also be set to child unit to only
- # build and display a portion of the tree.
- query = 'WHERE parentId IS NULL'
- root_statement = dfp.FilterStatement(query)
- response = inventory_service.getAdUnitsByStatement(
- root_statement.ToStatement())
- root_ad_unit = response['results']
-
- if root_ad_unit:
- BuildAndDisplayAdUnitTree(root_ad_unit, all_ad_units)
- else:
- print 'Could not build tree. No root ad unit found.'
-
-
-def DisplayAdUnitTree(root_ad_unit, ad_unit_tree, depth=0):
- """Helper for displaying ad unit tree.
-
- Args:
- root_ad_unit: dict the root ad unit.
- ad_unit_tree: dict the tree of ad units.
- [optional]
- depth: int the depth the tree has reached.
- """
- print '%s%s (%s)' % (GenerateTab(depth), root_ad_unit['name'],
- root_ad_unit['id'])
- if root_ad_unit['id'] in ad_unit_tree:
- for child in ad_unit_tree[root_ad_unit['id']]:
- DisplayAdUnitTree(child, ad_unit_tree, depth+1)
-
-
-def GenerateTab(depth):
- """Generate tabs to represent branching to children.
-
- Args:
- depth: int the depth the tree has reached.
-
- Returns:
- string inserted in front of the root unit.
- """
- tab_list = []
- if depth > 0:
- tab_list.append(' ')
- tab_list.append('| ' * depth)
- tab_list.append('+--')
- return ''.join(tab_list)
-
-
-def BuildAndDisplayAdUnitTree(root_ad_unit, all_ad_units):
- """Create an ad unit tree and display it.
-
- Args:
- root_ad_unit: dict the root ad unit to build the tree under.
- all_ad_units: list the list of all ad units to build the tree with.
- """
- tree = {}
- for ad_unit in all_ad_units:
- if 'parentId' in ad_unit:
- if ad_unit['parentId'] not in tree:
- tree[ad_unit['parentId']] = []
- tree[ad_unit['parentId']].append(ad_unit)
-
- DisplayAdUnitTree(root_ad_unit, tree)
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/inventory_service/get_all_ad_unit_sizes.py b/examples/dfp/v201408/inventory_service/get_all_ad_unit_sizes.py
deleted file mode 100755
index 180c781f..00000000
--- a/examples/dfp/v201408/inventory_service/get_all_ad_unit_sizes.py
+++ /dev/null
@@ -1,57 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all ad unit sizes defined in a network.
-
-To create ad units, run create_ad_units.py
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: InventoryService.getAdUnitSizesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- inventory_service = client.GetService('InventoryService', version='v201408')
- statement = dfp.FilterStatement()
-
- # Get ad units by statement.
- while True:
- response = inventory_service.getAdUnitSizesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for ad_unit_size in response['results']:
- print ('Ad unit size of dimensions %s was found.' %
- (ad_unit_size['fullDisplayString']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/inventory_service/get_all_ad_units.py b/examples/dfp/v201408/inventory_service/get_all_ad_units.py
deleted file mode 100755
index 6b8cfb52..00000000
--- a/examples/dfp/v201408/inventory_service/get_all_ad_units.py
+++ /dev/null
@@ -1,59 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all ad units within a network.
-
-To create ad units, run create_ad_units.py
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: InventoryService.getAdUnitsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- inventory_service = client.GetService('InventoryService', version='v201408')
- statement = dfp.FilterStatement()
-
- # Get ad units by statement.
- while True:
- response = inventory_service.getAdUnitsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for ad_unit in response['results']:
- print ('Ad unit with ID \'%s\' and name \'%s\' was found.'
- % (ad_unit['id'], ad_unit['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/inventory_service/get_top_level_ad_units.py b/examples/dfp/v201408/inventory_service/get_top_level_ad_units.py
deleted file mode 100755
index a32e7e12..00000000
--- a/examples/dfp/v201408/inventory_service/get_top_level_ad_units.py
+++ /dev/null
@@ -1,72 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all child ad units of the effective root ad unit.
-
-To create ad units, run create_ad_units.py
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: InventoryService.getAdUnitsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- inventory_service = client.GetService('InventoryService', version='v201408')
- network_service = client.GetService('NetworkService', version='v201408')
-
- root_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId']
-
- # Create a statement to select the children of the effective root ad unit.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': root_id
- }
- }]
- query = 'WHERE parentId = :id'
- statement = dfp.FilterStatement(query, values)
-
- # Get ad units by statement.
- while True:
- response = inventory_service.getAdUnitsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for ad_unit in response['results']:
- print ('Ad unit with ID \'%s\' and name \'%s\' was found.'
- % (ad_unit['id'], ad_unit['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/inventory_service/update_ad_units.py b/examples/dfp/v201408/inventory_service/update_ad_units.py
deleted file mode 100755
index 3a19b6ed..00000000
--- a/examples/dfp/v201408/inventory_service/update_ad_units.py
+++ /dev/null
@@ -1,91 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates ad unit sizes by adding a banner ad size.
-
-To determine which ad units exist, run get_all_ad_units.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: InventoryService.getAdUnit
-Tags: InventoryService.updateAdUnits
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-# Set the ID of the ad unit to get.
-AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE'
-
-
-def main(client, ad_unit_id):
- # Initialize appropriate service.
- inventory_service = client.GetService('InventoryService', version='v201408')
-
- # Create a statement to select a single ad unit by ID.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': ad_unit_id
- }
- }]
- query = 'WHERE id = :id'
- statement = dfp.FilterStatement(query, values)
-
- # Get ad units by statement.
- response = inventory_service.getAdUnitsByStatement(
- statement.ToStatement())
-
- # Add the size 468x60 to the ad unit.
- ad_unit_size = {
- 'size': {
- 'width': '468',
- 'height': '60'
- },
- 'environmentType': 'BROWSER'
- }
-
- if 'results' in response:
- updated_ad_units = []
- for ad_unit in response['results']:
- if 'adUnitSizes' not in ad_unit:
- ad_unit['adUnitSizes'] = []
- ad_unit['adUnitSizes'].append(ad_unit_size)
- updated_ad_units.append(ad_unit)
-
- # Update ad unit on the server.
- ad_units = inventory_service.updateAdUnits(updated_ad_units)
-
- # Display results.
- for ad_unit in ad_units:
- ad_unit_sizes = ['{%s x %s}' % (size['size']['width'],
- size['size']['height'])
- for size in ad_unit['adUnitSizes']]
- print ('Ad unit with ID \'%s\', name \'%s\', and sizes [%s] was updated'
- % (ad_unit['id'], ad_unit['name'], ','.join(ad_unit_sizes)))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, AD_UNIT_ID)
diff --git a/examples/dfp/v201408/label_service/__init__.py b/examples/dfp/v201408/label_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201408/label_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201408/label_service/create_labels.py b/examples/dfp/v201408/label_service/create_labels.py
deleted file mode 100755
index 96ef8d62..00000000
--- a/examples/dfp/v201408/label_service/create_labels.py
+++ /dev/null
@@ -1,56 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new labels.
-
-To determine which labels exist, run get_all_labels.py. This feature is only
-available to DFP premium solution networks."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- label_service = client.GetService('LabelService', version='v201408')
-
- # Create label objects.
- labels = []
- for _ in xrange(5):
- label = {
- 'name': 'Label #%s' % uuid.uuid4(),
- 'isActive': 'true',
- 'types': ['COMPETITIVE_EXCLUSION']
- }
- labels.append(label)
-
- # Add Labels.
- labels = label_service.createLabels(labels)
-
- # Display results.
- for label in labels:
- print ('Label with id \'%s\', name \'%s\', and types {%s} was found.'
- % (label['id'], label['name'], ','.join(label['types'])))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/label_service/deactivate_labels.py b/examples/dfp/v201408/label_service/deactivate_labels.py
deleted file mode 100755
index 7a2ebc2e..00000000
--- a/examples/dfp/v201408/label_service/deactivate_labels.py
+++ /dev/null
@@ -1,71 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example deactivates all active Labels.
-
-To determine which labels exist, run get_all_labels.py. This feature is only
-available to DFP premium solution networks."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- label_service = client.GetService('LabelService', version='v201408')
-
- # Create query.
- values = [{
- 'key': 'isActive',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'true'
- }
- }]
- query = 'WHERE isActive = :isActive'
- statement = dfp.FilterStatement(query, values)
-
- labels_deactivated = 0
-
- # Get labels by statement.
- while True:
- response = label_service.getLabelsByStatement(statement.ToStatement())
- if 'results' in response:
- for label in response['results']:
- print ('Label with id \'%s\' and name \'%s\' will be '
- 'deactivated.' % (label['id'], label['name']))
- # Perform action.
- result = label_service.performLabelAction(
- {'xsi_type': 'DeactivateLabels'}, statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- labels_deactivated += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Display results.
- if labels_deactivated > 0:
- print 'Number of labels deactivated: %s' % labels_deactivated
- else:
- print 'No labels were deactivated.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/label_service/get_all_labels.py b/examples/dfp/v201408/label_service/get_all_labels.py
deleted file mode 100755
index 9faf62ba..00000000
--- a/examples/dfp/v201408/label_service/get_all_labels.py
+++ /dev/null
@@ -1,54 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all labels.
-
-To create labels, run create_labels.py. This feature is only available to DFP
-premium solution networks."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- label_service = client.GetService('LabelService', version='v201408')
-
- # Create statement to get all labels
- statement = dfp.FilterStatement()
-
- # Get labels by statement.
- while True:
- response = label_service.getLabelsByStatement(statement.ToStatement())
- if 'results' in response:
- # Display results.
- for label in response['results']:
- print ('Label with id \'%s\' and name \'%s\' was found.'
- % (label['id'], label['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/label_service/get_labels_by_statement.py b/examples/dfp/v201408/label_service/get_labels_by_statement.py
deleted file mode 100755
index 5d084442..00000000
--- a/examples/dfp/v201408/label_service/get_labels_by_statement.py
+++ /dev/null
@@ -1,55 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all labels ordered by name.
-
-To create a label, run create_label.py. This feature is only available to DFP
-premium solution networks.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- label_service = client.GetService('LabelService', version='v201408')
-
- # Create statement to get all labels
- statement = dfp.FilterStatement('ORDER BY name')
-
- # Get labels by statement.
- while True:
- response = label_service.getLabelsByStatement(statement.ToStatement())
- if 'results' in response:
- # Display results.
- for label in response['results']:
- print ('Label with id \'%s\' and name \'%s\' was found.'
- % (label['id'], label['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/label_service/update_labels.py b/examples/dfp/v201408/label_service/update_labels.py
deleted file mode 100755
index 1873c083..00000000
--- a/examples/dfp/v201408/label_service/update_labels.py
+++ /dev/null
@@ -1,71 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates the description of a single label.
-
-To determine which labels exist, run get_all_labels.py. This feature is only
-available to DFP premium solution networks."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-LABEL_ID = 'INSERT_LABEL_ID_HERE'
-
-
-def main(client, label_id):
- # Initialize appropriate service.
- label_service = client.GetService('LabelService', version='v201408')
-
- # Create a statement to select only active labels.
- values = [
- {
- 'key': 'labelId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': label_id
- }
- }
- ]
- query = 'WHERE id = :labelId'
- statement = dfp.FilterStatement(query, values)
-
- # Get labels by filter.
- response = label_service.getLabelsByStatement(statement.ToStatement())
-
- if 'results' in response:
- # Update each local label object by changing the description.
- updated_labels = []
- for label in response['results']:
- label['description'] = 'These labels are updated.'
- updated_labels.append(label)
-
- # Update labels remotely.
- labels = label_service.updateLabels(updated_labels)
-
- for label in labels:
- print ('Label with id \'%s\' and name \'%s\' was updated.'
- % (label['id'], label['name']))
- else:
- print 'No labels found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, LABEL_ID)
-
diff --git a/examples/dfp/v201408/line_item_creative_association_service/__init__.py b/examples/dfp/v201408/line_item_creative_association_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201408/line_item_creative_association_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201408/line_item_creative_association_service/create_licas.py b/examples/dfp/v201408/line_item_creative_association_service/create_licas.py
deleted file mode 100755
index 283012e1..00000000
--- a/examples/dfp/v201408/line_item_creative_association_service/create_licas.py
+++ /dev/null
@@ -1,58 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new line item creative associations (LICAs) for an
-existing line item and a set of creative ids.
-
-To determine which LICAs exist, run get_all_licas.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the line item ID and creative IDs to associate.
-LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
-CREATIVE_IDS = ['INSERT_CREATIVE_IDS_HERE']
-
-
-def main(client, line_item_id, creative_ids):
- # Initialize appropriate service.
- lica_service = client.GetService(
- 'LineItemCreativeAssociationService', version='v201408')
-
- licas = []
- for creative_id in creative_ids:
- licas.append({'creativeId': creative_id,
- 'lineItemId': line_item_id})
-
- # Create the LICAs remotely.
- licas = lica_service.createLineItemCreativeAssociations(licas)
-
- # Display results.
- if licas:
- for lica in licas:
- print ('LICA with line item id \'%s\', creative id \'%s\', and '
- 'status \'%s\' was created.' %
- (lica['lineItemId'], lica['creativeId'], lica['status']))
- else:
- print 'No LICAs created.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, LINE_ITEM_ID, CREATIVE_IDS)
diff --git a/examples/dfp/v201408/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201408/line_item_creative_association_service/deactivate_licas.py
deleted file mode 100755
index 8f968236..00000000
--- a/examples/dfp/v201408/line_item_creative_association_service/deactivate_licas.py
+++ /dev/null
@@ -1,84 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example deactivates all LICAs for the line item.
-
-To determine which LICAs exist, run get_all_licas.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the id of the line item in which to deactivate LICAs.
-LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
-
-
-def main(client, line_item_id):
- # Initialize appropriate service.
- lica_service = client.GetService(
- 'LineItemCreativeAssociationService', version='v201408')
-
- # Create query.
- values = [{
- 'key': 'lineItemId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': line_item_id
- }
- }, {
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ACTIVE'
- }
- }]
- query = 'WHERE lineItemId = :lineItemId AND status = :status'
- statement = dfp.FilterStatement(query, values)
-
- num_deactivated_licas = 0
-
- # Get LICAs by statement.
- while True:
- response = lica_service.getLineItemCreativeAssociationsByStatement(
- statement.ToStatement())
- if 'results' in response:
- for lica in response['results']:
- print ('LICA with line item id \'%s\', creative id \'%s\', and status'
- ' \'%s\' will be deactivated.' %
- (lica['lineItemId'], lica['creativeId'], lica['status']))
-
- # Perform action.
- result = lica_service.performLineItemCreativeAssociationAction(
- {'xsi_type': 'DeactivateLineItemCreativeAssociations'},
- statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- num_deactivated_licas += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Display results.
- if num_deactivated_licas > 0:
- print 'Number of LICAs deactivated: %s' % num_deactivated_licas
- else:
- print 'No LICAs were deactivated.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, LINE_ITEM_ID)
diff --git a/examples/dfp/v201408/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201408/line_item_creative_association_service/get_all_licas.py
deleted file mode 100755
index daadf781..00000000
--- a/examples/dfp/v201408/line_item_creative_association_service/get_all_licas.py
+++ /dev/null
@@ -1,58 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all line item creative associations (LICA).
-
-To create LICAs, run create_licas.py or associate_creative_set_to_line_item.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- lica_service = client.GetService(
- 'LineItemCreativeAssociationService', version='v201408')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get line items by statement.
- while True:
- response = lica_service.getLineItemCreativeAssociationsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for lica in response['results']:
- if 'creativeSetId' in lica:
- print ('LICA with line item ID \'%s\', creative set ID \'%s\', and '
- 'status \'%s\' was found.' %
- (lica['lineItemId'], lica['creativeSetId'], lica['status']))
- else:
- print ('LICA with line item ID \'%s\', creative ID \'%s\', and status'
- ' \'%s\' was found.' % (lica['lineItemId'], lica['creativeId'],
- lica['status']))
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/line_item_creative_association_service/get_licas_by_statement.py b/examples/dfp/v201408/line_item_creative_association_service/get_licas_by_statement.py
deleted file mode 100755
index 0d7d5814..00000000
--- a/examples/dfp/v201408/line_item_creative_association_service/get_licas_by_statement.py
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all line item creative associations (LICA) for a given
-line item id.
-
-To create LICAs, run create_licas.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the id of the line item to get LICAs by.
-LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
-
-
-def main(client, line_item_id):
- # Initialize appropriate service.
- lica_service = client.GetService(
- 'LineItemCreativeAssociationService', version='v201408')
-
-# Create statement object to only select LICAs for the given line item id.
- values = [{
- 'key': 'lineItemId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': line_item_id
- }
- }]
- query = 'WHERE lineItemId = :lineItemId'
- statement = dfp.FilterStatement(query, values)
-
- while True:
- # Get LICAs by statement.
- response = lica_service.getLineItemCreativeAssociationsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- # Display results.
- for lica in response['results']:
- print ('LICA with line item id \'%s\', creative id \'%s\', and status '
- '\'%s\' was found.' % (lica['lineItemId'], lica['creativeId'],
- lica['status']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, LINE_ITEM_ID)
diff --git a/examples/dfp/v201408/line_item_creative_association_service/update_licas.py b/examples/dfp/v201408/line_item_creative_association_service/update_licas.py
deleted file mode 100755
index 152d8753..00000000
--- a/examples/dfp/v201408/line_item_creative_association_service/update_licas.py
+++ /dev/null
@@ -1,67 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates the destination URL of all line item creative
-associations (LICA).
-
-To determine which LICAs exist, run get_all_licas.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- lica_service = client.GetService(
- 'LineItemCreativeAssociationService', version='v201408')
-
- # Create statement object to get all LICAs.
- statement = dfp.FilterStatement()
-
- while True:
- # Get LICAs by statement.
- response = lica_service.getLineItemCreativeAssociationsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- # Update each local LICA object by changing its destination URL.
- updated_licas = []
- for lica in response['results']:
- lica['destinationUrl'] = 'http://news.google.com'
- updated_licas.append(lica)
-
- # Update LICAs remotely.
- licas = lica_service.updateLineItemCreativeAssociations(updated_licas)
-
- # Display results.
- for lica in licas:
- print ('LICA with line item id \'%s\', creative id \'%s\', and status '
- '\'%s\' was updated.' % (lica['lineItemId'], lica['creativeId'],
- lica['status']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- if response['totalResultSetSize'] == 0:
- print 'No LICAs found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/line_item_service/__init__.py b/examples/dfp/v201408/line_item_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201408/line_item_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201408/line_item_service/activate_line_items.py b/examples/dfp/v201408/line_item_service/activate_line_items.py
deleted file mode 100755
index 291dedd5..00000000
--- a/examples/dfp/v201408/line_item_service/activate_line_items.py
+++ /dev/null
@@ -1,86 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example activates all line items for the given order.
-
-To be activated, line items need to be in the approved state and have at least
-one creative associated with them. To approve line items, approve the order to
-which they belong by running approve_orders.py. To create LICAs, run
-create_licas.py. To determine which line items exist, run
-get_all_line_items.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the id of the order to get line items from.
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-
-
-def main(client, order_id):
- # Initialize appropriate service.
- line_item_service = client.GetService('LineItemService', version='v201408')
-
- # Create query.
- values = [{
- 'key': 'orderId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': order_id
- }
- }, {
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'NEEDS_CREATIVES'
- }
- }]
- query = 'WHERE orderId = :orderId AND status = :status'
- statement = dfp.FilterStatement(query, values)
-
- line_items_activated = 0
-
- # Get line items by statement.
- while True:
- response = line_item_service.getLineItemsByStatement(
- statement.ToStatement())
- if 'results' in response:
- for line_item in response['results']:
- print ('Line item with id \'%s\', belonging to order id \'%s\', and '
- 'name \'%s\' will be activated.' %
- (line_item['id'], line_item['orderId'], line_item['name']))
-
- # Perform action.
- result = line_item_service.performLineItemAction(
- {'xsi_type': 'ActivateLineItems'}, statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- line_items_activated += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Display results.
- if line_items_activated > 0:
- print 'Number of line items activated: %s' % line_items_activated
- else:
- print 'No line items were activated.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID)
diff --git a/examples/dfp/v201408/line_item_service/create_line_items.py b/examples/dfp/v201408/line_item_service/create_line_items.py
deleted file mode 100755
index 6488b335..00000000
--- a/examples/dfp/v201408/line_item_service/create_line_items.py
+++ /dev/null
@@ -1,172 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new line items.
-
-To determine which line items exist, run get_all_line_items.py. To determine
-which orders exist, run get_all_orders.py. To determine which placements exist,
-run get_all_placements.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-from datetime import date
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set order that the created line item will belong to and add the id of a
-# placement containing ad units to target.
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-TARGETED_PLACEMENT_IDS = ['INSERT_PLACEMENT_IDS_HERE']
-
-
-def main(client, order_id, targeted_placement_ids):
- # Initialize appropriate service.
- line_item_service = client.GetService('LineItemService', version='v201408')
-
- # Create line item objects.
- line_items = []
- for i in xrange(5):
- line_item = {
- 'name': 'Line item #%s' % uuid.uuid4(),
- 'orderId': order_id,
- 'targeting': {
- 'inventoryTargeting': {
- 'targetedPlacementIds': targeted_placement_ids
- },
- 'geoTargeting': {
- 'targetedLocations': [
- {
- 'id': '2840',
- 'displayName': 'US'
- },
- {
- 'id': '20133',
- 'displayName': 'Geneva'
- },
- {
- 'id': '9000093',
- 'displayName': 'B3P',
- }
- ],
- 'excludedLocations': [
- {
- 'id': '1016367',
- 'displayName': 'Chicago',
- },
- {
- 'id': '200501',
- 'displayName': 'New York NY'
- }
- ]
- },
- 'dayPartTargeting': {
- 'dayParts': [
- {
- 'dayOfWeek': 'SATURDAY',
- 'startTime': {
- 'hour': '0',
- 'minute': 'ZERO'
- },
- 'endTime': {
- 'hour': '24',
- 'minute': 'ZERO'
- }
- },
- {
- 'dayOfWeek': 'SUNDAY',
- 'startTime': {
- 'hour': '0',
- 'minute': 'ZERO'
- },
- 'endTime': {
- 'hour': '24',
- 'minute': 'ZERO'
- }
- }
- ],
- 'timeZone': 'BROWSER'
- },
- 'userDomainTargeting': {
- 'domains': ['usa.gov'],
- 'targeted': 'false'
- },
- 'technologyTargeting': {
- 'browserTargeting': {
- 'browsers': [{'id': '500072'}],
- 'isTargeted': 'true'
- }
- }
- },
- 'creativePlaceholders': [
- {
- 'size': {
- 'width': '300',
- 'height': '250'
- }
- },
- {
- 'size': {
- 'width': '120',
- 'height': '600'
- }
- }
- ],
- 'startDateTimeType': 'IMMEDIATELY',
- 'lineItemType': 'STANDARD',
- 'endDateTime': {
- 'date': {
- 'year': str(date.today().year + 1),
- 'month': '9',
- 'day': '30'
- },
- 'hour': '0',
- 'minute': '0',
- 'second': '0'
- },
- 'costType': 'CPM',
- 'costPerUnit': {
- 'currencyCode': 'USD',
- 'microAmount': '2000000'
- },
- 'primaryGoal': {
- 'units': '50',
- 'unitType': 'IMPRESSIONS',
- 'goalType': 'LIFETIME'
- },
- 'contractedUnitsBought': '100',
- 'creativeRotationType': 'EVEN',
- 'discountType': 'PERCENTAGE',
- 'allowOverbook': 'true'
- }
- line_items.append(line_item)
-
- # Add line items.
- line_items = line_item_service.createLineItems(line_items)
-
- # Display results.
- for line_item in line_items:
- print ('Line item with id \'%s\', belonging to order id \'%s\', and named '
- '\'%s\' was created.' % (line_item['id'], line_item['orderId'],
- line_item['name']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID, TARGETED_PLACEMENT_IDS)
-
diff --git a/examples/dfp/v201408/line_item_service/create_video_line_item.py b/examples/dfp/v201408/line_item_service/create_video_line_item.py
deleted file mode 100755
index da01d296..00000000
--- a/examples/dfp/v201408/line_item_service/create_video_line_item.py
+++ /dev/null
@@ -1,151 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates a new line item to serve to video content.
-
-This feature is only available to DFP premium solution networks. To determine
-which line items exist, run get_all_line_items.py. To determine which orders
-exist, run get_all_orders.py. To create a video ad unit, run
-create_video_ad_unit.py. To create criteria for categories, run
-create_custom_targeting_keys_and_values.py"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-from datetime import date
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set order that all created line item will belong to and the video ad unit id
-# to target.
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-TARGETED_VIDEO_AD_UNIT_ID = 'INSERT_TARGETED_VIDEO_AD_UNIT_ID_HERE'
-
-# Set the custom targeting key ID and value ID representing the metadata on the
-# content to target. This would typically be a key representing a 'genre' and
-# a value representing something like 'comedy'.
-CONTENT_CUSTOM_TARGETING_KEY_ID = 'INSERT_CONTENT_CUSTOM_TARGETING_KEY_ID_HERE'
-CONTENT_CUSTOM_TARGETING_VALUE_ID = \
- 'INSERT_CONTENT_CUSTOM_TARGETING_VALUE_ID_HERE'
-
-
-def main(client, order_id, targeted_video_ad_unit_id,
- content_custom_targeting_key_id, content_custom_targeting_value_id):
- # Initialize appropriate service.
- line_item_service = client.GetService('LineItemService', version='v201408')
-
- # create custom criteria for the content metadata targeting.
- custom_criteria = {
- 'xsi_type': 'CustomCriteria',
- 'keyId': content_custom_targeting_key_id,
- 'valueIds': [content_custom_targeting_value_id],
- 'operator': 'IS'
- }
-
- # Create the custom criteria set.
- top_set = {
- 'xsi_type': 'CustomCriteriaSet',
- 'logicalOperator': 'OR',
- 'children': [custom_criteria]
- }
-
- # Create line item object.
- line_item = {
- 'name': 'Line item #%s' % uuid.uuid4(),
- 'orderId': order_id,
- 'targeting': {
- 'customTargeting': top_set,
- 'inventoryTargeting': {
- 'targetedAdUnits': [{'adUnitId': targeted_video_ad_unit_id,
- 'includeDescendants': 'true'}]
- },
- 'videoPositionTargeting': {
- 'targetedPositions': [
- {
- 'videoPosition': {
- 'positionType': 'PREROLL'
- }
- }
- ]
- }
- },
- 'creativePlaceholders': [
- {
- 'size': {
- 'width': '400',
- 'height': '300'
- },
- 'companions': [
- {
- 'size': {
- 'width': '300',
- 'height': '250'
- },
- },
- {
- 'size': {
- 'width': '728',
- 'height': '90'
- },
- }
- ]
- }
- ],
- 'environmentType': 'VIDEO_PLAYER',
- 'companionDeliveryOption': 'OPTIONAL',
- 'startDateTimeType': 'IMMEDIATELY',
- 'lineItemType': 'SPONSORSHIP',
- 'endDateTime': {
- 'date': {
- 'year': str(date.today().year + 1),
- 'month': '9',
- 'day': '30'
- },
- 'hour': '0',
- 'minute': '0',
- 'second': '0'
- },
- 'costType': 'CPM',
- 'costPerUnit': {
- 'currencyCode': 'USD',
- 'microAmount': '2000000'
- },
- 'primaryGoal': {
- 'units': '50',
- 'unitType': 'IMPRESSIONS',
- 'goalType': 'DAILY'
- },
- 'contractedUnitsBought': '100',
- 'creativeRotationType': 'OPTIMIZED',
- 'discountType': 'PERCENTAGE',
- 'allowOverbook': 'true'
- }
-
- # Add line item.
- line_item = line_item_service.createLineItem(line_item)
-
- # Display results.
- print ('Video line item with id \'%s\', belonging to order id \'%s\', and '
- 'named \'%s\' was created.' % (line_item['id'], line_item['orderId'],
- line_item['name']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID, TARGETED_VIDEO_AD_UNIT_ID,
- CONTENT_CUSTOM_TARGETING_KEY_ID, CONTENT_CUSTOM_TARGETING_VALUE_ID)
diff --git a/examples/dfp/v201408/line_item_service/get_all_line_items.py b/examples/dfp/v201408/line_item_service/get_all_line_items.py
deleted file mode 100755
index c1827973..00000000
--- a/examples/dfp/v201408/line_item_service/get_all_line_items.py
+++ /dev/null
@@ -1,54 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all line items.
-
-To create line items, run create_line_items.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- line_item_service = client.GetService('LineItemService', version='v201408')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get line items by statement.
- while True:
- response = line_item_service.getLineItemsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for line_item in response['results']:
- print ('Line item with id \'%s\', belonging to order id \'%s\', and '
- 'named \'%s\' was found.' %
- (line_item['id'], line_item['orderId'], line_item['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/line_item_service/get_line_items_by_statement.py b/examples/dfp/v201408/line_item_service/get_line_items_by_statement.py
deleted file mode 100755
index 805ff404..00000000
--- a/examples/dfp/v201408/line_item_service/get_line_items_by_statement.py
+++ /dev/null
@@ -1,76 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all line items that need creatives for the given
-order.
-
-To create line items, run create_line_items.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the id of the order to get line items from.
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-
-
-def main(client, order_id):
- # Initialize appropriate service.
- line_item_service = client.GetService('LineItemService', version='v201408')
-
- # Create statement object to only select line items that need creatives from a
- # given order.
- values = [{
- 'key': 'orderId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': order_id
- }
- }, {
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'NEEDS_CREATIVES'
- }
- }]
- query = 'WHERE orderId = :orderId AND status = :status'
- statement = dfp.FilterStatement(query, values)
-
- while True:
- # Get line items by statement.
- response = line_item_service.getLineItemsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- # Display results.
- for line_item in response['results']:
- print ('Line item with id \'%s\', belonging to order id \'%s\', and '
- 'named \'%s\' was found.' % (line_item['id'],
- line_item['orderId'],
- line_item['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID)
diff --git a/examples/dfp/v201408/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201408/line_item_service/get_recently_updated_line_items.py
deleted file mode 100755
index 712ecb74..00000000
--- a/examples/dfp/v201408/line_item_service/get_recently_updated_line_items.py
+++ /dev/null
@@ -1,76 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example shows how to get recently updated line items.
-
-To create line items, run create_line_items.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import datetime
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-
-
-def main(client, order_id):
- # Initialize appropriate service.
- line_item_service = client.GetService('LineItemService', version='v201408')
-
- # Create statement object to only select line items belonging to the order and
- # have been modified in the last 3 days.
- three_days_ago = datetime.date.today() - datetime.timedelta(days=3)
- values = [{
- 'key': 'dateTimeString',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': three_days_ago.strftime('%Y-%m-%dT%H:%M:%S')
- }
- }, {
- 'key': 'orderId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': order_id
- }
- }]
- query = 'WHERE lastModifiedDateTime >= :dateTimeString AND orderId = :orderId'
- statement = dfp.FilterStatement(query, values)
-
- while True:
- # Get line items by statement.
- response = line_item_service.getLineItemsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- # Display results.
- for line_item in response['results']:
- print ('Line item with id \'%s\', belonging to order id \'%s\', and '
- 'named \'%s\' was found.' % (line_item['id'],
- line_item['orderId'],
- line_item['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID)
diff --git a/examples/dfp/v201408/line_item_service/target_custom_criteria.py b/examples/dfp/v201408/line_item_service/target_custom_criteria.py
deleted file mode 100755
index 3e09c5b5..00000000
--- a/examples/dfp/v201408/line_item_service/target_custom_criteria.py
+++ /dev/null
@@ -1,115 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates a line item to add custom criteria targeting.
-
-To determine which line items exist, run get_all_line_items.py. To determine
-which custom targeting keys and values exist, run
-get_all_custom_targeting_keys_and_values.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import pprint
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
-KEY_ID1 = 'INSERT_TARGETING_KEY_ID_HERE'
-KEY_ID2 = 'INSERT_TARGETING_KEY_ID_HERE'
-KEY_ID3 = 'INSERT_TARGETING_KEY_ID_HERE'
-
-VALUE_ID1 = 'INSERT_TARGETING_VALUE_ID_HERE'
-VALUE_ID2 = 'INSERT_TARGETING_VALUE_ID_HERE'
-VALUE_ID3 = 'INSERT_TARGETING_VALUE_ID_HERE'
-
-
-def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2,
- value_id3):
- # Initialize appropriate service.
- line_item_service = client.GetService('LineItemService', version='v201408')
-
- # create custom criterias
- custom_criteria1 = {
- 'xsi_type': 'CustomCriteria',
- 'keyId': key_id1,
- 'valueIds': [value_id1],
- 'operator': 'IS'
- }
-
- custom_criteria2 = {
- 'xsi_type': 'CustomCriteria',
- 'keyId': key_id2,
- 'valueIds': [value_id2],
- 'operator': 'IS_NOT'
- }
-
- custom_criteria3 = {
- 'xsi_type': 'CustomCriteria',
- 'keyId': key_id3,
- 'valueIds': [value_id3],
- 'operator': 'IS'
- }
-
- # Create the custom criteria set that will resemble:
- # (custom_criteria1.key == custom_criteria1.value OR
- # (custom_criteria2.key != custom_criteria2.value AND
- # custom_criteria13.key == custom_criteria3.value))
- sub_set = {
- 'xsi_type': 'CustomCriteriaSet',
- 'logicalOperator': 'AND',
- 'children': [custom_criteria2, custom_criteria3]
- }
-
- top_set = {
- 'xsi_type': 'CustomCriteriaSet',
- 'logicalOperator': 'OR',
- 'children': [custom_criteria1, sub_set]
- }
-
- # Create statement to get the line item
- values = [{
- 'key': 'lineItemId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': line_item_id
- }
- }]
- query = 'WHERE id = :lineItemId'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Set custom criteria targeting on the line item.
- line_item = line_item_service.getLineItemsByStatement(
- statement.ToStatement())['results'][0]
- line_item['targeting']['customTargeting'] = top_set
-
- # Update line item.
- line_item = line_item_service.updateLineItems([line_item])[0]
-
- # Display results.
- if line_item:
- print ('Line item with id \'%s\' updated with custom criteria targeting:'
- % line_item['id'])
- pprint.pprint(line_item['targeting']['customTargeting'])
- else:
- print 'No line items were updated.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, LINE_ITEM_ID, KEY_ID1, KEY_ID2, KEY_ID3, VALUE_ID1,
- VALUE_ID2, VALUE_ID3)
diff --git a/examples/dfp/v201408/line_item_service/update_line_items.py b/examples/dfp/v201408/line_item_service/update_line_items.py
deleted file mode 100755
index 18243fb3..00000000
--- a/examples/dfp/v201408/line_item_service/update_line_items.py
+++ /dev/null
@@ -1,83 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates the delivery rate of all line items in an order.
-
-To determine which line items exist, run get_all_line_items.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set id of the order to get line items from.
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-
-
-def main(client, order_id):
- # Initialize appropriate service.
- line_item_service = client.GetService('LineItemService', version='v201408')
-
- # Create statement object to only select line items with even delivery rates.
- values = [{
- 'key': 'deliveryRateType',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'EVENLY'
- }
- }, {
- 'key': 'orderId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': order_id
- }
- }]
-
- query = 'WHERE deliveryRateType = :deliveryRateType and orderId = :orderId'
- statement = dfp.FilterStatement(query, values, 500)
-
- # Get line items by statement.
- response = line_item_service.getLineItemsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- # Update each local line item by changing its delivery rate type.
- updated_line_items = []
- for line_item in response['results']:
- if not line_item['isArchived']:
- line_item['deliveryRateType'] = 'AS_FAST_AS_POSSIBLE'
- updated_line_items.append(line_item)
-
- # Update line items remotely.
- line_items = line_item_service.updateLineItems(updated_line_items)
-
- # Display results.
- if line_items:
- for line_item in line_items:
- print ('Line item with id \'%s\', belonging to order id \'%s\', named '
- '\'%s\', and delivery rate \'%s\' was updated.'
- % (line_item['id'], line_item['orderId'], line_item['name'],
- line_item['deliveryRateType']))
- else:
- print 'No line items were updated.'
- else:
- print 'No line items found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID)
diff --git a/examples/dfp/v201408/network_service/__init__.py b/examples/dfp/v201408/network_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201408/network_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201408/network_service/get_all_networks.py b/examples/dfp/v201408/network_service/get_all_networks.py
deleted file mode 100755
index df4beace..00000000
--- a/examples/dfp/v201408/network_service/get_all_networks.py
+++ /dev/null
@@ -1,46 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all networks that you have access to with the current login
-credentials.
-
-A networkCode should be left out for this request."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- network_service = client.GetService('NetworkService', version='v201408')
-
- # Get all networks that you have access to with the current login credentials.
- networks = network_service.getAllNetworks()
-
- # Display results.
- for network in networks:
- print ('Network with network code \'%s\' and display name \'%s\' was found.'
- % (network['networkCode'], network['displayName']))
-
- print '\nNumber of results found: %s' % len(networks)
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/network_service/get_current_network.py b/examples/dfp/v201408/network_service/get_current_network.py
deleted file mode 100755
index e5be7cc4..00000000
--- a/examples/dfp/v201408/network_service/get_current_network.py
+++ /dev/null
@@ -1,40 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets the current network that you can make requests against."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- network_service = client.GetService('NetworkService', version='v201408')
-
- # Get the current network.
- network = network_service.getCurrentNetwork()
-
- # Display results.
- print ('Current network has network code \'%s\' and display name \'%s\'.'
- % (network['networkCode'], network['displayName']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/network_service/make_test_network.py b/examples/dfp/v201408/network_service/make_test_network.py
deleted file mode 100755
index e33f56a4..00000000
--- a/examples/dfp/v201408/network_service/make_test_network.py
+++ /dev/null
@@ -1,53 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates a test network.
-
-You do not need to have a DFP account to run this example, but you do need to
-have a Google account (created at http://www.google.com/accounts/newaccount
-if you currently don't have one) that is not associated with any other DFP test
-networks. Once this network is created, you can supply the network code in your
-settings to make calls to other services.
-
-Alternatively, if you do not wish to run this example, you can create a test
-network at:
-https://dfp-playground.appspot.com
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- network_service = client.GetService('NetworkService', version='v201408')
-
- # Create a test network.
- network = network_service.MakeTestNetwork()
-
- # Display results.
- print ('Test network with network code \'%s\' and display name \'%s\' '
- 'created.' % (network['networkCode'], network['displayName']))
- print ('You may now sign in at http://www.google.com/dfp/main?networkCode=%s'
- % network['networkCode'])
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/order_service/__init__.py b/examples/dfp/v201408/order_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201408/order_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201408/order_service/approve_orders.py b/examples/dfp/v201408/order_service/approve_orders.py
deleted file mode 100755
index fa02cd9d..00000000
--- a/examples/dfp/v201408/order_service/approve_orders.py
+++ /dev/null
@@ -1,75 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example approves all eligible draft and pending orders.
-
-To determine which orders exist, run get_all_orders.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import datetime
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- order_service = client.GetService('OrderService', version='v201408')
-
- # Create query.
- values = [{
- 'key': 'today',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': datetime.date.today().strftime('%Y-%m-%dT%H:%M:%S')
- }
- }]
- query = ('WHERE status in (\'DRAFT\', \'PENDING_APPROVAL\')'
- ' AND endDateTime >= :today AND isArchived = FALSE')
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
- orders_approved = 0
-
- # Get orders by statement.
- while True:
- response = order_service.getOrdersByStatement(statement.ToStatement())
- if 'results' in response:
- # Display results.
- for order in response['results']:
- print ('Order with id \'%s\', name \'%s\', and status \'%s\' will be '
- 'approved.' % (order['id'], order['name'], order['status']))
- # Perform action.
- result = order_service.performOrderAction(
- {'xsi_type': 'ApproveOrders'}, statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- orders_approved += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Display results.
- if orders_approved > 0:
- print 'Number of orders approved: %s' % orders_approved
- else:
- print 'No orders were approved.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/order_service/create_orders.py b/examples/dfp/v201408/order_service/create_orders.py
deleted file mode 100755
index 9d37f3d4..00000000
--- a/examples/dfp/v201408/order_service/create_orders.py
+++ /dev/null
@@ -1,60 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new orders.
-
-To determine which orders exist, run get_all_orders.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
-SALESPERSON_ID = 'INSERT_SALESPERSON_ID_HERE'
-TRAFFICKER_ID = 'INSERT_TRAFFICKER_ID_HERE'
-
-
-def main(client, company_id, salesperson_id, trafficker_id):
- # Initialize appropriate service.
- order_service = client.GetService('OrderService', version='v201408')
-
- # Create order objects.
- orders = []
- for i in xrange(5):
- order = {
- 'name': 'Order #%s' % uuid.uuid4(),
- 'advertiserId': company_id,
- 'salespersonId': salesperson_id,
- 'traffickerId': trafficker_id
- }
- orders.append(order)
-
- # Add orders.
- orders = order_service.createOrders(orders)
-
- # Display results.
- for order in orders:
- print ('Order with id \'%s\' and name \'%s\' was created.'
- % (order['id'], order['name']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, COMPANY_ID, SALESPERSON_ID, TRAFFICKER_ID)
diff --git a/examples/dfp/v201408/order_service/get_all_orders.py b/examples/dfp/v201408/order_service/get_all_orders.py
deleted file mode 100755
index a3de741d..00000000
--- a/examples/dfp/v201408/order_service/get_all_orders.py
+++ /dev/null
@@ -1,54 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all orders.
-
-To create orders, run create_orders.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- order_service = client.GetService('OrderService', version='v201408')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get orders by statement.
- while True:
- response = order_service.getOrdersByStatement(statement.ToStatement())
- if 'results' in response:
- # Display results.
- for order in response['results']:
- print ('Order with id \'%s\', name \'%s\', and advertiser id \'%s\' was'
- ' found.' % (order['id'], order['name'], order['advertiserId']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/order_service/get_orders_by_statement.py b/examples/dfp/v201408/order_service/get_orders_by_statement.py
deleted file mode 100755
index b156a8c8..00000000
--- a/examples/dfp/v201408/order_service/get_orders_by_statement.py
+++ /dev/null
@@ -1,63 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets an order by an ID.
-
-To create orders, run create_orders.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set id of the order to get.
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-
-
-def main(client, order_id):
- # Initialize appropriate service.
- order_service = client.GetService('OrderService', version='v201408')
-
- # Create statement object to select a single order by an ID.
- values = [{
- 'key': 'orderId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': order_id
- }
- }]
- query = 'WHERE id = :orderId'
-
- statement = dfp.FilterStatement(query, values)
-
- # Get orders by statement.
- response = order_service.getOrdersByStatement(statement.ToStatement())
- orders = []
- if 'results' in response:
- orders = response['results']
-
- # Display results.
- for order in orders:
- print ('Order with id \'%s\' name \'%s\' was found.'
- % (order['id'], order['name']))
-
- print '\nNumber of results found: %s' % len(orders)
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID)
diff --git a/examples/dfp/v201408/order_service/update_orders.py b/examples/dfp/v201408/order_service/update_orders.py
deleted file mode 100755
index 5e8d346a..00000000
--- a/examples/dfp/v201408/order_service/update_orders.py
+++ /dev/null
@@ -1,77 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates the notes of a single order specified by ID.
-
-To determine which orders exist, run get_all_orders.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-
-
-def main(client, order_id):
- # Initialize appropriate service.
- order_service = client.GetService('OrderService', version='v201408')
-
- # Create statement object to select a single order by an ID.
- values = [{
- 'key': 'orderId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': order_id
- }
- }]
- query = 'WHERE id = :orderId'
-
- statement = dfp.FilterStatement(query, values)
-
- # Get orders by statement.
- response = order_service.getOrdersByStatement(statement.ToStatement())
-
- if 'results' in response:
- # Update each local order object by changing its notes.
- updated_orders = []
- for order in response['results']:
- # Archived orders cannot be updated.
- if not order['isArchived']:
- order['notes'] = 'Spoke to advertiser. All is well.'
- updated_orders.append(order)
-
- # Update orders remotely.
- orders = order_service.updateOrders(updated_orders)
-
- # Display results.
- if orders:
- for order in orders:
- print ('Order with id \'%s\', name \'%s\', advertiser id \'%s\', and '
- 'notes \'%s\' was updated.'
- % (order['id'], order['name'], order['advertiserId'],
- order['notes']))
- else:
- print 'No orders were updated.'
- else:
- print 'No orders found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID)
-
diff --git a/examples/dfp/v201408/placement_service/create_placements.py b/examples/dfp/v201408/placement_service/create_placements.py
deleted file mode 100755
index d9346747..00000000
--- a/examples/dfp/v201408/placement_service/create_placements.py
+++ /dev/null
@@ -1,110 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new placements for various ad unit sizes.
-
-To determine which placements exist, run get_all_placements.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- placement_service = client.GetService('PlacementService', version='v201408')
- inventory_service = client.GetService('InventoryService', version='v201408')
-
- # Create placement object to store medium rectangle ad units.
- medium_rectangle_ad_unit_placement = {
- 'name': 'Medium rectangle AdUnit Placement #%s' % uuid.uuid4(),
- 'description': 'Contains ad units that hold creatives of size 300x250',
- 'targetedAdUnitIds': []
- }
-
- # Create placement object to store skyscraper ad units.
- skyscraper_ad_unit_placement = {
- 'name': 'Skyscraper AdUnit Placement #%s' % uuid.uuid4(),
- 'description': 'Contains ad units that hold creatives of size 120x600',
- 'targetedAdUnitIds': []
- }
-
- # Create placement object to store banner ad units.
- banner_ad_unit_placement = {
- 'name': 'Banner AdUnit Placement #%s' % uuid.uuid4(),
- 'description': 'Contains ad units that hold creatives of size 468x60',
- 'targetedAdUnitIds': []
- }
-
- placement_list = []
-
- # Create statement to get all the ad units.
- statement = dfp.FilterStatement()
-
- while True:
- response = inventory_service.getAdUnitsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- # Separate the ad units by size.
- for ad_unit in response['results']:
- if 'adUnitSizes' in ad_unit:
- for ad_unit_size in ad_unit['adUnitSizes']:
- size = ad_unit_size['size']
- if size['width'] == '300' and size['height'] == '250':
- medium_rectangle_ad_unit_placement['targetedAdUnitIds'].append(
- ad_unit['id'])
- elif size['width'] == '120' and size['height'] == '600':
- skyscraper_ad_unit_placement['targetedAdUnitIds'].append(
- ad_unit['id'])
- elif size['width'] == '468' and size['height'] == '60':
- banner_ad_unit_placement['targetedAdUnitIds'].append(
- ad_unit['id'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Only create placements with one or more ad unit.
- if medium_rectangle_ad_unit_placement['targetedAdUnitIds']:
- placement_list.append(medium_rectangle_ad_unit_placement)
-
- if skyscraper_ad_unit_placement['targetedAdUnitIds']:
- placement_list.append(skyscraper_ad_unit_placement)
-
- if banner_ad_unit_placement['targetedAdUnitIds']:
- placement_list.append(banner_ad_unit_placement)
-
- # Add placements.
- placements = placement_service.createPlacements(placement_list)
-
- # Display results.
- for placement in placements:
- ad_unit_ids = ''
- if 'targetedAdUnitIds' in placement:
- ad_unit_ids = ', '.join(placement['targetedAdUnitIds'])
- print ('A Placement with ID \'%s\', name \'%s\', and containing ad units '
- '{%s} was created.' % (placement['id'], placement['name'],
- ad_unit_ids))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/placement_service/deactivate_placements.py b/examples/dfp/v201408/placement_service/deactivate_placements.py
deleted file mode 100755
index d173b2a2..00000000
--- a/examples/dfp/v201408/placement_service/deactivate_placements.py
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example deactivates all active placements.
-
-To determine which placements exist, run get_all_placements.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-PLACEMENT_ID = 'INSERT_PLACEMENT_ID_HERE'
-
-
-def main(client, placement_id):
- # Initialize appropriate service.
- placement_service = client.GetService('PlacementService', version='v201408')
-
- # Create query.
- values = [{
- 'key': 'placementId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': placement_id
- }
- }]
- query = 'WHERE id = :placementId'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get placements by statement.
- placements = placement_service.getPlacementsByStatement(
- statement.ToStatement())
-
- for placement in placements:
- print ('Placement with id \'%s\', name \'%s\', and status \'%s\' will be '
- 'deactivated.' % (placement['id'], placement['name'],
- placement['status']))
-
- # Perform action.
- result = placement_service.performPlacementAction(
- {'xsi_type': 'DeactivatePlacements'}, statement.ToStatement())
-
- # Display results.
- if result and int(result['numChanges']) > 0:
- print 'Number of placements deactivated: %s' % result['numChanges']
- else:
- print 'No placements were deactivated.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PLACEMENT_ID)
diff --git a/examples/dfp/v201408/placement_service/get_all_placements.py b/examples/dfp/v201408/placement_service/get_all_placements.py
deleted file mode 100755
index 833a5c66..00000000
--- a/examples/dfp/v201408/placement_service/get_all_placements.py
+++ /dev/null
@@ -1,54 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all placements.
-
-To create placements, run create_placement.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- placement_service = client.GetService('PlacementService', version='v201408')
-
- # Create statement to fetch all placements.
- statement = dfp.FilterStatement()
-
- # Get placements by statement.
- while True:
- response = placement_service.getPlacementsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for placement in response['results']:
- print ('Placement with id \'%s\' and name \'%s\' was found.'
- % (placement['id'], placement['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/placement_service/get_placements_by_statement.py b/examples/dfp/v201408/placement_service/get_placements_by_statement.py
deleted file mode 100755
index 0189c544..00000000
--- a/examples/dfp/v201408/placement_service/get_placements_by_statement.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all active placements by using a statement.
-
-To create a placement, run create_placements.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- placement_service = client.GetService('PlacementService', version='v201408')
-
- # Create a statement to only select active placements.
- values = [{
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ACTIVE'
- }
- }]
- query = 'WHERE status = :status'
- statement = dfp.FilterStatement(query, values)
-
- # Get placements by statement.
- while True:
- response = placement_service.getPlacementsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for placement in response['results']:
- print ('Placement with id \'%s\' and name \'%s\' was found.'
- % (placement['id'], placement['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/placement_service/update_placements.py b/examples/dfp/v201408/placement_service/update_placements.py
deleted file mode 100755
index 7f196084..00000000
--- a/examples/dfp/v201408/placement_service/update_placements.py
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates a single placement to allow for AdSense targeting.
-
-To determine which placements exist, run get_all_placements.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-PLACEMENT_ID = 'INSERT_PLACEMENT_ID_HERE'
-
-
-def main(client, placement_id):
- # Initialize appropriate service.
- placement_service = client.GetService('PlacementService', version='v201408')
-# Create query.
- values = [{
- 'key': 'placementId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': placement_id
- }
- }]
- query = 'WHERE id = :placementId'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get placements by statement.
- placements = placement_service.getPlacementsByStatement(
- statement.ToStatement())
-
- for placement in placements:
- if not placement['targetingDescription']:
- placement['targetingDescription'] = 'Generic description'
- placement['targetingAdLocation'] = 'All images on sports pages.'
- placement['targetingSiteName'] = 'http://code.google.com'
- placement['isAdSenseTargetingEnabled'] = 'true'
-
- # Update placements remotely.
- placements = placement_service.updatePlacements(placements)
-
- for placement in placements:
- print ('Placement with id \'%s\', name \'%s\', and AdSense targeting '
- 'enabled \'%s\' was updated.'
- % (placement['id'], placement['name'],
- placement['isAdSenseTargetingEnabled']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PLACEMENT_ID)
diff --git a/examples/dfp/v201408/publisher_query_language_service/__init__.py b/examples/dfp/v201408/publisher_query_language_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201408/publisher_query_language_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201408/publisher_query_language_service/fetch_match_tables.py b/examples/dfp/v201408/publisher_query_language_service/fetch_match_tables.py
deleted file mode 100755
index 18f20806..00000000
--- a/examples/dfp/v201408/publisher_query_language_service/fetch_match_tables.py
+++ /dev/null
@@ -1,57 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example fetches data from PQL tables and creates match table files."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import tempfile
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize a report downloader.
- report_downloader = client.GetDataDownloader(version='v201408')
-
- line_items_file = tempfile.NamedTemporaryFile(
- prefix='line_items_', suffix='.csv', mode='w', delete=False)
- ad_units_file = tempfile.NamedTemporaryFile(
- prefix='ad_units_', suffix='.csv', mode='w', delete=False)
-
- line_items_pql_query = ('SELECT Name, Id, Status FROM Line_Item ORDER BY Id '
- 'ASC')
- ad_units_pql_query = 'SELECT Name, Id FROM Ad_Unit ORDER BY Id ASC'
-
- # Downloads the response from PQL select statement to the specified file
- report_downloader.DownloadPqlResultToCsv(
- line_items_pql_query, line_items_file)
- report_downloader.DownloadPqlResultToCsv(
- ad_units_pql_query, ad_units_file)
-
- line_items_file.close()
- ad_units_file.close()
-
- print ('Saved line items to... %s' % line_items_file.name)
- print ('Saved ad units to... %s' % ad_units_file.name)
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/publisher_query_language_service/get_geo_targets.py b/examples/dfp/v201408/publisher_query_language_service/get_geo_targets.py
deleted file mode 100755
index bab9d479..00000000
--- a/examples/dfp/v201408/publisher_query_language_service/get_geo_targets.py
+++ /dev/null
@@ -1,65 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets geographic criteria from the Geo_Target table.
-
-The types available to filter on include 'City', 'Country', 'Region', 'State',
-'Postal_Code', and 'DMA_Region' (i.e. Metro).
-
-A full list of available geo target types can be found at
-https://developers.google.com/doubleclick-publishers/docs/reference/v201408/PublisherQueryLanguageService
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import tempfile
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize a report downloader.
- report_downloader = client.GetDataDownloader(version='v201408')
-
- output_file = tempfile.NamedTemporaryFile(
- prefix='geo_target_type_', suffix='.csv', mode='w', delete=False)
-
- # Create bind value to select geo-targets of type 'City'.
- values = [{
- 'key': 'type',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'City'
- }
- }]
-
- pql_query = ('SELECT Name, Id FROM Geo_Target '
- 'WHERE targetable = true AND Type = :type')
-
- # Downloads the response from PQL select statement to the specified file
- report_downloader.DownloadPqlResultToCsv(
- pql_query, output_file, values)
- output_file.close()
-
- print ('Saved geo targets to... %s' % output_file.name)
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/publisher_query_language_service/get_line_items_named_like.py b/examples/dfp/v201408/publisher_query_language_service/get_line_items_named_like.py
deleted file mode 100755
index ec7dc34b..00000000
--- a/examples/dfp/v201408/publisher_query_language_service/get_line_items_named_like.py
+++ /dev/null
@@ -1,58 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all line items with names starting with 'line item'."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import tempfile
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize a report downloader.
- report_downloader = client.GetDataDownloader(version='v201408')
-
- output_file = tempfile.NamedTemporaryFile(
- prefix='line_items_named_like_', suffix='.csv', mode='w', delete=False)
-
- # Create bind value to select line items with names starting with 'line item'.
- values = [{
- 'key': 'name',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'line item%'
- }
- }]
-
- pql_query = ('SELECT Name, Id, Status FROM Line_Item '
- 'WHERE Name LIKE :name')
-
- # Downloads the response from PQL select statement to the specified file
- report_downloader.DownloadPqlResultToCsv(
- pql_query, output_file, values)
- output_file.close()
-
- print ('Saved line items to... %s' % output_file.name)
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/report_service/__init__.py b/examples/dfp/v201408/report_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201408/report_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201408/report_service/run_delivery_report.py b/examples/dfp/v201408/report_service/run_delivery_report.py
deleted file mode 100755
index 123d0472..00000000
--- a/examples/dfp/v201408/report_service/run_delivery_report.py
+++ /dev/null
@@ -1,85 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example runs a report similar to the "Orders report" on the DFP
-website with additional attributes and can filter to include just one order.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-import tempfile
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-from googleads import errors
-
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-
-
-def main(client, order_id):
- # Create statement object to filter for an order.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': order_id
- }
- }]
- filter_statement = {'query': 'WHERE ORDER_ID = :id',
- 'values': values}
-
- # Create report job.
- report_job = {
- 'reportQuery': {
- 'dimensions': ['ORDER_ID', 'ORDER_NAME'],
- 'dimensionAttributes': ['ORDER_TRAFFICKER', 'ORDER_START_DATE_TIME',
- 'ORDER_END_DATE_TIME'],
- 'statement': filter_statement,
- 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS',
- 'AD_SERVER_CTR', 'AD_SERVER_CPM_AND_CPC_REVENUE',
- 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'],
- 'dateRangeType': 'LAST_MONTH'
- }
- }
-
- # Initialize a DataDownloader.
- report_downloader = client.GetDataDownloader(version='v201408')
-
- try:
- # Run the report and wait for it to finish.
- report_job_id = report_downloader.WaitForReport(report_job)
- except errors.DfpReportError, e:
- print 'Failed to generate report. Error was: %s' % e
-
- # Change to your preferred export format.
- export_format = 'CSV_DUMP'
-
- report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
-
- # Download report data.
- report_downloader.DownloadReportToFile(
- report_job_id, export_format, report_file)
-
- report_file.close()
-
- # Display results.
- print 'Report job with id \'%s\' downloaded to:\n%s' % (
- report_job_id, report_file.name)
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID)
diff --git a/examples/dfp/v201408/report_service/run_inventory_report.py b/examples/dfp/v201408/report_service/run_inventory_report.py
deleted file mode 100755
index 18592405..00000000
--- a/examples/dfp/v201408/report_service/run_inventory_report.py
+++ /dev/null
@@ -1,90 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example runs a report equal to the "Whole network report" on the
-DFP website.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-import tempfile
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-from googleads import errors
-
-
-def main(client):
- # Initialize appropriate service.
- network_service = client.GetService('NetworkService', version='v201408')
- # Initialize a DataDownloader.
- report_downloader = client.GetDataDownloader(version='v201408')
-
- # Get root ad unit id for network.
- root_ad_unit_id = (
- network_service.getCurrentNetwork()['effectiveRootAdUnitId'])
-
- # Set filter statement and bind value for reportQuery.
- values = [{
- 'key': 'parent_ad_unit_id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': root_ad_unit_id
- }
- }]
- filter_statement = {'query': 'WHERE PARENT_AD_UNIT_ID = :parent_ad_unit_id',
- 'values': values}
-
- # Create report job.
- report_job = {
- 'reportQuery': {
- 'dimensions': ['DATE', 'AD_UNIT_NAME'],
- 'adUnitView': 'HIERARCHICAL',
- 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS',
- 'DYNAMIC_ALLOCATION_INVENTORY_LEVEL_IMPRESSIONS',
- 'DYNAMIC_ALLOCATION_INVENTORY_LEVEL_CLICKS',
- 'TOTAL_INVENTORY_LEVEL_IMPRESSIONS',
- 'TOTAL_INVENTORY_LEVEL_CPM_AND_CPC_REVENUE'],
- 'dateRangeType': 'LAST_WEEK',
- 'statement': filter_statement
- }
- }
-
- try:
- # Run the report and wait for it to finish.
- report_job_id = report_downloader.WaitForReport(report_job)
- except errors.DfpReportError, e:
- print 'Failed to generate report. Error was: %s' % e
-
- # Change to your preferred export format.
- export_format = 'CSV_DUMP'
-
- report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
-
- # Download report data.
- report_downloader.DownloadReportToFile(
- report_job_id, export_format, report_file)
-
- report_file.close()
-
- # Display results.
- print 'Report job with id \'%s\' downloaded to:\n%s' % (
- report_job_id, report_file.name)
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/report_service/run_reach_report.py b/examples/dfp/v201408/report_service/run_reach_report.py
deleted file mode 100755
index d3d017ee..00000000
--- a/examples/dfp/v201408/report_service/run_reach_report.py
+++ /dev/null
@@ -1,66 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example runs a reach report."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-import tempfile
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-from googleads import errors
-
-
-def main(client):
- # Initialize a DataDownloader.
- report_downloader = client.GetDataDownloader(version='v201408')
-
- # Create report job.
- report_job = {
- 'reportQuery': {
- 'dimensions': ['LINE_ITEM_ID', 'LINE_ITEM_NAME'],
- 'columns': ['REACH_FREQUENCY', 'REACH_AVERAGE_REVENUE', 'REACH'],
- 'dateRangeType': 'REACH_LIFETIME'
- }
- }
-
- try:
- # Run the report and wait for it to finish.
- report_job_id = report_downloader.WaitForReport(report_job)
- except errors.DfpReportError, e:
- print 'Failed to generate report. Error was: %s' % e
-
- # Change to your preferred export format.
- export_format = 'CSV_DUMP'
-
- report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
-
- # Download report data.
- report_downloader.DownloadReportToFile(
- report_job_id, export_format, report_file)
-
- report_file.close()
-
- # Display results.
- print 'Report job with id \'%s\' downloaded to:\n%s' % (
- report_job_id, report_file.name)
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/report_service/run_report_with_custom_fields.py b/examples/dfp/v201408/report_service/run_report_with_custom_fields.py
deleted file mode 100755
index 2fcac888..00000000
--- a/examples/dfp/v201408/report_service/run_report_with_custom_fields.py
+++ /dev/null
@@ -1,107 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example runs a report that with custom fields found in the line
-items of an order.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-import tempfile
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-from googleads import errors
-
-# Set the ID of the order to get line items from.
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-
-
-def main(client, order_id):
- # Initialize appropriate service.
- line_item_service = client.GetService('LineItemService', version='v201408')
- # Initialize a DataDownloader.
- report_downloader = client.GetDataDownloader(version='v201408')
-
- # Filter for line items of a given order.
- values = [{
- 'key': 'orderId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': order_id
- }
- }]
- query = 'WHERE orderId = :orderId'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Collect all line item custom field IDs for an order.
- custom_field_ids = set()
-
- # Get users by statement.
- while True:
- response = line_item_service.getLineItemsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Get custom field IDs from the line items of an order.
- for line_item in response['results']:
- if 'customFieldValues' in line_item:
- for custom_field_value in line_item['customFieldValues']:
- custom_field_ids.add(custom_field_value['customFieldId'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Create statement object to filter for an order.
- filter_statement = {'query': query, 'values': values}
-
- # Create report job.
- report_job = {
- 'reportQuery': {
- 'dimensions': ['LINE_ITEM_ID', 'LINE_ITEM_NAME'],
- 'statement': filter_statement,
- 'columns': ['AD_SERVER_IMPRESSIONS'],
- 'dateRangeType': 'LAST_MONTH',
- 'customFieldIds': list(custom_field_ids)
- }
- }
-
- try:
- # Run the report and wait for it to finish.
- report_job_id = report_downloader.WaitForReport(report_job)
- except errors.DfpReportError, e:
- print 'Failed to generate report. Error was: %s' % e
-
- # Change to your preferred export format.
- export_format = 'CSV_DUMP'
-
- report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
-
- # Download report data.
- report_downloader.DownloadReportToFile(
- report_job_id, export_format, report_file)
-
- report_file.close()
-
- # Display results.
- print 'Report job with id \'%s\' downloaded to:\n%s' % (
- report_job_id, report_file.name)
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID)
diff --git a/examples/dfp/v201408/report_service/run_sales_report.py b/examples/dfp/v201408/report_service/run_sales_report.py
deleted file mode 100755
index 1e330d64..00000000
--- a/examples/dfp/v201408/report_service/run_sales_report.py
+++ /dev/null
@@ -1,67 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example runs a report equal to the "Sales by salespersons report."
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-import tempfile
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-from googleads import errors
-
-
-def main(client):
- # Initialize a DataDownloader.
- report_downloader = client.GetDataDownloader(version='v201408')
-
- # Create report job.
- report_job = {
- 'reportQuery': {
- 'dimensions': ['SALESPERSON_ID', 'SALESPERSON_NAME'],
- 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CPM_AND_CPC_REVENUE',
- 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'],
- 'dateRangeType': 'LAST_MONTH'
- }
- }
-
- try:
- # Run the report and wait for it to finish.
- report_job_id = report_downloader.WaitForReport(report_job)
- except errors.DfpReportError, e:
- print 'Failed to generate report. Error was: %s' % e
-
- # Change to your preferred export format.
- export_format = 'CSV_DUMP'
-
- report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
-
- # Download report data.
- report_downloader.DownloadReportToFile(
- report_job_id, export_format, report_file)
-
- report_file.close()
-
- # Display results.
- print 'Report job with id \'%s\' downloaded to:\n%s' % (
- report_job_id, report_file.name)
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/suggested_ad_unit_service/__init__.py b/examples/dfp/v201408/suggested_ad_unit_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201408/suggested_ad_unit_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201408/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/dfp/v201408/suggested_ad_unit_service/approve_all_suggested_ad_units.py
deleted file mode 100755
index 9d70e3ed..00000000
--- a/examples/dfp/v201408/suggested_ad_unit_service/approve_all_suggested_ad_units.py
+++ /dev/null
@@ -1,80 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example approves all suggested ad units with 50 or more requests.
-
-This feature is only available to DFP premium solution networks.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-THRESHOLD_NUMBER_OF_REQUESTS = '50'
-
-
-def main(client):
- # Initialize appropriate service.
- suggested_ad_unit_service = client.GetService(
- 'SuggestedAdUnitService', version='v201408')
-
- values = [{
- 'key': 'numRequests',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': THRESHOLD_NUMBER_OF_REQUESTS
- }
- }]
-
- query = 'WHERE numRequests > :numRequests'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
- num_approved_suggested_ad_units = 0
-
- # Get suggested ad units by statement.
- while True:
- response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Print suggested ad units that will be approved.
- for suggested_ad_unit in response['results']:
- print ('Suggested ad unit with id \'%s\', and number of requests \'%s\''
- ' will be approved.' % (suggested_ad_unit['id'],
- suggested_ad_unit['numRequests']))
-
- # Approve suggested ad units.
- result = suggested_ad_unit_service.performSuggestedAdUnitAction(
- {'xsi_type': 'ApproveSuggestedAdUnit'},
- statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- num_approved_suggested_ad_units += int(result['numChanges'])
- else:
- break
-
- if num_approved_suggested_ad_units > 0:
- print ('Number of suggested ad units approved: %s' %
- num_approved_suggested_ad_units)
- else:
- print 'No suggested ad units were approved.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
-
diff --git a/examples/dfp/v201408/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/dfp/v201408/suggested_ad_unit_service/get_all_suggested_ad_units.py
deleted file mode 100755
index 94ed9e4c..00000000
--- a/examples/dfp/v201408/suggested_ad_unit_service/get_all_suggested_ad_units.py
+++ /dev/null
@@ -1,56 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all suggested ad units.
-
-To approve suggested ad units, run approve_suggested_ad_units.py. This feature
-is only available to DFP premium solution networks.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- suggested_ad_unit_service = client.GetService(
- 'SuggestedAdUnitService', version='v201408')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get suggested ad units by statement.
- while True:
- response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for suggested_ad_unit in response['results']:
- print ('Ad unit with id \'%s\' and number of requests \'%s\' was found.'
- % (suggested_ad_unit['id'], suggested_ad_unit['numRequests']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py b/examples/dfp/v201408/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py
deleted file mode 100755
index 1be5bc2d..00000000
--- a/examples/dfp/v201408/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py
+++ /dev/null
@@ -1,65 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets suggested ad units that have more than 50 requests.
-
-This feature is only available to DFP premium solution networks.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- suggested_ad_unit_service = client.GetService(
- 'SuggestedAdUnitService', version='v201408')
-
- values = [{
- 'key': 'numRequests',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': '50'
- }
- }]
-
- query = 'WHERE numRequests > :numRequests'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Get suggested ad units by statement.
- while True:
- response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for suggested_ad_unit in response['results']:
- print ('Ad unit with id \'%s\' and number of requests \'%s\' was found.'
- % (suggested_ad_unit['id'], suggested_ad_unit['numRequests']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/team_service/__init__.py b/examples/dfp/v201408/team_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201408/team_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201408/team_service/create_teams.py b/examples/dfp/v201408/team_service/create_teams.py
deleted file mode 100755
index 213bcbfa..00000000
--- a/examples/dfp/v201408/team_service/create_teams.py
+++ /dev/null
@@ -1,64 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates new teams.
-
-To determine which teams exist, run get_all_teams.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: TeamService.createTeams
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- team_service = client.GetService('TeamService', version='v201408')
-
- # Create team objects.
- teams = []
- for i in xrange(5):
- team = {
- 'name': 'Team %s' % uuid.uuid4(),
- 'hasAllCompanies': 'false',
- 'hasAllInventory': 'false',
- 'teamAccessType': 'READ_WRITE'
- }
- teams.append(team)
-
- # Add Teams.
- teams = team_service.createTeams(teams)
-
- # Display results.
- for team in teams:
- print ('Team with ID \'%s\' and name \'%s\' was created.'
- % (team['id'], team['name']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/team_service/get_all_teams.py b/examples/dfp/v201408/team_service/get_all_teams.py
deleted file mode 100755
index 21e99e5f..00000000
--- a/examples/dfp/v201408/team_service/get_all_teams.py
+++ /dev/null
@@ -1,60 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all teams.
-
-To create teams, run create_teams.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: TeamService.getTeamsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- team_service = client.GetService('TeamService', version='v201408')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get users by statement.
- while True:
- response = team_service.getTeamsByStatement(statement.ToStatement())
- if 'results' in response:
- # Display results.
- for team in response['results']:
- print ('Team with ID \'%s\' and name \'%s\' was found.'
- % (team['id'], team['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/team_service/get_teams_by_statement.py b/examples/dfp/v201408/team_service/get_teams_by_statement.py
deleted file mode 100755
index 8efa32d3..00000000
--- a/examples/dfp/v201408/team_service/get_teams_by_statement.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets a single team by ID.
-
-To create teams, run create_teams.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: TeamService.getTeamsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-TEAM_ID = 'INSERT_TEAM_ID_HERE'
-
-
-def main(client, team_id):
- # Initialize appropriate service.
- team_service = client.GetService('TeamService', version='v201408')
-
- # Create a filter statement to select a single team by ID.
- values = [{
- 'key': 'teamId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': team_id
- }
- }]
- query = 'WHERE id = :teamId'
- statement = dfp.FilterStatement(query, values)
-
- while True:
- # Get teams by statement.
- response = team_service.getTeamsByStatement(statement.ToStatement())
- if 'results' in response:
- # Display results.
- for team in response['results']:
- print ('Team with id \'%s\' and name \'%s\' was found.'
- % (team['id'], team['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, TEAM_ID)
diff --git a/examples/dfp/v201408/team_service/update_teams.py b/examples/dfp/v201408/team_service/update_teams.py
deleted file mode 100755
index 28e09c69..00000000
--- a/examples/dfp/v201408/team_service/update_teams.py
+++ /dev/null
@@ -1,84 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates teams by adding an ad unit to a team.
-
-To determine which teams exist, run get_all_teams.py. To determine which ad
-units exist, run get_all_ad_units.py
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: TeamService.getTeamsByStatement, TeamService.updateTeams
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE'
-TEAM_ID = 'INSERT_TEAM_ID_HERE'
-
-
-def main(client, ad_unit_id, team_id):
- # Initialize appropriate service.
- team_service = client.GetService('TeamService', version='v201408')
-
- # Create a filter statement to select a single team by ID.
- values = [{
- 'key': 'teamId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': team_id
- }
- }]
- query = 'WHERE id = :teamId'
- statement = dfp.FilterStatement(query, values)
-
- # Get teams by statement.
- response = team_service.getTeamsByStatement(statement.ToStatement())
-
- if 'results' in response:
- updated_teams = []
- # Update each local team object by adding the ad unit to it.
- for team in response['results']:
- ad_unit_ids = []
- if 'adUnitIds' in team:
- ad_unit_ids = team['adUnitIds']
- # Don't add the ad unit if the team has all inventory already.
- if not team['hasAllInventory']:
- ad_unit_ids.append(ad_unit_id)
- team['adUnitIds'] = ad_unit_ids
- updated_teams.append(team)
-
- # Update teams on the server.
- teams = team_service.updateTeams(updated_teams)
-
- # Display results.
- for team in teams:
- print ('Team with id \'%s\' and name \'%s\' was updated.'
- % (team['id'], team['name']))
- else:
- print 'No teams found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, AD_UNIT_ID, TEAM_ID)
diff --git a/examples/dfp/v201408/user_service/__init__.py b/examples/dfp/v201408/user_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201408/user_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201408/user_service/create_users.py b/examples/dfp/v201408/user_service/create_users.py
deleted file mode 100755
index 457c9218..00000000
--- a/examples/dfp/v201408/user_service/create_users.py
+++ /dev/null
@@ -1,59 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new users.
-
-To determine which users exist, run get_all_users.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-NEW_USER_EMAIL_ADDRESS = 'INSERT_EMAIL_ADDRESS_HERE'
-NEW_USER_NAME = 'INSERT_NAME_HERE'
-
-
-def main(client, email, name):
- # Initialize appropriate service.
- user_service = client.GetService('UserService', version='v201408')
-
- # Create user objects.
- users = [
- {
- 'email': email,
- 'name': name,
- 'preferredLocale': 'en_US'
- }
- ]
- for user in users:
- # Set the system defined ID of the trafficker role.
- # To determine what other roles exist, run get_all_roles.py.
- user['roleId'] = '-7'
-
- # Add users.
- users = user_service.createUsers(users)
-
- # Display results.
- for user in users:
- print ('User with id \'%s\', email \'%s\', and role \'%s\' was created.'
- % (user['id'], user['email'], user['roleName']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, NEW_USER_EMAIL_ADDRESS, NEW_USER_NAME)
diff --git a/examples/dfp/v201408/user_service/deactivate_users.py b/examples/dfp/v201408/user_service/deactivate_users.py
deleted file mode 100755
index bdb55bc4..00000000
--- a/examples/dfp/v201408/user_service/deactivate_users.py
+++ /dev/null
@@ -1,73 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example deactivates a user.
-
-Deactivated users can no longer make requests to the API. The user making the
-request cannot deactivate itself. To determine which users exist, run
-get_all_users.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-USER_ID = 'INSERT_USER_ID_TO_DEACTIVATE_HERE'
-
-
-def main(client, user_id):
- # Initialize appropriate service.
- user_service = client.GetService('UserService', version='v201408')
-
- # Create query.
- values = [{
- 'key': 'userId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': user_id
- }
- }]
- query = 'WHERE id = :userId'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Get users by statement.
- response = user_service.getUsersByStatement(statement.ToStatement())
- users = response['results'] if 'results' in response else []
-
- for user in users:
- print ('User with id \'%s\', email \'%s\', and status \'%s\' will be '
- 'deactivated.'
- % (user['id'], user['email'],
- {'true': 'ACTIVE', 'false': 'INACTIVE'}[user['isActive']]))
- print 'Number of users to be deactivated: %s' % len(users)
-
- # Perform action.
- result = user_service.performUserAction({'xsi_type': 'DeactivateUsers'},
- statement.ToStatement())
-
- # Display results.
- if result and int(result['numChanges']) > 0:
- print 'Number of users deactivated: %s' % result['numChanges']
- else:
- print 'No users were deactivated.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, USER_ID)
diff --git a/examples/dfp/v201408/user_service/get_all_roles.py b/examples/dfp/v201408/user_service/get_all_roles.py
deleted file mode 100755
index b9053254..00000000
--- a/examples/dfp/v201408/user_service/get_all_roles.py
+++ /dev/null
@@ -1,46 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all roles.
-
-This sample can be used to determine which role id is needed when getting and
-creating users."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- user_service = client.GetService('UserService', version='v201408')
-
- # Get all roles.
- roles = user_service.getAllRoles()
-
- # Display results.
- for role in roles:
- print ('Role with id \'%s\' and name \'%s\' was found.'
- % (role['id'], role['name']))
-
- print '\nNumber of results found: %s' % len(roles)
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/user_service/get_all_users.py b/examples/dfp/v201408/user_service/get_all_users.py
deleted file mode 100755
index 8466edd4..00000000
--- a/examples/dfp/v201408/user_service/get_all_users.py
+++ /dev/null
@@ -1,50 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all users. To create users, run create_users.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- user_service = client.GetService('UserService', version='v201408')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get users by statement.
- while True:
- response = user_service.getUsersByStatement(statement.ToStatement())
- if 'results' in response:
- # Display results.
- for user in response['results']:
- print ('User with id \'%s\', email \'%s\', and role \'%s\' was found.'
- % (user['id'], user['email'], user['roleName']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/user_service/get_current_user.py b/examples/dfp/v201408/user_service/get_current_user.py
deleted file mode 100755
index 386bff30..00000000
--- a/examples/dfp/v201408/user_service/get_current_user.py
+++ /dev/null
@@ -1,40 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets the current user."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- user_service = client.GetService('UserService', version='v201408')
-
- # Get current user.
- user = user_service.getCurrentUser()
-
- # Display results.
- print ('User with id \'%s\', email \'%s\', and role \'%s\' was found.'
- % (user['id'], user['email'], user['roleName']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/user_service/get_users_by_statement.py b/examples/dfp/v201408/user_service/get_users_by_statement.py
deleted file mode 100755
index cc1ca2fb..00000000
--- a/examples/dfp/v201408/user_service/get_users_by_statement.py
+++ /dev/null
@@ -1,59 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets a user by its id.
-
-To create users, run create_user.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-USER_ID = 'INSERT_USER_ID_TO_FIND_HERE'
-
-
-def main(client, user_id):
- # Initialize appropriate service.
- user_service = client.GetService('UserService', version='v201408')
-
- # Create query.
- values = [{
- 'key': 'userId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': user_id
- }
- }]
- query = 'WHERE id = :userId'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Get users by statement.
- response = user_service.getUsersByStatement(statement.ToStatement())
- users = response['results'] if 'results' in response else []
-
- for user in users:
- # Display results.
- print ('User with id \'%s\', email \'%s\', and role \'%s\' was found.'
- % (user['id'], user['email'], user['roleName']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, USER_ID)
diff --git a/examples/dfp/v201408/user_service/update_users.py b/examples/dfp/v201408/user_service/update_users.py
deleted file mode 100755
index 8476420c..00000000
--- a/examples/dfp/v201408/user_service/update_users.py
+++ /dev/null
@@ -1,66 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates a user by adding " Sr." to the end of their name.
-
-To determine which users exist, run get_all_users.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-USER_ID = 'INSERT_USER_ID_TO_UPDATE_HERE'
-
-
-def main(client, user_id):
- # Initialize appropriate service.
- user_service = client.GetService('UserService', version='v201408')
-
- # Create query.
- values = [{
- 'key': 'userId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': user_id
- }
- }]
- query = 'WHERE id = :userId'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Get users by statement.
- response = user_service.getUsersByStatement(statement.ToStatement())
-
- if 'results' in response:
- users = response['results']
- for user in users:
- user['name'] += ' Sr.'
-
- # Update users on server.
- users = user_service.updateUsers(users)
- for user in users:
- print ('User with id \'%s\' and name \'%s\' was updated.'
- % (user['id'], user['name']))
- else:
- print 'No users found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, USER_ID)
diff --git a/examples/dfp/v201408/user_team_association_service/__init__.py b/examples/dfp/v201408/user_team_association_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201408/user_team_association_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201408/user_team_association_service/create_user_team_associations.py b/examples/dfp/v201408/user_team_association_service/create_user_team_associations.py
deleted file mode 100755
index f298bcdc..00000000
--- a/examples/dfp/v201408/user_team_association_service/create_user_team_associations.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds a user to a team by creating an association between them.
-
-To determine which teams exists, run get_all_teams.py. To determine which
-users exist, run get_all_users.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: UserTeamAssociationService.createUserTeamAssociations
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-TEAM_ID = 'INSERT_TEAM_ID_HERE'
-USER_IDS = ['INSERT_USER_IDS_TO_ASSOCIATE_TO_TEAM_HERE']
-
-
-def main(client, team_id, user_ids):
- # Initialize appropriate service.
- user_team_association_service = client.GetService(
- 'UserTeamAssociationService', version='v201408')
-
- user_team_associations = []
- for user_id in user_ids:
- user_team_associations.append(
- {
- 'teamId': team_id,
- 'userId': user_id
- })
-
- # Create the user team association on the server.
- user_team_associations = (
- user_team_association_service.createUserTeamAssociations(
- user_team_associations))
-
- # Display results.
- if user_team_associations:
- for user_team_association in user_team_associations:
- print ('A user team association between user with ID \'%s\' and team with'
- ' ID \'%s\'was created.' % (user_team_association['userId'],
- user_team_association['teamId']))
- else:
- print 'No user team associations created.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, TEAM_ID, USER_IDS)
diff --git a/examples/dfp/v201408/user_team_association_service/delete_user_team_associations.py b/examples/dfp/v201408/user_team_association_service/delete_user_team_associations.py
deleted file mode 100755
index 2d6967e6..00000000
--- a/examples/dfp/v201408/user_team_association_service/delete_user_team_associations.py
+++ /dev/null
@@ -1,83 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example removes the user from all its teams.
-
-To determine which users exist, run get_all_users.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: UserTeamAssociationService.performUserTeamAssociationAction
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-USER_ID = 'INSERT_USER_ID_HERE'
-
-
-def main(client, user_id):
- # Initialize appropriate service.
- user_team_association_service = client.GetService(
- 'UserTeamAssociationService', version='v201408')
-
- # Create filter text to select user team associations by the user ID.
- values = [{
- 'key': 'userId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': user_id
- }
- }]
- query = 'WHERE userId = :userId'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Get user team associations by statement.
- response = user_team_association_service.getUserTeamAssociationsByStatement(
- statement.ToStatement())
- user_team_associations = response['results'] if 'results' in response else []
-
- for user_team_association in user_team_associations:
- print ('User team association between user with ID \'%s\' and team with '
- 'ID \'%s\' will be deleted.' % (user_team_association['userId'],
- user_team_association['teamId']))
- print ('Number of teams that the user will be removed from: %s' %
- len(user_team_associations))
-
- # Perform action.
- result = user_team_association_service.performUserTeamAssociationAction(
- {'xsi_type': 'DeleteUserTeamAssociations'},
- {'query': query, 'values': values})
-
- # Display results.
- if result and int(result['numChanges']) > 0:
- print ('Number of teams that the user was removed from: %s'
- % result['numChanges'])
- else:
- print 'No user team associations were deleted.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, USER_ID)
diff --git a/examples/dfp/v201408/user_team_association_service/get_all_user_team_associations.py b/examples/dfp/v201408/user_team_association_service/get_all_user_team_associations.py
deleted file mode 100755
index f536ef0e..00000000
--- a/examples/dfp/v201408/user_team_association_service/get_all_user_team_associations.py
+++ /dev/null
@@ -1,64 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all user team associations.
-
-To create user team associations, run create_user_team_assocations.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: UserTeamAssociationService.getUserTeamAssociationsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- user_team_association_service = client.GetService(
- 'UserTeamAssociationService', version='v201408')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get user team associations by statement.
- while True:
- response = user_team_association_service.getUserTeamAssociationsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for user_team_association in response['results']:
- print ('User team association between user with ID \'%s\' and team with'
- ' ID \'%s\' was found.' % (user_team_association['userId'],
- user_team_association['teamId']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201408/user_team_association_service/get_user_team_associations_for_user.py b/examples/dfp/v201408/user_team_association_service/get_user_team_associations_for_user.py
deleted file mode 100755
index e60af35d..00000000
--- a/examples/dfp/v201408/user_team_association_service/get_user_team_associations_for_user.py
+++ /dev/null
@@ -1,75 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all user team associations for a single user.
-
-To determine which users exist, run get_all_users.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: UserTeamAssociationService.getUserTeamAssociation
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-USER_ID = 'INSERT_USER_ID_HERE'
-
-
-def main(client, user_id):
- # Initialize appropriate service.
- user_team_association_service = client.GetService(
- 'UserTeamAssociationService', version='v201408')
-
- # Create query.
- values = [{
- 'key': 'userId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': user_id
- }
- }]
- query = 'WHERE userId = :userId'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Get user team associations by statement.
- while True:
- response = user_team_association_service.getUserTeamAssociationsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for user_team_association in response['results']:
- print ('User team association between user with ID \'%s\' and team with'
- ' ID \'%s\' was found.' % (user_team_association['userId'],
- user_team_association['teamId']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, USER_ID)
diff --git a/examples/dfp/v201408/user_team_association_service/update_user_team_associations.py b/examples/dfp/v201408/user_team_association_service/update_user_team_associations.py
deleted file mode 100755
index 9d730096..00000000
--- a/examples/dfp/v201408/user_team_association_service/update_user_team_associations.py
+++ /dev/null
@@ -1,89 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates user team associations.
-
-It updates a user team association by setting the overridden access type to read
-only for all teams that the user belongs to. To determine which users exists,
-run get_all_users.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: UserTeamAssociationService.getUserTeamAssociationsByStatement
-Tags: UserTeamAssociationService.updateUserTeamAssociations
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-USER_ID = 'INSERT_USER_ID_TO_UPDATE_HERE'
-
-
-def main(client, user_id):
- # Initialize appropriate service.
- user_team_association_service = client.GetService(
- 'UserTeamAssociationService', version='v201408')
-
- # Create filter text to select user team associations by the user ID.
- values = [{
- 'key': 'userId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': user_id
- }
- }]
- query = 'WHERE userId = :userId'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Get user team associations by statement.
- response = user_team_association_service.getUserTeamAssociationsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- updated_user_team_associations = []
- # Update each local user team association to read only access.
- for user_team_association in response['results']:
- user_team_association['overriddenTeamAccessType'] = 'READ_ONLY'
- updated_user_team_associations.append(user_team_association)
-
- # Update user team associations on the server.
- user_team_associations = (
- user_team_association_service.updateUserTeamAssociations(
- updated_user_team_associations))
-
- # Display results.
- if user_team_associations:
- for user_team_association in user_team_associations:
- print ('User team association between user with ID \'%s\' and team with'
- ' ID \'%s\' was updated.' % (user_team_association['userId'],
- user_team_association['teamId']))
- else:
- print 'No user team associations were updated.'
- else:
- print 'No user team associations found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, USER_ID)
diff --git a/examples/dfp/v201411/activity_group_service/__init__.py b/examples/dfp/v201411/activity_group_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201411/activity_group_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201411/activity_group_service/create_activity_groups.py b/examples/dfp/v201411/activity_group_service/create_activity_groups.py
deleted file mode 100755
index 4a57d7a5..00000000
--- a/examples/dfp/v201411/activity_group_service/create_activity_groups.py
+++ /dev/null
@@ -1,74 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new activity groups.
-
-To determine which activity groups exist, run get_all_activity_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ActivityGroupService.createActivityGroups
-"""
-
-__author__ = ('Vincent Tsao',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the advertiser company this activity group is associated with.
-ADVERTISER_COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
-
-
-def main(client, advertiser_company_id):
- # Initialize appropriate service.
- activity_group_service = client.GetService('ActivityGroupService',
- version='v201411')
-
- # Create a short-term activity group.
- short_term_activity_group = {
- 'name': 'Short-term activity group #%s' % uuid.uuid4(),
- 'companyIds': [advertiser_company_id],
- 'clicksLookback': '1',
- 'impressionsLookback': '1'
- }
-
- # Create a long-term activity group.
- long_term_activity_group = {
- 'name': 'Long-term activity group #%s' % uuid.uuid4(),
- 'companyIds': [advertiser_company_id],
- 'clicksLookback': '30',
- 'impressionsLookback': '30'
- }
-
- # Create the activity groups on the server.
- activity_groups = activity_group_service.createActivityGroups([
- short_term_activity_group, long_term_activity_group])
-
- # Display results.
- for activity_group in activity_groups:
- print ('Activity group with ID \'%s\' and name \'%s\' was created.'
- % (activity_group['id'], activity_group['name']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ADVERTISER_COMPANY_ID)
diff --git a/examples/dfp/v201411/activity_group_service/get_active_activity_groups.py b/examples/dfp/v201411/activity_group_service/get_active_activity_groups.py
deleted file mode 100755
index 99dea94d..00000000
--- a/examples/dfp/v201411/activity_group_service/get_active_activity_groups.py
+++ /dev/null
@@ -1,72 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all active activity groups.
-
-To create activity groups, run create_activity_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ActivityGroupService.getActivityGroupsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- activity_group_service = client.GetService('ActivityGroupService',
- version='v201411')
-
- # Create statement object to only select active activity groups.
- values = [{
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ACTIVE'
- }
- }]
- query = 'WHERE status = :status'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Get activity groups by statement.
- while True:
- response = activity_group_service.getActivityGroupsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for activity_group in response['results']:
- print ('Activity group with ID \'%s\' and name \'%s\' was found.'
- % (activity_group['id'], activity_group['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/activity_group_service/get_all_activity_groups.py b/examples/dfp/v201411/activity_group_service/get_all_activity_groups.py
deleted file mode 100755
index 38571d30..00000000
--- a/examples/dfp/v201411/activity_group_service/get_all_activity_groups.py
+++ /dev/null
@@ -1,63 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all activity groups.
-
-To create activity groups, run create_activity_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ActivityGroupService.getActivityGroupsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- activity_group_service = client.GetService('ActivityGroupService',
- version='v201411')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get activity groups by statement.
- while True:
- response = activity_group_service.getActivityGroupsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for activity_group in response['results']:
- print ('Activity group with ID \'%s\' and name \'%s\' was found.'
- % (activity_group['id'], activity_group['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/activity_group_service/update_activity_groups.py b/examples/dfp/v201411/activity_group_service/update_activity_groups.py
deleted file mode 100755
index a1ca687c..00000000
--- a/examples/dfp/v201411/activity_group_service/update_activity_groups.py
+++ /dev/null
@@ -1,80 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates activity groups.
-
-To determine which activity groups exist, run get_all_activity_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ActivityGroupService.getActivityGroup
-Tags: ActivityGroupService.updateActivityGroups
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the activity group and the company to update it with.
-ACTIVITY_GROUP_ID = 'INSERT_ACTIVITY_GROUP_ID_HERE'
-ADVERTISER_COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
-
-
-def main(client, activity_group_id, advertiser_company_id):
- # Initialize appropriate service.
- activity_group_service = client.GetService('ActivityGroupService',
- version='v201411')
-
- # Create statement object to select a single activity groups by ID.
- values = [{
- 'key': 'activityGroupId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': activity_group_id
- }
- }]
- query = 'WHERE id = :activityGroupId'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get activity groups by statement.
- response = activity_group_service.getActivityGroupsByStatement(
- statement.ToStatement())
- if 'results' in response:
- updated_activity_groups = []
- for activity_group in response['results']:
- activity_group['companyIds'].append(advertiser_company_id)
- updated_activity_groups.append(activity_group)
- # Update the activity groups on the server.
- activity_groups = activity_group_service.updateActivityGroups(
- updated_activity_groups)
-
- for activity_group in activity_groups:
- print (('Activity group with ID \'%s\' and name \'%s\' was updated.')
- % (activity_group['id'], activity_group['name']))
- else:
- print 'No activity groups found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ACTIVITY_GROUP_ID, ADVERTISER_COMPANY_ID)
diff --git a/examples/dfp/v201411/activity_service/__init__.py b/examples/dfp/v201411/activity_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201411/activity_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201411/activity_service/create_activities.py b/examples/dfp/v201411/activity_service/create_activities.py
deleted file mode 100755
index d9220dcc..00000000
--- a/examples/dfp/v201411/activity_service/create_activities.py
+++ /dev/null
@@ -1,71 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new activities.
-
-To determine which activities groups exist, run get_all_activities.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ActivityService.createActivities
-"""
-
-__author__ = ('Vincent Tsao',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the activity group this activity is associated with.
-ACTIVITY_GROUP_ID = 'INSERT_ACTIVITY_GROUP_ID_HERE'
-
-
-def main(client, activity_group_id):
- # Initialize appropriate service.
- activity_service = client.GetService('ActivityService', version='v201411')
-
- # Create a daily visits activity.
- daily_visits_activity = {
- 'name': 'Activity #%s' % uuid.uuid4(),
- 'activityGroupId': activity_group_id,
- 'type': 'DAILY_VISITS'
- }
-
- # Create a custom activity.
- custom_activity = {
- 'name': 'Activity #%s' % uuid.uuid4(),
- 'activityGroupId': activity_group_id,
- 'type': 'CUSTOM'
- }
-
- # Create the activities on the server.
- activities = activity_service.createActivities([
- daily_visits_activity, custom_activity])
-
- # Display results.
- for activity in activities:
- print ('An activity with ID \'%s\', name \'%s\', and type \'%s\' was '
- 'created.' % (activity['id'], activity['name'], activity['type']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ACTIVITY_GROUP_ID)
diff --git a/examples/dfp/v201411/activity_service/get_active_activities.py b/examples/dfp/v201411/activity_service/get_active_activities.py
deleted file mode 100755
index e3376d8b..00000000
--- a/examples/dfp/v201411/activity_service/get_active_activities.py
+++ /dev/null
@@ -1,69 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all active activities.
-
-To create activities, run create_activities.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ActivityService.getActivitiesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- activity_service = client.GetService('ActivityService', version='v201411')
-
- # Create statement object to only select active activities.
- values = [{
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ACTIVE'
- }
- }]
- query = 'WHERE status = :status'
- statement = dfp.FilterStatement(query, values)
-
- # Get activities by statement.
- while True:
- response = activity_service.getActivitiesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for activity in response['results']:
- print ('Activity with ID \'%s\', name \'%s\', and type \'%s\' was '
- 'found.' % (activity['id'], activity['name'], activity['type']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/activity_service/get_all_activities.py b/examples/dfp/v201411/activity_service/get_all_activities.py
deleted file mode 100755
index cc1897c0..00000000
--- a/examples/dfp/v201411/activity_service/get_all_activities.py
+++ /dev/null
@@ -1,61 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all activities.
-
-To create activities, run create_activities.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ActivityService.getActivitiesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- activity_service = client.GetService('ActivityService', version='v201411')
-
- # Create statement object to select only all activities.
- statement = dfp.FilterStatement()
-
- # Get activities by statement.
- while True:
- response = activity_service.getActivitiesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for activity in response['results']:
- print ('Activity with ID \'%s\', name \'%s\', and type \'%s\' was '
- 'found.' % (activity['id'], activity['name'], activity['type']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/activity_service/update_activities.py b/examples/dfp/v201411/activity_service/update_activities.py
deleted file mode 100755
index 9c215666..00000000
--- a/examples/dfp/v201411/activity_service/update_activities.py
+++ /dev/null
@@ -1,76 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates activities.
-
-To determine which activities exist, run get_all_activities.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ActivityService.updateActivities
- ActivityService.getActivitiesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the activity to update.
-ACTIVITY_ID = 'INSERT_ACTIVITY_ID_HERE'
-
-
-def main(client, activity_id):
- # Initialize appropriate service.
- activity_service = client.GetService('ActivityService', version='v201411')
-
- # Create statement object to select one activity by ID to update.
- values = [{
- 'key': 'activityId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': activity_id
- }
- }]
- query = 'WHERE id = :activityId'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get activities by statement.
- response = activity_service.getActivitiesByStatement(
- statement.ToStatement())
- if 'results' in response:
- updated_activities = []
- for activity in response['results']:
- # Update the expected URL.
- activity['expectedURL'] = 'https://google.com'
- updated_activities.append(activity)
- # Update the activity on the server.
- activities = activity_service.updateActivities(updated_activities)
-
- for updated_activity in activities:
- print (('Activity with ID \'%s\' and name \'%s\' was updated.')
- % (updated_activity['id'], updated_activity['name']))
- else:
- print 'No activities found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ACTIVITY_ID)
diff --git a/examples/dfp/v201411/audience_segment_service/__init__.py b/examples/dfp/v201411/audience_segment_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201411/audience_segment_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201411/audience_segment_service/create_audience_segments.py b/examples/dfp/v201411/audience_segment_service/create_audience_segments.py
deleted file mode 100755
index d3c0bfe1..00000000
--- a/examples/dfp/v201411/audience_segment_service/create_audience_segments.py
+++ /dev/null
@@ -1,100 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates a new rule based first party audience segment."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the IDs of the custom criteria to be used in the segment rule.
-CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'
-CUSTOM_TARGETING_VALUE_ID = 'INSERT_CUSTOM_TARGETING_VALUE_ID_HERE'
-
-def main(client, custom_targeting_key_id, custom_targeting_value_id):
- # Initialize client object.
- client = dfp.DfpClient.LoadFromStorage()
-
- # Initialize appropriate services.
- audience_segment_service = client.GetService(
- 'AudienceSegmentService', version='v201411')
- network_service = client.GetService('NetworkService', version='v201411')
-
- # Get the root ad unit ID used to target the entire network.
- root_ad_unit_id = (
- network_service.getCurrentNetwork()['effectiveRootAdUnitId'])
-
- # Create inventory targeting (pointed at root ad unit i.e. the whole network)
- inventory_targeting = {
- 'targetedAdUnits': [
- {'adUnitId': root_ad_unit_id}
- ]
- }
-
- # Create custom criteria.
- custom_criteria = [
- {
- 'xsi_type': 'CustomCriteria',
- 'keyId': CUSTOM_TARGETING_KEY_ID,
- 'valueIds': [CUSTOM_TARGETING_VALUE_ID],
- 'operator': 'IS'
- }
- ]
-
- # Create the custom criteria set.
- top_custom_criteria_set = {
- 'logicalOperator': 'AND',
- 'children': custom_criteria
- }
-
- # Create the audience segment rule.
- rule = {
- 'inventoryRule': inventory_targeting,
- 'customCriteriaRule': top_custom_criteria_set
- }
-
- # Create an audience segment.
- audience_segment = [
- {
- 'xsi_type': 'RuleBasedFirstPartyAudienceSegment',
- 'name': ('Sports enthusiasts audience segment %s' %
- uuid.uuid4()),
- 'description': 'Sports enthusiasts between the ages of 20 and 30',
- 'pageViews': '6',
- 'recencyDays': '6',
- 'membershipExpirationDays': '88',
- 'rule': rule
- }
- ]
-
- audience_segments = (
- audience_segment_service.createAudienceSegments(audience_segment))
-
- for created_audience_segment in audience_segments:
- print ('An audience segment with ID \'%s\', name \'%s\', and type \'%s\' '
- 'was created.' % (created_audience_segment['id'],
- created_audience_segment['name'],
- created_audience_segment['type']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CUSTOM_TARGETING_KEY_ID, CUSTOM_TARGETING_VALUE_ID)
diff --git a/examples/dfp/v201411/audience_segment_service/get_all_audience_segments.py b/examples/dfp/v201411/audience_segment_service/get_all_audience_segments.py
deleted file mode 100755
index d32b2ea2..00000000
--- a/examples/dfp/v201411/audience_segment_service/get_all_audience_segments.py
+++ /dev/null
@@ -1,60 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all audience segments.
-
-To create audience segments, run create_audience_segments.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize client object.
- client = dfp.DfpClient.LoadFromStorage()
-
- # Initialize appropriate service.
- audience_segment_service = client.GetService(
- 'AudienceSegmentService', version='v201411')
-
- # Create statement object to select all audience segments.
- statement = dfp.FilterStatement()
-
- # Get audience segments by statement.
- while True:
- response = audience_segment_service.getAudienceSegmentsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for segment in response['results']:
- print ('Audience segment with id \'%s\' and name '
- '\'%s\' of size %s was found.' %
- (segment['id'], segment['name'], segment['size']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/audience_segment_service/get_first_party_audience_segments.py b/examples/dfp/v201411/audience_segment_service/get_first_party_audience_segments.py
deleted file mode 100755
index cb4f5c53..00000000
--- a/examples/dfp/v201411/audience_segment_service/get_first_party_audience_segments.py
+++ /dev/null
@@ -1,69 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all first party audience segments.
-
-To create first party audience segments, run create_audience_segments.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize client object.
- client = dfp.DfpClient.LoadFromStorage()
-
- # Initialize appropriate service.
- audience_segment_service = client.GetService(
- 'AudienceSegmentService', version='v201411')
-
- # Create statement object to only select first party audience segments.
- values = [{
- 'key': 'type',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'FIRST_PARTY'
- }
- }]
- query = 'WHERE Type = :type'
- statement = dfp.FilterStatement(query, values)
-
- # Get audience segments by statement.
- while True:
- response = audience_segment_service.getAudienceSegmentsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- segments = response['results']
- for segment in segments:
- print ('Audience segment with id \'%s\' and name \'%s\' of size '
- '%s was found. ' %
- (segment['id'], segment['name'], segment['size']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201411/audience_segment_service/populate_first_party_audience_segments.py
deleted file mode 100755
index 0088b991..00000000
--- a/examples/dfp/v201411/audience_segment_service/populate_first_party_audience_segments.py
+++ /dev/null
@@ -1,84 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example populates a specific first party audience segment.
-
-To determine which first party audience segments exist, run
-get_first_party_audience_segments.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-AUDIENCE_SEGMENT_ID = 'INSERT_AUDIENCE_SEGMENT_ID_HERE'
-
-
-def main(client, audience_segment_id):
- # Initialize client object.
- client = dfp.DfpClient.LoadFromStorage()
-
- # Initialize appropriate service.
- audience_segment_service = client.GetService(
- 'AudienceSegmentService', version='v201411')
-
- # Create statement object to get the specified first party audience segment.
- values = (
- [{'key': 'type',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'FIRST_PARTY'
- }
- },
- {'key': 'audience_segment_id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': AUDIENCE_SEGMENT_ID
- }
- }])
- query = 'WHERE Type = :type AND Id = :audience_segment_id'
- statement = dfp.FilterStatement(query, values, 1)
-
- response = audience_segment_service.getAudienceSegmentsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- segments = response['results']
-
- for segment in segments:
- print ('Audience segment with id \'%s\' and name \'%s\' will be populated.'
- % (segment['id'], segment['name']))
-
- action = {
- 'xsi_type': 'PopulateAudienceSegments'
- }
-
- populated_audience_segments = (
- audience_segment_service.performAudienceSegmentAction(
- action, statement.ToStatement()))
-
- print ('%s audience segment populated' %
- populated_audience_segments['numChanges'])
- else:
- print 'No Results Found'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, AUDIENCE_SEGMENT_ID)
diff --git a/examples/dfp/v201411/audience_segment_service/update_audience_segments.py b/examples/dfp/v201411/audience_segment_service/update_audience_segments.py
deleted file mode 100755
index 0d2dfa3e..00000000
--- a/examples/dfp/v201411/audience_segment_service/update_audience_segments.py
+++ /dev/null
@@ -1,82 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates rule based first party audience segments.
-
-To determine which audience segments exist, run get_all_audience_segments.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-AUDIENCE_SEGMENT_ID = 'INSERT_AUDIENCE_SEGMENT_ID_HERE'
-
-
-def main(client, audience_segment_id):
- # Initialize client object.
- client = dfp.DfpClient.LoadFromStorage()
-
- # Initialize appropriate service.
- audience_segment_service = client.GetService(
- 'AudienceSegmentService', version='v201411')
-
- # Create statement object to get the specified first party audience segment.
- values = (
- [{'key': 'type',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'FIRST_PARTY'
- }
- },
- {'key': 'audience_segment_id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': AUDIENCE_SEGMENT_ID
- }
- }])
- query = 'WHERE Type = :type AND Id = :audience_segment_id'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get audience segments by statement.
- response = audience_segment_service.getAudienceSegmentsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- updated_audience_segments = []
- for audience_segment in response['results']:
- print ('Audience segment with id \'%s\' and name \'%s\' will be updated.'
- % (audience_segment['id'], audience_segment['name']))
-
- audience_segment['membershipExpirationDays'] = '180'
- updated_audience_segments.append(audience_segment)
-
- audience_segments = audience_segment_service.updateAudienceSegments(
- updated_audience_segments)
-
- for audience_segment in audience_segments:
- print ('Audience segment with id \'%s\' and name \'%s\' was updated' %
- (audience_segment['id'], audience_segment['name']))
- else:
- print 'No audience segment found to update.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, AUDIENCE_SEGMENT_ID)
diff --git a/examples/dfp/v201411/base_rate_service/__init__.py b/examples/dfp/v201411/base_rate_service/__init__.py
deleted file mode 100755
index a426ca48..00000000
--- a/examples/dfp/v201411/base_rate_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201411/base_rate_service/create_product_base_rates.py b/examples/dfp/v201411/base_rate_service/create_product_base_rates.py
deleted file mode 100755
index dcccdbba..00000000
--- a/examples/dfp/v201411/base_rate_service/create_product_base_rates.py
+++ /dev/null
@@ -1,65 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates a product base rate.
-
-To determine which base rates exist, run get_all_base_rates.py.
-
-Tags: BaseRateService.createBaseRates
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE'
-RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE'
-
-
-def main(client, product_id, rate_card_id):
- # Initialize appropriate service.
- base_rate_service = client.GetService(
- 'BaseRateService', version='v201411')
-
- # Create a product base rate.
- product_base_rate = {
- 'xsi_type': 'ProductBaseRate',
- 'rateCardId': rate_card_id,
- 'productId': product_id,
- # Set the rate to be $2.
- 'rate': {
- 'currencyCode': 'USD',
- 'microAmount': 2000000
- }
- }
-
- # Create base rates on the server.
- base_rates = base_rate_service.createBaseRates(
- [product_base_rate])
-
- if base_rates:
- for base_rate in base_rates:
- print ('A product base rate with ID \'%s\' and rate \'%.2f\' %s was '
- 'created.' % (base_rate['id'],
- base_rate['rate']['microAmount'],
- base_rate['rate']['currencyCode']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PRODUCT_ID, RATE_CARD_ID)
diff --git a/examples/dfp/v201411/base_rate_service/create_product_template_base_rates.py b/examples/dfp/v201411/base_rate_service/create_product_template_base_rates.py
deleted file mode 100755
index 1d135c71..00000000
--- a/examples/dfp/v201411/base_rate_service/create_product_template_base_rates.py
+++ /dev/null
@@ -1,65 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates a product template base rate.
-
-To determine which base rates exist, run get_all_base_rates.py.
-
-Tags: BaseRateService.createBaseRates
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE'
-RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE'
-
-
-def main(client, product_template_id, rate_card_id):
- # Initialize appropriate service.
- base_rate_service = client.GetService(
- 'BaseRateService', version='v201411')
-
- # Create a product template base rate.
- product_template_base_rate = {
- 'xsi_type': 'ProductTemplateBaseRate',
- 'rateCardId': rate_card_id,
- 'productTemplateId': product_template_id,
- # Set the rate to be $2.
- 'rate': {
- 'currencyCode': 'USD',
- 'microAmount': 2000000
- }
- }
-
- # Create base rates on the server.
- base_rates = base_rate_service.createBaseRates(
- [product_template_base_rate])
-
- if base_rates:
- for base_rate in base_rates:
- print ('A product template base rate with ID \'%s\' and rate \'%.2f\' %s'
- ' was created.' % (base_rate['id'],
- base_rate['rate']['microAmount'],
- base_rate['rate']['currencyCode']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PRODUCT_TEMPLATE_ID, RATE_CARD_ID)
diff --git a/examples/dfp/v201411/base_rate_service/get_all_base_rates.py b/examples/dfp/v201411/base_rate_service/get_all_base_rates.py
deleted file mode 100755
index a5ebeaa2..00000000
--- a/examples/dfp/v201411/base_rate_service/get_all_base_rates.py
+++ /dev/null
@@ -1,60 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all base rates.
-
-To create product base rates, run create_product_base_rates.py
-To create product template base rates, run
-create_product_template_base_rates.py.
-
-Tags: BaseRateService.getBaseRatesByStatement
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- base_rate_service = client.GetService('BaseRateService', version='v201411')
-
- # Create a filter statement.
- statement = dfp.FilterStatement('ORDER BY id ASC')
-
- # Get base rates by statement.
- while True:
- response = base_rate_service.getBaseRatesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for base_rate in response['results']:
- print ('Base rate with ID \'%s\' and type \'%s\' belonging to '
- 'rate card ID \'%s\' was found.' % (
- base_rate['id'], base_rate['BaseRate.Type'],
- base_rate['rateCardId']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/base_rate_service/get_base_rates_for_a_rate_card.py b/examples/dfp/v201411/base_rate_service/get_base_rates_for_a_rate_card.py
deleted file mode 100755
index f15d79d9..00000000
--- a/examples/dfp/v201411/base_rate_service/get_base_rates_for_a_rate_card.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all base rates.
-
-To create product base rates, run create_product_base_rates.py
-To create product template base rates, run
-create_product_template_base_rates.py.
-
-Tags: BaseRateService.getBaseRatesByStatement
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE'
-
-
-def main(client, rate_card_id):
- # Initialize appropriate service.
- base_rate_service = client.GetService('BaseRateService', version='v201411')
-
- # Create a filter statement for base rates for a single rate card.
- values = [{
- 'key': 'rateCardId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': rate_card_id
- }
- }]
- query = 'where rateCardId = :rateCardId ORDER BY id ASC'
- statement = dfp.FilterStatement(query, values)
-
- # Get base rates by statement.
- while True:
- response = base_rate_service.getBaseRatesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for base_rate in response['results']:
- print ('Base rate with ID \'%s\' and type \'%s\' belonging to '
- 'rate card ID \'%s\' was found.' % (
- base_rate['id'], base_rate['BaseRate.Type'],
- base_rate['rateCardId']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, RATE_CARD_ID)
diff --git a/examples/dfp/v201411/base_rate_service/update_base_rates.py b/examples/dfp/v201411/base_rate_service/update_base_rates.py
deleted file mode 100755
index 0beebbd4..00000000
--- a/examples/dfp/v201411/base_rate_service/update_base_rates.py
+++ /dev/null
@@ -1,83 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates a base rate's value.
-
-To determine which base rates exist, run get_all_base_rates.py.
-
-Tags: BaseRateService.getBaseRatesByStatement
-Tags: BaseRateService.updateBaseRates
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-BASE_RATE_ID = 'INSERT_BASE_RATE_ID_HERE'
-
-
-def main(client, base_rate_id):
- # Initialize appropriate service.
- base_rate_service = client.GetService('BaseRateService', version='v201411')
-
- # Create a filter statement for base rates for a single rate card.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': base_rate_id
- }
- }]
- query = 'where id = :id ORDER BY id ASC'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get single base rate by statement.
- response = base_rate_service.getBaseRatesByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- # Update each local base rate object by changing its value to $3 USD.
- new_rate = {
- 'currencyCode': 'USD',
- 'microAmount': 3000000
- }
-
- updated_base_rates = []
- for base_rate in response['results']:
- base_rate['rate'] = new_rate
- updated_base_rates.append(base_rate)
-
- # Update base rates remotely.
- base_rates = base_rate_service.updateBaseRates(updated_base_rates)
-
- # Display results.
- if base_rates:
- for base_rate in base_rates:
- print ('Base rate with ID \'%s\' and type \'%s\' belonging to '
- 'rate card ID \'%s\' was updated.' % (
- base_rate['id'], base_rate['BaseRate.Type'],
- base_rate['rateCardId']))
- else:
- print 'No base rates were updated.'
- else:
- print 'No base rates found to update.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, BASE_RATE_ID)
diff --git a/examples/dfp/v201411/company_service/__init__.py b/examples/dfp/v201411/company_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201411/company_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201411/company_service/create_companies.py b/examples/dfp/v201411/company_service/create_companies.py
deleted file mode 100755
index 33fdedeb..00000000
--- a/examples/dfp/v201411/company_service/create_companies.py
+++ /dev/null
@@ -1,65 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new companies.
-
-To determine which companies exist, run get_all_companies.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CompanyService.createCompanies
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- company_service = client.GetService('CompanyService', version='v201411')
-
- # Create company objects.
- companies = [
- {
- 'name': 'Advertiser #%s' % uuid.uuid4(),
- 'type': 'ADVERTISER'
- },
- {
- 'name': 'Agency #%s' % uuid.uuid4(),
- 'type': 'AGENCY'
- }
- ]
-
- # Add companies.
- companies = company_service.createCompanies(companies)
-
- # Display results.
- for company in companies:
- print ('Company with ID \'%s\', name \'%s\', and type \'%s\' was created.'
- % (company['id'], company['name'], company['type']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/company_service/get_advertisers.py b/examples/dfp/v201411/company_service/get_advertisers.py
deleted file mode 100755
index 4923ecb4..00000000
--- a/examples/dfp/v201411/company_service/get_advertisers.py
+++ /dev/null
@@ -1,69 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all companies that are advertisers.
-
-To create companies, run create_companies.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CompanyService.getCompaniesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- company_service = client.GetService('CompanyService', version='v201411')
-
- # Create statement object to only select companies that are advertisers.
- values = [{
- 'key': 'type',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ADVERTISER'
- }
- }]
- query = 'WHERE type = :type'
- statement = dfp.FilterStatement(query, values)
-
- # Get companies by statement.
- while True:
- response = company_service.getCompaniesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for company in response['results']:
- print ('Company with ID \'%s\', name \'%s\', and type \'%s\' was found.'
- % (company['id'], company['name'], company['type']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/company_service/get_all_companies.py b/examples/dfp/v201411/company_service/get_all_companies.py
deleted file mode 100755
index b7917243..00000000
--- a/examples/dfp/v201411/company_service/get_all_companies.py
+++ /dev/null
@@ -1,61 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all companies.
-
-To create companies, run create_companies.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CompanyService.getCompaniesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- company_service = client.GetService('CompanyService', version='v201411')
-
- # Create statement object to select all companies.
- statement = dfp.FilterStatement()
-
- # Get companies by statement.
- while True:
- response = company_service.getCompaniesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for company in response['results']:
- print ('Company with ID \'%s\', name \'%s\', and type \'%s\' was found.'
- % (company['id'], company['name'], company['type']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/company_service/update_companies.py b/examples/dfp/v201411/company_service/update_companies.py
deleted file mode 100755
index 2940d98f..00000000
--- a/examples/dfp/v201411/company_service/update_companies.py
+++ /dev/null
@@ -1,77 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates company comments.
-
-To determine which companies exist, run get_all_companies.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CompanyService.updateCompanies
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the company to update.
-COMPANY_ID = 'INSERT_COMPANY_ID_HERE'
-
-
-def main(client, company_id):
- # Initialize appropriate service.
- company_service = client.GetService('CompanyService', version='v201411')
-
- # Create statement object to only select a single company by ID.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': company_id
- }
- }]
- query = 'WHERE id = :id'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get companies by statement.
- response = company_service.getCompaniesByStatement(
- statement.ToStatement())
- if 'results' in response:
- updated_companies = []
- for company in response['results']:
- company['comment'] += ' Updated.'
- updated_companies.append(company)
-
- # Update the companies on the server.
- companies = company_service.updateCompanies(updated_companies)
-
- # Display results.
- for company in companies:
- print (('Company with ID \'%s\', name \'%s\', and comment \'%s\''
- 'was updated.')
- % (company['id'], company['name'], company['comment']))
- else:
- print 'No companies found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, COMPANY_ID)
diff --git a/examples/dfp/v201411/contact_service/__init__.py b/examples/dfp/v201411/contact_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201411/contact_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201411/contact_service/create_contacts.py b/examples/dfp/v201411/contact_service/create_contacts.py
deleted file mode 100755
index 8fcd07ab..00000000
--- a/examples/dfp/v201411/contact_service/create_contacts.py
+++ /dev/null
@@ -1,74 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new contacts.
-
-To determine which contacts exist, run get_all_contacts.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContactService.createContacts
-"""
-
-__author__ = ('Vincent Tsao',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the advertiser company this contact is associated with.
-ADVERTISER_COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
-
-# Set the ID of the agency company this contact is associated with.
-AGENCY_COMPANY_ID = 'INSERT_AGENCY_COMPANY_ID_HERE'
-
-
-def main(client, advertiser_company_id, agency_company_id):
- # Initialize appropriate service.
- contact_service = client.GetService('ContactService', version='v201411')
-
- # Create an advertiser contact.
- advertiser_contact = {
- 'name': 'Mr. Advertiser #%s' % uuid.uuid4(),
- 'email': 'advertiser@advertising.com',
- 'companyId': advertiser_company_id
- }
-
- # Create an agency contact.
- agency_contact = {
- 'name': 'Ms. Agency #%s' % uuid.uuid4(),
- 'email': 'agency@agencies.com',
- 'companyId': agency_company_id
- }
-
- # Create the contacts on the server.
- contacts = contact_service.createContacts([advertiser_contact,
- agency_contact])
-
- # Display results.
- for contact in contacts:
- print ('Contact with ID \'%s\' name \'%s\' was created.'
- % (contact['id'], contact['name']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ADVERTISER_COMPANY_ID, AGENCY_COMPANY_ID)
diff --git a/examples/dfp/v201411/contact_service/get_all_contacts.py b/examples/dfp/v201411/contact_service/get_all_contacts.py
deleted file mode 100755
index ddd7108f..00000000
--- a/examples/dfp/v201411/contact_service/get_all_contacts.py
+++ /dev/null
@@ -1,61 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all contacts.
-
-To create contacts, run create_contacts.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContactService.getContactsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- contact_service = client.GetService('ContactService', version='v201411')
-
- # Create statement object to get all contacts.
- statement = dfp.FilterStatement()
-
- # Get contacts by statement.
- while True:
- response = contact_service.getContactsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for contact in response['results']:
- print ('Contact with ID \'%s\' and name \'%s\' was found.'
- % (contact['id'], contact['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/contact_service/get_uninvited_contacts.py b/examples/dfp/v201411/contact_service/get_uninvited_contacts.py
deleted file mode 100755
index b911f4f8..00000000
--- a/examples/dfp/v201411/contact_service/get_uninvited_contacts.py
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all contacts that aren't invited yet.
-
-To create contacts, run create_contacts.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContactService.getContactsByStatement
-"""
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- contact_service = client.GetService('ContactService', version='v201411')
-
- # Create statement object to only select contacts that are uninvited.
- values = [{
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'UNINVITED'
- }
- }]
- query = 'WHERE status = :status'
- statement = dfp.FilterStatement(query, values)
-
- # Get contacts by statement.
- while True:
- response = contact_service.getContactsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for contact in response['results']:
- print ('Contact with ID \'%s\' and name \'%s\' was found.'
- % (contact['id'], contact['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/contact_service/update_contacts.py b/examples/dfp/v201411/contact_service/update_contacts.py
deleted file mode 100755
index 61bb8508..00000000
--- a/examples/dfp/v201411/contact_service/update_contacts.py
+++ /dev/null
@@ -1,79 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates contact addresses.
-
-To determine which contacts exist, run get_all_contacts.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContactService.updateContacts
- ContactService.getContactsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the contact to update.
-CONTACT_ID = 'INSERT_CONTACT_ID_HERE'
-
-
-def main(client, contact_id):
- # Initialize appropriate service.
- contact_service = client.GetService('ContactService', version='v201411')
-
- # Create statement object to select the single contact by ID.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': contact_id
- }
- }]
- query = 'WHERE id = :id'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get contacts by statement.
- response = contact_service.getContactsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- updated_contacts = []
- for contact in response['results']:
- contact['address'] = '123 New Street, New York, NY, 10011'
- updated_contacts.append(contact)
-
- # Update the contact on the server.
- contacts = contact_service.updateContacts(updated_contacts)
-
- # Display results.
- for contact in contacts:
- print (('Contact with ID \'%s\', name \'%s\', and address \'%s\' '
- 'was updated.')
- % (contact['id'], contact['name'], contact['address']))
- else:
- print 'No contacts found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CONTACT_ID)
diff --git a/examples/dfp/v201411/content_metadata_key_hierarchy_service/__init__.py b/examples/dfp/v201411/content_metadata_key_hierarchy_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201411/content_metadata_key_hierarchy_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201411/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/dfp/v201411/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py
deleted file mode 100755
index b77e1222..00000000
--- a/examples/dfp/v201411/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py
+++ /dev/null
@@ -1,81 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new content metadata key hierarchies.
-
-To determine which content metadata key hierarchies exist, run
-get_all_content_metadata_key_hierarchies.py.
-
-This feature is only available to DFP video publishers.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContentMetadataKeyHierarchyService.createContentMetadataKeyHierarchies
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the IDs of the custom targeting keys for the hierarchy.
-HIERARCHY_LEVEL_ONE_KEY_ID = 'INSERT_LEVEL_ONE_CUSTOM_TARGETING_KEY_ID_HERE'
-HIERARCHY_LEVEL_TWO_KEY_ID = 'INSERT_LEVEL_TWO_CUSTOM_TARGETING_KEY_ID_HERE'
-
-
-def main(client, hierarchy_level_one_key_id, hierarchy_level_two_key_id):
- # Initialize appropriate service.
- content_metadata_key_hierarchy_service = client.GetService(
- 'ContentMetadataKeyHierarchyService', version='v201411')
-
- hierarchy_level_1 = {
- 'customTargetingKeyId': hierarchy_level_one_key_id,
- 'hierarchyLevel': '1'
- }
-
- hierarchy_level_2 = {
- 'customTargetingKeyId': hierarchy_level_two_key_id,
- 'hierarchyLevel': '2'
- }
-
- hierarchy_levels = [hierarchy_level_1, hierarchy_level_2]
-
- # Create content metadata key hierarchy object.
- content_metadata_key_hierarchy = {
- 'name': 'Content Metadata Key Hierarchy #%s' % uuid.uuid4(),
- 'hierarchyLevels': hierarchy_levels
- }
-
- content_metadata_key_hierarchies = (
- content_metadata_key_hierarchy_service
- .createContentMetadataKeyHierarchies([content_metadata_key_hierarchy]))
-
- # Display results.
- for content_metadata_key_hierarchy in content_metadata_key_hierarchies:
- print ('Content metadata key hierarchy with id \'%s\' and name \'%s\''
- ' was created.' % (content_metadata_key_hierarchy['id'],
- content_metadata_key_hierarchy['name']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, HIERARCHY_LEVEL_ONE_KEY_ID, HIERARCHY_LEVEL_TWO_KEY_ID)
diff --git a/examples/dfp/v201411/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py b/examples/dfp/v201411/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py
deleted file mode 100755
index 063cccca..00000000
--- a/examples/dfp/v201411/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py
+++ /dev/null
@@ -1,88 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example deletes content metadata key hierarchies.
-
-To determine which content metadata key hierarchies exist, run
-get_all_content_metadata_key_hierarchies.py.
-
-This feature is only available to DFP video publishers.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContentMetadataKeyHierarchyService.getContentMetadataKeyHierarchiesByStatement
- ContentMetadataKeyHierarchyService.perfomContentMetadataKeyHierarchyAction
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the content metadata key hierarchy to delete.
-CONTENT_METADATA_KEY_HIERARCHY_ID = (
- 'INSERT_CONTENT_METADATA_KEY_HIERARCHY_ID_HERE')
-
-
-def main(client, content_metadata_key_hierarchy_id):
- # Initialize appropriate service.
- content_metadata_key_hierarchy_service = client.GetService(
- 'ContentMetadataKeyHierarchyService', version='v201411')
-
- # Create a query to select a single content metadata key hierarchy.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': content_metadata_key_hierarchy_id
- }
- }]
-
- query = 'WHERE id = :id ORDER BY id ASC'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get a single content metadata key hierarchy by statement.
- response = (content_metadata_key_hierarchy_service
- .getContentMetadataKeyHierarchiesByStatement(
- statement.ToStatement())[0])
- content_metadata_key_hierarchies = (response['results']
- if 'results' in response else None)
-
- # Display results.
- if content_metadata_key_hierarchies:
- for content_metadata_key_hierarchy in content_metadata_key_hierarchies:
- print ('Content metadata key hierarchy with ID \'%s\' and name \'%s\' '
- 'will be deleted.' % (content_metadata_key_hierarchy['id'],
- content_metadata_key_hierarchy['name']))
-
- # Perform action.
- result = (content_metadata_key_hierarchy_service
- .performContentMetadataKeyHierarchyAction(
- {'type': 'DeleteContentMetadataKeyHierarchies'},
- statement.ToStatement()))[0]
-
- # Display results.
- print ('Number of content metadata key hierarchies deleted: %s' %
- result['numChanges'])
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CONTENT_METADATA_KEY_HIERARCHY_ID)
diff --git a/examples/dfp/v201411/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/dfp/v201411/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py
deleted file mode 100755
index c0ae709c..00000000
--- a/examples/dfp/v201411/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py
+++ /dev/null
@@ -1,66 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all content metadata key hierarchies.
-
-This feature is only available to DFP video publishers.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContentMetadataKeyHierarchyService.getContentMetadataKeyHierarchiesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- content_metadata_key_hierarchy_service = client.GetService(
- 'ContentMetadataKeyHierarchyService', version='v201411')
-
- # Create statement object to select all content.
- statement = dfp.FilterStatement()
-
- # Get content by statement.
- while True:
- response = (content_metadata_key_hierarchy_service
- .getContentMetadataKeyHierarchiesByStatement(
- statement.ToStatement())[0])
- content_metadata_key_hierarchies = (response['results']
- if 'results' in response else None)
- if content_metadata_key_hierarchies:
- # Display results.
- for content_metadata_key_hierarchy in content_metadata_key_hierarchies:
- print ('Content metadata key hierarchyy with id \'%s\' and name \'%s\''
- ' was found.' % (content_metadata_key_hierarchy['id'],
- content_metadata_key_hierarchy['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/dfp/v201411/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py
deleted file mode 100755
index 74401822..00000000
--- a/examples/dfp/v201411/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py
+++ /dev/null
@@ -1,100 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates content metadata key hierarchies.
-
-To determine which content metadata key hierarchies exist, run
-get_all_content_metadata_key_hierarchies.py.
-
-This feature is only available to DFP video publishers.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContentMetadataKeyHierarchyService.getContentMetadataKeyHierarchiesByStatement
- ContentMetadataKeyHierarchyService.updateContentMetadataKeyHierarchies
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the content metadata key hierarchy to update.
-CONTENT_METADATA_KEY_HIERARCHY_ID = (
- 'INSERT_CONTENT_METADATA_KEY_HIERARCHY_ID_HERE')
-# Set the ID of the custom targeting key to be added as a hierarchy level.
-CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'
-
-
-def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id):
- # Initialize appropriate service.
- content_metadata_key_hierarchy_service = client.GetService(
- 'ContentMetadataKeyHierarchyService', version='v201411')
-
- # Create a query to select a single content metadata key hierarchy.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': content_metadata_key_hierarchy_id
- }
- }]
-
- query = 'WHERE id = :id ORDER BY id ASC'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get a single content metadata key hierarchy by statement.
- response = (content_metadata_key_hierarchy_service
- .getContentMetadataKeyHierarchiesByStatement(
- statement.ToStatement()))[0]
- content_metadata_key_hierarchies = (response['results']
- if 'results' in response else None)
-
- if content_metadata_key_hierarchies:
- content_metadata_key_hierarchy = content_metadata_key_hierarchies[0]
-
- # Update the content metadata key hierarchy by adding a hierarchy level.
- hierarchy_levels = content_metadata_key_hierarchy['hierarchyLevels']
-
- hierarchy_level = {
- 'customTargetingKeyId': custom_targeting_key_id,
- 'hierarchyLevel': str(len(hierarchy_levels) + 1)
- }
-
- content_metadata_key_hierarchy['hierarchyLevels'] = (
- hierarchy_levels.append(hierarchy_level))
-
- content_metadata_key_hierarchies = (
- content_metadata_key_hierarchy_service
- .updateContentMetadataKeyHierarchies(content_metadata_key_hierarchies))
-
- # Display results.
- for content_metadata_key_hierarchy in content_metadata_key_hierarchies:
- print ('Content metadata key hierarchy with id \'%s\' and name \'%s\''
- ' was updated.' % (content_metadata_key_hierarchy['id'],
- content_metadata_key_hierarchy['name']))
-
- else:
- print 'No content metadata key hierarchies were found'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CONTENT_METADATA_KEY_HIERARCHY_ID, CUSTOM_TARGETING_KEY_ID)
diff --git a/examples/dfp/v201411/content_service/__init__.py b/examples/dfp/v201411/content_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201411/content_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201411/content_service/get_all_content.py b/examples/dfp/v201411/content_service/get_all_content.py
deleted file mode 100755
index 0ff9e1e3..00000000
--- a/examples/dfp/v201411/content_service/get_all_content.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all content.
-
-This feature is only available to DFP video publishers.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContentService.getContentByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- content_service = client.GetService('ContentService', version='v201411')
-
- # Create statement object to select all content.
- statement = dfp.FilterStatement()
-
- # Get content by statement.
- while True:
- response = content_service.getContentByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for content_item in response['results']:
- print ('Content with id \'%s\', name \'%s\', and status \'%s\' was '
- 'found.' % (content_item['id'], content_item['name'],
- content_item['status']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/content_service/get_content_by_category.py b/examples/dfp/v201411/content_service/get_content_by_category.py
deleted file mode 100755
index 6273ebc0..00000000
--- a/examples/dfp/v201411/content_service/get_content_by_category.py
+++ /dev/null
@@ -1,112 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all active content categorized as a "comedy" using the
-network's content browse custom targeting key.
-
-This feature is only available to DFP video publishers.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContentService.getContentByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- content_service = client.GetService('ContentService', version='v201411')
- network_service = client.GetService('NetworkService', version='v201411')
- custom_targeting_service = client.GetService(
- 'CustomTargetingService', version='v201411')
-
- # Get the network's content browse custom targeting key.
- network = network_service.getCurrentNetwork()
- key_id = network['contentBrowseCustomTargetingKeyId']
-
- # Create a statement to select the categories matching the name comedy.
- values = [
- {
- 'key': 'contentBrowseCustomTargetingKeyId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': key_id
- }
- },
- {
- 'key': 'category',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'comedy'
- }
- }
- ]
- category_filter_query = ('WHERE customTargetingKeyId = '
- ':contentBrowseCustomTargetingKeyId and name = '
- ':category')
- category_filter_statement = dfp.FilterStatement(
- category_filter_query, values, 1)
-
- # Get categories matching the filter statement.
- response = custom_targeting_service.getCustomTargetingValuesByStatement(
- category_filter_statement.ToStatement())
-
- # Get the custom targeting value ID for the comedy category.
- if 'results' in response:
- category_custom_targeting_value_id = (response['results']['id'])
-
- # Create a statement to select the active content.
- content_values = [
- {
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ACTIVE'
- }
- }
- ]
- content_query = 'WHERE status = :status'
- content_statement = dfp.FilterStatement(content_query, content_values)
-
- while True:
- # Get the content by statement and custom targeting value.
- response = content_service.getContentByStatementAndCustomTargetingValue(
- content_statement.ToStatement(),
- category_custom_targeting_value_id)
- if 'results' in response:
- # Display results.
- for content_item in response['results']:
- print ('Content with id \'%s\', name \'%s\', and status \'%s\' was '
- 'found.' % (content_item['id'], content_item['name'],
- content_item['status']))
- content_statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/creative_service/__init__.py b/examples/dfp/v201411/creative_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201411/creative_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201411/creative_service/create_creative_from_template.py b/examples/dfp/v201411/creative_service/create_creative_from_template.py
deleted file mode 100755
index 3db1c257..00000000
--- a/examples/dfp/v201411/creative_service/create_creative_from_template.py
+++ /dev/null
@@ -1,104 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates a new template creative for a given advertiser.
-
-To determine which companies are advertisers, run get_advertisers.py.
-To determine which creative templates exist, run
-get_all_creative_templates.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeService.createCreative
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import base64
-import os
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set id of the advertiser (company) that the creative will be assigned to.
-ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
-
-
-def main(client, advertiser_id):
- # Initialize appropriate service.
- creative_service = client.GetService('CreativeService', version='v201411')
-
- # Use the image banner with optional third party tracking template.
- creative_template_id = '10000680'
-
- image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data',
- 'medium_rectangle.jpg'), 'r').read()
- image_data = base64.encodestring(image_data)
- # Create creative from templates.
- creative = {
- 'xsi_type': 'TemplateCreative',
- 'name': 'Template Creative #%s' % uuid.uuid4(),
- 'advertiserId': advertiser_id,
- 'size': {'width': '300', 'height': '250'},
- 'creativeTemplateId': creative_template_id,
- 'creativeTemplateVariableValues': [
- {
- 'xsi_type': 'AssetCreativeTemplateVariableValue',
- 'uniqueName': 'Imagefile',
- 'assetByteArray': image_data,
- 'fileName': 'image%s.jpg' % uuid.uuid4()
- },
- {
- 'xsi_type': 'LongCreativeTemplateVariableValue',
- 'uniqueName': 'Imagewidth',
- 'value': '300'
- },
- {
- 'xsi_type': 'LongCreativeTemplateVariableValue',
- 'uniqueName': 'Imageheight',
- 'value': '250'
- },
- {
- 'xsi_type': 'UrlCreativeTemplateVariableValue',
- 'uniqueName': 'ClickthroughURL',
- 'value': 'www.google.com'
- },
- {
- 'xsi_type': 'StringCreativeTemplateVariableValue',
- 'uniqueName': 'Targetwindow',
- 'value': '_blank'
- }
- ]
- }
-
- # Call service to create the creative.
- creative = creative_service.createCreative(creative)
-
- # Display results.
- print ('Template creative with id \'%s\', name \'%s\', and type \'%s\' was '
- 'created and can be previewed at %s.'
- % (creative['id'], creative['name'], creative['Creative.Type'],
- creative['previewUrl']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ADVERTISER_ID)
diff --git a/examples/dfp/v201411/creative_service/create_creatives.py b/examples/dfp/v201411/creative_service/create_creatives.py
deleted file mode 100755
index 184aefc3..00000000
--- a/examples/dfp/v201411/creative_service/create_creatives.py
+++ /dev/null
@@ -1,94 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new image creatives for a given advertiser.
-
-To determine which companies are advertisers, run get_advertisers.py.
-To determine which creatives already exist, run get_all_creatives.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeService.createCreatives
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import base64
-import os
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set id of the advertiser (company) that all creatives will be assigned to.
-ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
-
-
-def main(client, advertiser_id):
- # Initialize appropriate service.
- creative_service = client.GetService('CreativeService', version='v201411')
-
- # Create creative objects.
- creatives = []
- with open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data',
- 'medium_rectangle.jpg'), 'r') as image:
- image_data = base64.encodestring(image.read())
-
- for i in xrange(5):
- # Create creative size.
- size = {
- 'width': '300',
- 'height': '250'
- }
-
- # Create image asset.
- creative_asset = {
- 'xsi_type': 'CreativeAsset',
- 'fileName': 'image.jpg',
- 'assetByteArray': image_data,
- 'size': size
- }
-
- # Create an image creative.
- creative = {
- 'xsi_type': 'ImageCreative',
- 'name': 'Image Creative #%s' % uuid.uuid4(),
- 'advertiserId': advertiser_id,
- 'destinationUrl': 'http://google.com',
- 'size': size,
- 'primaryImageAsset': creative_asset
- }
-
- creatives.append(creative)
-
- # Add creatives.
- creatives = creative_service.createCreatives(creatives)
-
- # Display results.
- for creative in creatives:
- print ('Image creative with id \'%s\', name \'%s\', and type \'%s\' was '
- 'created and can be previewed at %s.'
- % (creative['id'], creative['name'], creative['Creative.Type'],
- creative['previewUrl']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ADVERTISER_ID)
diff --git a/examples/dfp/v201411/creative_service/create_custom_creative.py b/examples/dfp/v201411/creative_service/create_custom_creative.py
deleted file mode 100755
index 443c98f0..00000000
--- a/examples/dfp/v201411/creative_service/create_custom_creative.py
+++ /dev/null
@@ -1,90 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates a custom creative for a given advertiser.
-
-This feature is only available to DFP premium solution networks. To determine
-which companies are advertisers, run get_advertisers.py. To determine
-which creative templates exist, run get_all_creative_templates.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeService.createCreative
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import base64
-import os
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set id of the advertiser (company) that the creative will be assigned to.
-ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
-
-
-def main(client, advertiser_id):
- # Initialize appropriate service.
- creative_service = client.GetService('CreativeService', version='v201411')
-
- # Get the image data for the creative.
- image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data',
- 'medium_rectangle.jpg'), 'r').read()
- image_data = base64.encodestring(image_data)
-
- # Create the HTML snippet used in the custom creative.
- html_snippet = (' Click above for '
- 'great deals!') % ('%%CLICK_URL_UNESC%%', '%%DEST_URL%%',
- '%%FILE:IMAGE_ASSET%%')
-
- # Create custom creative.
- creative = {
- 'xsi_type': 'CustomCreative',
- 'name': 'Custom Creative #%s' % uuid.uuid4(),
- 'advertiserId': advertiser_id,
- 'size': {'width': '300', 'height': '250'},
- 'destinationUrl': 'http://google.com',
- 'customCreativeAssets': [
- {
- 'xsi_type': 'CustomCreativeAsset',
- 'macroName': 'IMAGE_ASSET',
- 'assetByteArray': image_data,
- 'fileName': 'image%s.jpg' % uuid.uuid4()
- }
- ],
- 'htmlSnippet': html_snippet
- }
-
- # Call service to create the creative.
- creative = creative_service.createCreative(creative)
-
- # Display results.
- if creative:
- print ('Template creative with id \'%s\', name \'%s\', and type \'%s\' was '
- 'created and can be previewed at %s.'
- % (creative['id'], creative['name'], creative['Creative.Type'],
- creative['previewUrl']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ADVERTISER_ID)
diff --git a/examples/dfp/v201411/creative_service/get_all_creatives.py b/examples/dfp/v201411/creative_service/get_all_creatives.py
deleted file mode 100755
index 999cf422..00000000
--- a/examples/dfp/v201411/creative_service/get_all_creatives.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all creatives.
-
-To create creatives, run create_creatives.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeService.getCreativesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- creative_service = client.GetService('CreativeService', version='v201411')
-
- # Create statement object to select all creatives.
- statement = dfp.FilterStatement()
-
- # Get creatives by statement.
- while True:
- response = creative_service.getCreativesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for creative in response['results']:
- print ('Creative with id \'%s\', name \'%s\', and type \'%s\' was '
- 'found.' % (creative['id'], creative['name'],
- creative['Creative.Type']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/creative_service/get_creatives_by_statement.py b/examples/dfp/v201411/creative_service/get_creatives_by_statement.py
deleted file mode 100755
index 1c391510..00000000
--- a/examples/dfp/v201411/creative_service/get_creatives_by_statement.py
+++ /dev/null
@@ -1,72 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all image creatives.
-
-To create an image creative, run create_creatives.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeService.getCreativesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- creative_service = client.GetService('CreativeService', version='v201411')
-
- # Create statement object to only select image creatives.
- values = [{
- 'key': 'creativeType',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ImageCreative'
- }
- }]
- query = 'WHERE creativeType = :creativeType'
- statement = dfp.FilterStatement(query, values)
-
- # Get creatives by statement.
- while True:
- response = creative_service.getCreativesByStatement(
- statement.ToStatement())
- creatives = response['results']
-
- if creatives:
- # Display results.
- for creative in creatives:
- print ('Creative with id \'%s\', name \'%s\', and type \'%s\' was '
- 'found.' % (creative['id'], creative['name'],
- creative['Creative.Type']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/creative_service/update_creatives.py b/examples/dfp/v201411/creative_service/update_creatives.py
deleted file mode 100755
index 8222690e..00000000
--- a/examples/dfp/v201411/creative_service/update_creatives.py
+++ /dev/null
@@ -1,84 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates the destination URL of a single image creative.
-
-To determine which image creatives exist, run get_all_creatives.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeService.updateCreatives
- CreativeService.getCreativesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-IMAGE_CREATIVE_ID = 'INSERT_IMAGE_CREATIVE_ID_HERE'
-
-
-def main(client, image_creative_id):
- # Initialize appropriate service.
- creative_service = client.GetService('CreativeService', version='v201411')
-
- # Create statement object to get all image creatives.
- values = [{
- 'key': 'type',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ImageCreative'
- }
- }, {
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': image_creative_id
- }
- }]
- query = 'WHERE creativeType = :type AND id = :id'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get creatives by statement.
- response = creative_service.getCreativesByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- # Update each local creative object by changing its destination URL.
- updated_creatives = []
- for creative in response['results']:
- creative['destinationUrl'] = 'http://news.google.com'
- updated_creatives.append(creative)
-
- # Update creatives remotely.
- creatives = creative_service.updateCreatives(updated_creatives)
-
- # Display results.
- for creative in creatives:
- print ('Image creative with id \'%s\' and destination URL \'%s\' was '
- 'updated.' % (creative['id'], creative['destinationUrl']))
- else:
- print 'No creatives found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, IMAGE_CREATIVE_ID)
diff --git a/examples/dfp/v201411/creative_set_service/__init__.py b/examples/dfp/v201411/creative_set_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201411/creative_set_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201411/creative_set_service/associate_creative_set_to_line_item.py b/examples/dfp/v201411/creative_set_service/associate_creative_set_to_line_item.py
deleted file mode 100755
index 134b1e6d..00000000
--- a/examples/dfp/v201411/creative_set_service/associate_creative_set_to_line_item.py
+++ /dev/null
@@ -1,59 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates a line item creative association for a creative
-set.
-
-To create creative sets, run create_creative_set.py. To create creatives, run
-create_creatives.py. To determine which LICAs exist, run get_all_licas.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: LineItemCreativeAssociationService.createLineItemCreativeAssociations
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-CREATIVE_SET_ID = 'INSERT_CREATIVE_SET_ID_HERE'
-LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
-
-
-def main(client, creative_set_id, line_item_id):
- # Initialize appropriate service.
- lica_service = client.GetService(
- 'LineItemCreativeAssociationService', version='v201411')
-
- # Create LICA for a creative set.
- lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id}
-
- # Add LICA.
- lica = lica_service.createLineItemCreativeAssociations([lica])
-
- # Display results.
- print (('LICA with line item ID \'%s\' and creative set ID \'%s\' was '
- 'created.') % (lica['lineItemId'], lica['creativeSetId']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CREATIVE_SET_ID, LINE_ITEM_ID)
diff --git a/examples/dfp/v201411/creative_set_service/create_creative_set.py b/examples/dfp/v201411/creative_set_service/create_creative_set.py
deleted file mode 100755
index 70b26d62..00000000
--- a/examples/dfp/v201411/creative_set_service/create_creative_set.py
+++ /dev/null
@@ -1,64 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new creative sets.
-
-To determine which creative sets exist, run get_all_creative_sets.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeSetService.createCreativeSet
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-MASTER_CREATIVE_ID = 'INSERT_MASTER_CREATIVE_ID_HERE'
-COMPANION_CREATIVE_ID = 'INSERT_COMPANION_CREATIVE_ID_HERE'
-
-
-def main(client, master_creative_id, companion_creative_id):
- # Initialize appropriate service.
- creative_set_service = client.GetService('CreativeSetService',
- version='v201411')
-
- # Create creative set objects.
- creative_set = {'name': 'Creative set #%s' % uuid.uuid4(),
- 'masterCreativeId': master_creative_id,
- 'companionCreativeIds': [companion_creative_id]}
-
- # Add creative sets.
- creative_set = creative_set_service.createCreativeSet(creative_set)
-
- # Display results.
- if creative_set:
- print (('Creative set with ID \'%s\', master creative ID \'%s\', and '
- 'companion creative IDs {%s} was created.')
- % (creative_set['id'], creative_set['masterCreativeId'],
- ','.join(creative_set['companionCreativeIds'])))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, MASTER_CREATIVE_ID, COMPANION_CREATIVE_ID)
diff --git a/examples/dfp/v201411/creative_set_service/get_all_creative_sets.py b/examples/dfp/v201411/creative_set_service/get_all_creative_sets.py
deleted file mode 100755
index 7b53ea25..00000000
--- a/examples/dfp/v201411/creative_set_service/get_all_creative_sets.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all creative sets.
-
-To create creative sets, run create_creative_sets.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeSetService.getCreativeSetsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- creative_set_service = client.GetService('CreativeSetService',
- version='v201411')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get creative sets by statement.
- while True:
- response = creative_set_service.getCreativeSetsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for creative_set in response['results']:
- print ('Creative set with ID \'%s\' and name \'%s\' was found.'
- % (creative_set['id'], creative_set['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/creative_set_service/get_creative_sets_by_statement.py b/examples/dfp/v201411/creative_set_service/get_creative_sets_by_statement.py
deleted file mode 100755
index bee62a09..00000000
--- a/examples/dfp/v201411/creative_set_service/get_creative_sets_by_statement.py
+++ /dev/null
@@ -1,75 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all creative sets for a master creative.
-
-To create creative sets, run create_creative_sets.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeSetService.getCreativeSetsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-MASTER_CREATIVE_ID = 'INSERT_MASTER_CREATIVE_ID_HERE'
-
-
-def main(client, master_creative_id):
- # Initialize appropriate service.
- creative_set_service = client.GetService('CreativeSetService',
- version='v201411')
-
- # Create statement object to only select creative sets that have the given
- # master creative.
- values = [{
- 'key': 'masterCreativeId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': master_creative_id
- }
- }]
- query = 'WHERE masterCreativeId = :masterCreativeId'
- statement = dfp.FilterStatement(query, values)
-
- # Get creative sets by statement.
- while True:
- response = creative_set_service.getCreativeSetsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for creative_set in response['results']:
- print (('Creative set with ID \'%s\', master creative ID \'%s\', and '
- 'companion creative IDs {%s} was found.')
- % (creative_set['id'], creative_set['masterCreativeId'],
- ','.join(creative_set['companionCreativeIds'])))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, MASTER_CREATIVE_ID)
diff --git a/examples/dfp/v201411/creative_set_service/update_creative_set.py b/examples/dfp/v201411/creative_set_service/update_creative_set.py
deleted file mode 100755
index 49bedcef..00000000
--- a/examples/dfp/v201411/creative_set_service/update_creative_set.py
+++ /dev/null
@@ -1,82 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates a creative set by adding a companion creative.
-
-To determine which creative sets exist, run get_all_creative_sets.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeSetService.updateCreativeSet
- CreativeSetService.getCreativeSetsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the creative set to update.
-CREATIVE_SET_ID = 'INSERT_CREATIVE_SET_ID_HERE'
-COMPANION_CREATIVE_ID = 'INSERT_COMPANION_CREATIVE_ID_HERE'
-
-
-def main(client, creative_set_id, companion_creative_id):
- # Initialize appropriate service.
- creative_set_service = client.GetService('CreativeSetService',
- version='v201411')
-
- # Create statement to select a single creative set by ID.
- values = [{
- 'key': 'creativeSetId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': creative_set_id
- }
- }]
- query = 'WHERE id = :creativeSetId'
- statement = dfp.FilterStatement(query, values)
-
- # Get creative set.
- response = creative_set_service.getCreativeSetsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- updated_created_sets = []
- for creative_set in response['results']:
- creative_set['companionCreativeIds'].append(companion_creative_id)
- updated_created_sets.append(creative_set)
-
- # Update the creative sets on the server.
- creative_sets = creative_set_service.updateCreativeSet(updated_created_sets)
-
- # Display results.
- for creative_set in creative_sets:
- print (('Creative set with ID \'%s\', master creative ID \'%s\', and '
- 'companion creative IDs {%s} was updated.')
- % (creative_set['id'], creative_set['masterCreativeId'],
- ','.join(creative_set['companionCreativeIds'])))
- else:
- print 'No creative sets found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CREATIVE_SET_ID, COMPANION_CREATIVE_ID)
diff --git a/examples/dfp/v201411/creative_template_service/__init__.py b/examples/dfp/v201411/creative_template_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201411/creative_template_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201411/creative_template_service/get_all_creative_templates.py b/examples/dfp/v201411/creative_template_service/get_all_creative_templates.py
deleted file mode 100755
index 7896b6f6..00000000
--- a/examples/dfp/v201411/creative_template_service/get_all_creative_templates.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all creative templates.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeTemplateService.getCreativeTemplatesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- creative_template_service = client.GetService(
- 'CreativeTemplateService', version='v201411')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get creative templates by statement.
- while True:
- response = creative_template_service.getCreativeTemplatesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for template in response['results']:
- print ('Creative template with id \'%s\', name \'%s\', and type \'%s\' '
- 'was found.' % (template['id'],
- template['name'],
- template['type']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/creative_template_service/get_creative_templates_by_statement.py b/examples/dfp/v201411/creative_template_service/get_creative_templates_by_statement.py
deleted file mode 100755
index dee9b434..00000000
--- a/examples/dfp/v201411/creative_template_service/get_creative_templates_by_statement.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all system defined creative templates.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeTemplateService.getCreativeTemplatesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- creative_template_service = client.GetService(
- 'CreativeTemplateService', version='v201411')
-
- # Create statement object to only select system defined creative templates.
- values = [{
- 'key': 'creativeTemplateType',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'SYSTEM_DEFINED'
- }
- }]
- query = 'WHERE type = :creativeTemplateType'
- statement = dfp.FilterStatement(query, values)
-
- # Get creative templates by statement.
- while True:
- response = creative_template_service.getCreativeTemplatesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for template in response['results']:
- print ('Creative template with id \'%s\', name \'%s\', and type \'%s\' '
- 'was found.' % (template['id'],
- template['name'],
- template['type']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/creative_wrapper_service/create_creative_wrappers.py b/examples/dfp/v201411/creative_wrapper_service/create_creative_wrappers.py
deleted file mode 100755
index ebc814e0..00000000
--- a/examples/dfp/v201411/creative_wrapper_service/create_creative_wrappers.py
+++ /dev/null
@@ -1,66 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates a new creative wrapper.
-
-Creative wrappers must be associated with a LabelType.CREATIVE_WRAPPER label and
-applied to ad units by AdUnit.appliedLabels. To determine which creative
-wrappers exist, run get_all_creative_wrappers.py
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeWrapperService.createCreativeWrappers
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-LABEL_ID = 'INSERT_CREATIVE_WRAPPER_LABEL_ID_HERE'
-
-
-def main(client, label_id):
- # Initialize appropriate service.
- creative_wrapper_service = client.GetService('CreativeWrapperService',
- version='v201411')
-
- # Create creative wrapper objects.
- creative_wrapper = {
- # A label can only be associated with one creative wrapper.
- 'labelId': label_id,
- 'ordering': 'INNER',
- 'header': {'htmlSnippet': 'My creative wrapper header'},
- 'footer': {'htmlSnippet': 'My creative wrapper footer'}
- }
-
- # Add creative wrapper.
- creative_wrappers = creative_wrapper_service.createCreativeWrappers(
- [creative_wrapper])
-
- # Display results.
- for creative_wrapper in creative_wrappers:
- print ('Creative wrapper with ID \'%s\' applying to label \'%s\' was '
- 'created.' % (creative_wrapper['id'], creative_wrapper['labelId']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, LABEL_ID)
diff --git a/examples/dfp/v201411/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201411/creative_wrapper_service/deactivate_creative_wrapper.py
deleted file mode 100755
index 2090cf13..00000000
--- a/examples/dfp/v201411/creative_wrapper_service/deactivate_creative_wrapper.py
+++ /dev/null
@@ -1,92 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example deactivates a creative wrapper belonging to a label.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeWrapperService.getCreativeWrapperByStatement
-Tags: CreativeWrapperService.performCreativeWrapperAction
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-LABEL_ID = 'INSERT_LABEL_ID_HERE'
-
-
-def main(client, label_id):
- # Initialize appropriate service.
- creative_wrapper_service = client.GetService('CreativeWrapperService',
- version='v201411')
-
- # Create a query to select the active creative wrappers for the given label.
- values = [{
- 'key': 'labelId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': label_id
- }
- }, {
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ACTIVE'
- }
- }]
- query = 'WHERE status = :status AND labelId = :labelId'
- statement = dfp.FilterStatement(query, values)
-
- creative_wrappers_deactivated = 0
-
- # Get creative wrappers by statement.
- while True:
- response = creative_wrapper_service.getCreativeWrappersByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for creative_wrapper in response['results']:
- print ('Creative wrapper with ID \'%s\' applying to label \'%s\' with '
- 'status \'%s\' will be deactivated.' %
- (creative_wrapper['id'],
- creative_wrapper['labelId'],
- creative_wrapper['status']))
- # Perform action.
- result = creative_wrapper_service.performCreativeWrapperAction(
- {'xsi_type': 'DeactivateCreativeWrappers'}, statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- creative_wrappers_deactivated += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Display results.
- if creative_wrappers_deactivated > 0:
- print ('Number of creative wrappers deactivated: %s' %
- creative_wrappers_deactivated)
- else:
- print 'No creative wrappers were deactivated.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, LABEL_ID)
diff --git a/examples/dfp/v201411/creative_wrapper_service/get_active_creative_wrappers.py b/examples/dfp/v201411/creative_wrapper_service/get_active_creative_wrappers.py
deleted file mode 100755
index 0c9dc2b2..00000000
--- a/examples/dfp/v201411/creative_wrapper_service/get_active_creative_wrappers.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all active creative wrappers.
-
-To create creative wrappers, run create_creative_wrappers.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeWrapperService.getCreativeWrappersByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- creative_wrapper_service = client.GetService('CreativeWrapperService',
- version='v201411')
-
- # Create statement object to only select active creative wrappers.
- values = [{
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ACTIVE'
- }
- }]
- query = 'WHERE status = :status'
- statement = dfp.FilterStatement(query, values)
-
- # Get creative wrappers by statement.
- while True:
- response = creative_wrapper_service.getCreativeWrappersByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for creative_wrapper in response['results']:
- print ('Creative wrapper with ID \'%s\' applying to label \'%s\' was '
- 'found.' % (creative_wrapper['id'], creative_wrapper['labelId']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/creative_wrapper_service/get_all_creative_wrappers.py b/examples/dfp/v201411/creative_wrapper_service/get_all_creative_wrappers.py
deleted file mode 100755
index d55662b6..00000000
--- a/examples/dfp/v201411/creative_wrapper_service/get_all_creative_wrappers.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all creative wrappers.
-
-To create creative wrappers, run create_creative_wrappers.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeWrapperService.getCreativeWrappersByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- creative_wrapper_service = client.GetService('CreativeWrapperService',
- version='v201411')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get creative wrappers by statement.
- while True:
- response = creative_wrapper_service.getCreativeWrappersByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for creative_wrapper in response['results']:
- print ('Creative wrapper with ID \'%s\' applying to label \'%s\' was '
- 'found.' % (creative_wrapper['id'], creative_wrapper['labelId']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/creative_wrapper_service/update_creative_wrappers.py b/examples/dfp/v201411/creative_wrapper_service/update_creative_wrappers.py
deleted file mode 100755
index 681e06b6..00000000
--- a/examples/dfp/v201411/creative_wrapper_service/update_creative_wrappers.py
+++ /dev/null
@@ -1,81 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates a creative wrapper to the 'OUTER' wrapping order.
-
-To determine which creative wrappers exist, run get_all_creative_wrappers.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeWrapperService.getCreativeWrappersByStatement
-Tags: CreativeWrapperService.updateCreativeWrappers
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the creative wrapper to update.
-CREATIVE_WRAPPER_ID = 'INSERT_CREATIVE_WRAPPER_ID_HERE'
-
-
-def main(client, creative_wrapper_id):
- # Initialize appropriate service.
- creative_wrapper_service = client.GetService('CreativeWrapperService',
- version='v201411')
-
- # Create statement to get a creative wrapper by ID.
- values = [{
- 'key': 'creativeWrapperId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': creative_wrapper_id
- }
- }]
- query = 'WHERE id = :creativeWrapperId'
- statement = dfp.FilterStatement(query, values)
-
- # Get creative wrappers.
- response = creative_wrapper_service.getCreativeWrappersByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- updated_creative_wrappers = []
- for creative_wrapper in response['results']:
- creative_wrapper['ordering'] = 'OUTER'
- updated_creative_wrappers.append(creative_wrapper)
-
- # Update the creative wrappers on the server.
- creative_wrappers = creative_wrapper_service.updateCreativeWrappers(
- updated_creative_wrappers)
-
- # Display results.
- for creative_wrapper in creative_wrappers:
- print (('Creative wrapper with ID \'%s\' and wrapping order \'%s\' '
- 'was updated.') % (creative_wrapper['id'],
- creative_wrapper['ordering']))
- else:
- print 'No creative wrappers found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CREATIVE_WRAPPER_ID)
diff --git a/examples/dfp/v201411/custom_field_service/__init__.py b/examples/dfp/v201411/custom_field_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201411/custom_field_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201411/custom_field_service/create_custom_field_options.py b/examples/dfp/v201411/custom_field_service/create_custom_field_options.py
deleted file mode 100755
index 428865a7..00000000
--- a/examples/dfp/v201411/custom_field_service/create_custom_field_options.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates custom field options for a drop-down custom field.
-
-Once created, custom field options can be found under the options fields of the
-drop-down custom field and they cannot be deleted. To determine which custom
-fields exist, run get_all_custom_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomFieldService.createCustomFieldOptions
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the drop-down custom field to create options for.
-CUSTOM_FIELD_ID = 'INSERT_DROP_DOWN_CUSTOM_FIELD_ID_HERE'
-
-
-def main(client, custom_field_id):
- # Initialize appropriate service.
- custom_field_service = client.GetService(
- 'CustomFieldService', version='v201411')
-
- # Create custom field options.
- custom_field_options = [
- {
- 'displayName': 'Approved',
- 'customFieldId': custom_field_id
- },
- {
- 'displayName': 'Unapproved',
- 'customFieldId': custom_field_id
- }
- ]
-
- # Add custom field options.
- custom_field_options = custom_field_service.createCustomFieldOptions(
- custom_field_options)
-
- # Display results.
- for custom_field_option in custom_field_options:
- print ('Custom field option with ID \'%s\' and name \'%s\' was created.'
- % (custom_field_option['id'], custom_field_option['displayName']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CUSTOM_FIELD_ID)
diff --git a/examples/dfp/v201411/custom_field_service/create_custom_fields.py b/examples/dfp/v201411/custom_field_service/create_custom_fields.py
deleted file mode 100755
index ec674836..00000000
--- a/examples/dfp/v201411/custom_field_service/create_custom_fields.py
+++ /dev/null
@@ -1,69 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates custom fields.
-
-To determine which custom fields exist, run get_all_custom_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomFieldService.createCustomFields
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- custom_field_service = client.GetService(
- 'CustomFieldService', version='v201411')
-
- # Create custom field objects.
- custom_fields = [
- {
- 'name': 'Customer comments #%s' % uuid.uuid4(),
- 'entityType': 'LINE_ITEM',
- 'dataType': 'STRING',
- 'visibility': 'FULL'
- }, {
- 'name': 'Internal approval status #%s' % uuid.uuid4(),
- 'entityType': 'LINE_ITEM',
- 'dataType': 'DROP_DOWN',
- 'visibility': 'FULL'
- }
- ]
-
- # Add custom fields.
- custom_fields = custom_field_service.createCustomFields(custom_fields)
-
- # Display results.
- for custom_field in custom_fields:
- print ('Custom field with ID \'%s\' and name \'%s\' was created.'
- % (custom_field['id'], custom_field['name']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201411/custom_field_service/deactivate_all_line_item_custom_fields.py
deleted file mode 100755
index d80b74d5..00000000
--- a/examples/dfp/v201411/custom_field_service/deactivate_all_line_item_custom_fields.py
+++ /dev/null
@@ -1,89 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example deactivates all active line items custom fields.
-
-To determine which custom fields exist, run get_all_custom_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomFieldService.getCustomFieldsByStatement
-Tags: CustomFieldService.performCustomFieldAction
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- custom_field_service = client.GetService(
- 'CustomFieldService', version='v201411')
-
- # Create statement to select only active custom fields that apply to
- # line items.
- values = [
- {
- 'key': 'entityType',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'LINE_ITEM'
- }
- }, {
- 'key': 'isActive',
- 'value': {
- 'xsi_type': 'BooleanValue',
- 'value': 'true'
- }
- }
- ]
- query = 'WHERE entityType = :entityType and isActive = :isActive'
- statement = dfp.FilterStatement(query, values)
-
- custom_fields_deactivated = 0
-
- # Get custom fields by statement.
- while True:
- response = custom_field_service.getCustomFieldsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for custom_field in response['results']:
- print ('Custom field with ID \'%s\' and name \'%s\' will'
- ' be deactivated.' % (custom_field['id'], custom_field['name']))
- result = custom_field_service.performCustomFieldAction(
- {'xsi_type': 'DeactivateCustomFields'}, statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- custom_fields_deactivated += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- if custom_fields_deactivated > 0:
- print 'Number of custom fields deactivated: %s' % custom_fields_deactivated
- else:
- print 'No custom fields were deactivated.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/custom_field_service/get_all_custom_fields.py b/examples/dfp/v201411/custom_field_service/get_all_custom_fields.py
deleted file mode 100755
index d14472ca..00000000
--- a/examples/dfp/v201411/custom_field_service/get_all_custom_fields.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all custom fields.
-
-To create custom fields, run create_custom_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomFieldService.getCustomFieldsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- custom_field_service = client.GetService(
- 'CustomFieldService', version='v201411')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get custom fields by statement.
- while True:
- response = custom_field_service.getCustomFieldsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for custom_field in response['results']:
- print ('Custom field with ID \'%s\' and name \'%s\' was found.'
- % (custom_field['id'], custom_field['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/custom_field_service/get_all_line_item_custom_fields.py b/examples/dfp/v201411/custom_field_service/get_all_line_item_custom_fields.py
deleted file mode 100755
index 50b1c2fd..00000000
--- a/examples/dfp/v201411/custom_field_service/get_all_line_item_custom_fields.py
+++ /dev/null
@@ -1,72 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all custom fields that apply to line items.
-
-To create custom fields, run create_custom_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomFieldService.getCustomFieldsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- custom_field_service = client.GetService(
- 'CustomFieldService', version='v201411')
-
- # Create statement to select only custom fields that apply to line items.
- values = [{
- 'key': 'entityType',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'LINE_ITEM'
- }
- }]
- query = 'WHERE entityType = :entityType'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Get custom fields by statement.
- while True:
- response = custom_field_service.getCustomFieldsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for custom_field in response['results']:
- print ('Custom field with ID \'%s\' and name \'%s\' was found.'
- % (custom_field['id'], custom_field['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/custom_field_service/set_line_item_custom_field_value.py b/examples/dfp/v201411/custom_field_service/set_line_item_custom_field_value.py
deleted file mode 100755
index 19d4a6f2..00000000
--- a/examples/dfp/v201411/custom_field_service/set_line_item_custom_field_value.py
+++ /dev/null
@@ -1,160 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example sets custom field values on a line item.
-
-To determine which custom fields exist, run get_all_custom_fields.py.
-To determine which line item exist, run get_all_line_items.py.
-To create custom field options, run create_custom_field_options.py
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomFieldService.getCustomFieldsByStatement
- LineItemService.getLineItemsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the custom fields, custom field option, and line item.
-CUSTOM_FIELD_ID = 'INSERT_CUSTOM_FIELD_ID_HERE'
-DROP_DOWN_CUSTOM_FIELD_ID = 'INSERT_DROP_DOWN_CUSTOM_FIELD_ID_HERE'
-CUSTOM_FIELD_OPTION_ID = 'INSERT_CUSTOM_FIELD_OPTION_ID_HERE'
-LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
-
-
-def main(client, custom_field_id, drop_down_custom_field_id,
- custom_field_option_id, line_item_id):
- # Initialize appropriate services.
- custom_field_service = client.GetService(
- 'CustomFieldService', version='v201411')
-
- line_item_service = client.GetService('LineItemService', version='v201411')
-
- # Create statement to get a custom field.
- custom_field_values = [{
- 'key': 'customFieldId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': custom_field_id
- }
- }]
- custom_field_query = 'WHERE id = :customFieldId'
- custom_field_statement = dfp.FilterStatement(
- custom_field_query, custom_field_values, 1)
-
- # Get custom field.
- custom_field = custom_field_service.getCustomFieldsByStatement(
- custom_field_statement.ToStatement())['results'][0]
-
- # Create statement to get a drop down custom field.
- drop_down_custom_field_values = [{
- 'key': 'dropDownCustomFieldId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': drop_down_custom_field_id
- }
- }]
- drop_down_custom_field_query = 'WHERE id = :dropDownCustomFieldId'
- drop_down_custom_field_statement = dfp.FilterStatement(
- drop_down_custom_field_query, drop_down_custom_field_values, 1)
-
- # Get drop-down custom field.
- drop_down_custom_field = custom_field_service.getCustomFieldsByStatement(
- drop_down_custom_field_statement.ToStatement())['results'][0]
-
- # Create statement to get a line item.
- line_item_values = [{
- 'key': 'lineItemId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': line_item_id
- }
- }]
- line_item_query = 'WHERE id = :lineItemId'
- line_item_statement = dfp.FilterStatement(
- line_item_query, line_item_values, 1)
-
- # Get line item.
- line_item = line_item_service.getLineItemsByStatement(
- line_item_statement.ToStatement())['results'][0]
-
- if custom_field and line_item:
- # Create custom field values.
- custom_field_value = {
- 'customFieldId': custom_field['id'],
- 'xsi_type': 'CustomFieldValue',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'Custom field value'
- }
- }
-
- drop_down_custom_field_value = {
- 'customFieldId': drop_down_custom_field['id'],
- 'xsi_type': 'DropDownCustomFieldValue',
- 'customFieldOptionId': custom_field_option_id,
- }
-
- custom_field_values = [custom_field_value, drop_down_custom_field_value]
-
- old_custom_field_values = []
- if 'customFieldValues' in line_item:
- old_custom_field_values = line_item['customFieldValues']
-
- # Only add existing custom field values for different custom fields than the
- # ones you are setting.
- for old_custom_field_value in old_custom_field_values:
- if (old_custom_field_value['customFieldId'] !=
- custom_field_value['customFieldId']
- and old_custom_field_value['customFieldId'] !=
- drop_down_custom_field_value['customFieldId']):
- custom_field_values.append(old_custom_field_value)
-
- line_item['customFieldValues'] = custom_field_values
-
- # Update the line item on the server.
- line_items = line_item_service.updateLineItems([line_item])
-
- # Display results.
- for line_item in line_items:
- custom_field_value_strings = []
- for value in line_item['customFieldValues']:
- if value['BaseCustomFieldValue.Type'] == 'CustomFieldValue':
- custom_field_value_string = (
- '{ID: \'%s\', value: \'%s\'}'
- % (value['customFieldId'], value['value']['value']))
- elif value['BaseCustomFieldValue.Type'] == 'DropDownCustomFieldValue':
- custom_field_value_string = (
- '{ID: \'%s\', custom field option ID: \'%s\'}'
- % (value['customFieldId'], value['customFieldOptionId']))
- custom_field_value_strings.append(custom_field_value_string)
- print ('Line item with ID \'%s\' set with custom field values %s.'
- % (line_item['id'], ','.join(custom_field_value_strings)))
- else:
- print 'Line item or custom field not found.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CUSTOM_FIELD_ID, DROP_DOWN_CUSTOM_FIELD_ID,
- CUSTOM_FIELD_OPTION_ID, LINE_ITEM_ID)
diff --git a/examples/dfp/v201411/custom_field_service/update_custom_fields.py b/examples/dfp/v201411/custom_field_service/update_custom_fields.py
deleted file mode 100755
index ef78d4c6..00000000
--- a/examples/dfp/v201411/custom_field_service/update_custom_fields.py
+++ /dev/null
@@ -1,79 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates custom field descriptions.
-
-To determine which custom fields exist, run get_all_custom_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomFieldService.updateCustomFields
- CustomFieldService.getCustomFieldByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the custom field to update.
-CUSTOM_FIELD_ID = 'INSERT_CUSTOM_FIELD_ID_HERE'
-
-
-def main(client, custom_field_id):
- # Initialize appropriate service.
- custom_field_service = client.GetService(
- 'CustomFieldService', version='v201411')
-
- # Create statement to get a custom field.
- values = [{
- 'key': 'customFieldId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': custom_field_id
- }
- }]
- query = 'WHERE id = :customFieldId'
- statement = dfp.FilterStatement(query, values)
-
- # Get custom field.
- custom_fields = custom_field_service.getCustomsFieldByStatement(
- statement.ToStatement())
-
- if custom_fields:
- for custom_field in custom_fields:
- custom_field['description'] += ' Updated.'
-
- # Update the custom field on the server.
- custom_fields = custom_field_service.updateCustomFields(custom_fields)
-
- # Display results.
- for custom_field in custom_fields:
- print (('Custom field with ID \'%s\', name \'%s\', and '
- 'description \'%s\' was updated.')
- % (custom_field['id'], custom_field['name'],
- custom_field['description']))
- else:
- print 'No custom fields found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CUSTOM_FIELD_ID)
diff --git a/examples/dfp/v201411/custom_targeting_service/__init__.py b/examples/dfp/v201411/custom_targeting_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201411/custom_targeting_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201411/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/dfp/v201411/custom_targeting_service/create_custom_targeting_keys_and_values.py
deleted file mode 100755
index 2306e2c8..00000000
--- a/examples/dfp/v201411/custom_targeting_service/create_custom_targeting_keys_and_values.py
+++ /dev/null
@@ -1,136 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates new custom targeting keys and values.
-
-To determine which custom targeting keys and values exist, run
-get_all_custom_targeting_keys_and_values.py. To target these custom targeting
-keys and values, run target_custom_criteria_example.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomTargetingService.createCustomTargetingKeys
- CustomTargetingService.createCustomTargetingValues
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- custom_targeting_service = client.GetService(
- 'CustomTargetingService', version='v201411')
-
- # Create custom targeting key objects.
- keys = [
- {
- 'displayName': 'gender',
- 'name': 'g',
- 'type': 'PREDEFINED'
- },
- {
- 'displayName': 'car model',
- 'name': 'c',
- 'type': 'FREEFORM'
- },
- # Add predefined key that may be use for content targeting.
- {
- 'displayName': 'genre',
- 'name': 'genre',
- 'type': 'PREDEFINED'
- }
- ]
-
- # Add custom targeting keys.
- keys = custom_targeting_service.createCustomTargetingKeys(keys)
-
- # Display results.
- if keys:
- for key in keys:
- print ('A custom targeting key with id \'%s\', name \'%s\', and display '
- 'name \'%s\' was created.' % (key['id'], key['name'],
- key['displayName']))
- else:
- print 'No keys were created.'
-
- # Create custom targeting value objects.
- values = [
- {
- 'customTargetingKeyId': keys['id'],
- 'displayName': 'male',
- # Name is set to 1 so that the actual name can be hidden from website
- # users.
- 'name': '1',
- 'matchType': 'EXACT'
- },
- {
- 'customTargetingKeyId': keys['id'],
- 'displayName': 'female',
- # Name is set to 2 so that the actual name can be hidden from website
- # users.
- 'name': '2',
- 'matchType': 'EXACT'
- },
- {
- 'customTargetingKeyId': keys[1]['id'],
- 'displayName': 'honda civic',
- 'name': 'honda civic',
- 'matchType': 'EXACT'
- },
- {
- 'customTargetingKeyId': keys[1]['id'],
- 'displayName': 'toyota',
- 'name': 'toyota',
- 'matchType': 'EXACT'
- },
- {
- 'customTargetingKeyId': keys[2]['id'],
- 'displayName': 'comedy',
- 'name': 'comedy',
- 'matchType': 'EXACT'
- },
- {
- 'customTargetingKeyId': keys[2]['id'],
- 'displayName': 'drama',
- 'name': 'drama',
- 'matchType': 'EXACT'
- }
- ]
-
- # Add custom targeting values.
- values = custom_targeting_service.createCustomTargetingValues(values)
-
- # Display results.
- if values:
- for value in values:
- print ('A custom targeting value with id \'%s\', belonging to key with id'
- ' \'%s\', name \'%s\', and display name \'%s\' was created.'
- % (value['id'], value['customTargetingKeyId'], value['name'],
- value['displayName']))
- else:
- print 'No values were created.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/custom_targeting_service/delete_custom_targeting_keys.py b/examples/dfp/v201411/custom_targeting_service/delete_custom_targeting_keys.py
deleted file mode 100755
index 8191349f..00000000
--- a/examples/dfp/v201411/custom_targeting_service/delete_custom_targeting_keys.py
+++ /dev/null
@@ -1,85 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example deletes a custom targeting key by its name.
-
-To determine which custom targeting keys exist, run
-get_all_custom_targeting_keys_and_values.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomTargetingService.getCustomTargetingKeysByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-KEY_NAME = 'INSERT_CUSTOM_TARGETING_KEY_NAME_HERE'
-
-
-def main(client, key_name):
- # Initialize appropriate service.
- custom_targeting_service = client.GetService(
- 'CustomTargetingService', version='v201411')
-
- values = [{
- 'key': 'name',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': key_name
- }
- }]
- query = 'WHERE name = :name'
- statement = dfp.FilterStatement(query, values)
-
- deleted_custom_targeting_keys = 0
-
- # Get custom targeting keys.
- while True:
- response = custom_targeting_service.getCustomTargetingKeysByStatement(
- statement.ToStatement())
- if 'results' in response:
- key_ids = [key['id'] for key in response['results']]
- action = {'xsi_type': 'DeleteCustomTargetingKeys'}
- key_query = 'WHERE id IN (%s)' % ', '.join(key_ids)
- key_statement = dfp.FilterStatement(key_query)
-
- # Delete custom targeting keys.
- result = custom_targeting_service.performCustomTargetingKeyAction(
- action, key_statement.ToStatement())
-
- if result and int(result['numChanges']) > 0:
- deleted_custom_targeting_keys += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- if deleted_custom_targeting_keys > 0:
- print ('Number of custom targeting keys deleted: %s'
- % deleted_custom_targeting_keys)
- else:
- print 'No custom targeting keys were deleted.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, KEY_NAME)
diff --git a/examples/dfp/v201411/custom_targeting_service/delete_custom_targeting_values.py b/examples/dfp/v201411/custom_targeting_service/delete_custom_targeting_values.py
deleted file mode 100755
index bd39b35d..00000000
--- a/examples/dfp/v201411/custom_targeting_service/delete_custom_targeting_values.py
+++ /dev/null
@@ -1,86 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example deletes custom targeting values for a given custom targeting
-key.
-
-To determine which custom targeting keys and values exist, run
-get_all_custom_targeting_keys_and_values.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomTargetingService.getCustomTargetingValuesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'
-
-
-def main(client, key_id):
- # Initialize appropriate service.
- custom_targeting_service = client.GetService(
- 'CustomTargetingService', version='v201411')
-
- filter_values = [{
- 'key': 'keyId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': key_id
- }
- }]
- query = 'WHERE customTargetingKeyId = :keyId'
- statement = dfp.FilterStatement(query, filter_values)
-
- deleted_custom_targeting_values = 0
-
- # Get custom targeting values.
- while True:
- response = custom_targeting_service.getCustomTargetingValuesByStatement(
- statement.ToStatement())
- if 'results' in response:
- value_ids = [value['id'] for value in response['results']]
- action = {'xsi_type': 'DeleteCustomTargetingValues'}
- value_query = ('WHERE customTargetingKeyId = :keyId '
- 'AND id IN (%s)' % ', '.join(value_ids))
- value_statement = dfp.FilterStatement(value_query, filter_values)
-
- # Delete custom targeting values.
- result = custom_targeting_service.performCustomTargetingValueAction(
- action, value_statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- deleted_custom_targeting_values += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- if deleted_custom_targeting_values > 0:
- print ('Number of custom targeting values deleted: %s'
- % deleted_custom_targeting_values)
- else:
- print 'No custom targeting values were deleted.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, KEY_ID)
diff --git a/examples/dfp/v201411/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201411/custom_targeting_service/get_all_custom_targeting_keys_and_values.py
deleted file mode 100755
index 464c2ac9..00000000
--- a/examples/dfp/v201411/custom_targeting_service/get_all_custom_targeting_keys_and_values.py
+++ /dev/null
@@ -1,90 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all custom targeting keys and the values.
-
-To create custom targeting keys and values, run
-create_custom_targeting_keys_and_values.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- custom_targeting_service = client.GetService(
- 'CustomTargetingService', version='v201411')
-
- # Create statement to get all targeting keys.
- targeting_key_statement = dfp.FilterStatement()
-
- all_keys = []
-
- # Get custom targeting keys by statement.
- while True:
- response = custom_targeting_service.getCustomTargetingKeysByStatement(
- targeting_key_statement.ToStatement())
- if 'results' in response:
- all_keys.extend(response['results'])
- targeting_key_statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- if all_keys:
- # Create map of custom targeting key id to custom targeting values.
- key_value_map = {}
-
- # Create statement to get all targeting values.
- query = ('WHERE customTargetingKeyId IN (%s)'
- % ', '.join([key['id'] for key in all_keys]))
- targeting_value_statement = dfp.FilterStatement(query)
-
- # Get custom targeting values by statement.
- while True:
- response = custom_targeting_service.getCustomTargetingValuesByStatement(
- targeting_value_statement.ToStatement())
- if 'results' in response:
- for key in all_keys:
- for value in response['results']:
- if key['id'] == value['customTargetingKeyId']:
- if key['id'] not in key_value_map.keys():
- key_value_map[key['id']] = []
- key_value_map[key['id']].append(value)
- targeting_value_statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Display results.
- for key in all_keys:
- print ('Custom targeting key with id \'%s\', name \'%s\', display name '
- '\'%s\', and type \'%s\' was found.'
- %(key['id'], key['name'], key['displayName'], key['type']))
- if key['id'] in key_value_map.keys():
- for value in key_value_map[key['id']]:
- print ('\tCustom targeting value with id \'%s\', name \'%s\', and '
- 'display name \'%s\' was found.'
- % (value['id'], value['name'], value['displayName']))
- else:
- print 'No keys were found.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
-
diff --git a/examples/dfp/v201411/custom_targeting_service/get_custom_targeting_keys_by_statement.py b/examples/dfp/v201411/custom_targeting_service/get_custom_targeting_keys_by_statement.py
deleted file mode 100755
index de51b5ec..00000000
--- a/examples/dfp/v201411/custom_targeting_service/get_custom_targeting_keys_by_statement.py
+++ /dev/null
@@ -1,63 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all predefined custom targeting keys.
-
-To create custom targeting keys, run create_custom_targeting_keys_and_values.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- custom_targeting_service = client.GetService(
- 'CustomTargetingService', version='v201411')
-
- values = [{
- 'key': 'type',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'PREDEFINED'
- }
- }]
- query = 'WHERE type = :type'
- statement = dfp.FilterStatement(query, values)
-
- # Get custom targeting keys by statement.
- while True:
- response = custom_targeting_service.getCustomTargetingKeysByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for key in response['results']:
- print ('Custom targeting key with id \'%s\', name \'%s\', display name '
- '\'%s\', and type \'%s\' was found.'
- % (key['id'], key['name'], key['displayName'], key['type']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/custom_targeting_service/get_custom_targeting_values_by_statement.py b/examples/dfp/v201411/custom_targeting_service/get_custom_targeting_values_by_statement.py
deleted file mode 100755
index fada5280..00000000
--- a/examples/dfp/v201411/custom_targeting_service/get_custom_targeting_values_by_statement.py
+++ /dev/null
@@ -1,67 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets custom targeting values for the given predefined custom
-targeting key.
-
-To create custom targeting values, run
-create_custom_targeting_keys_and_values.py. To determine which custom
-targeting keys exist, run get_all_custom_targeting_keys_and_values.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'
-
-
-def main(client, key_id):
- # Initialize appropriate service.
- custom_targeting_service = client.GetService(
- 'CustomTargetingService', version='v201411')
-
- values = [{
- 'key': 'keyId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': key_id
- }
- }]
- query = 'WHERE customTargetingKeyId = :keyId'
- statement = dfp.FilterStatement(query, values)
-
- # Get custom targeting values by statement.
- while True:
- response = custom_targeting_service.getCustomTargetingValuesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for value in response['results']:
- print ('Custom targeting value with id \'%s\', name \'%s\', and display'
- ' name \'%s\' was found.'
- % (value['id'], value['name'], value['displayName']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CUSTOM_TARGETING_KEY_ID)
diff --git a/examples/dfp/v201411/custom_targeting_service/update_custom_targeting_keys.py b/examples/dfp/v201411/custom_targeting_service/update_custom_targeting_keys.py
deleted file mode 100755
index e8075cb0..00000000
--- a/examples/dfp/v201411/custom_targeting_service/update_custom_targeting_keys.py
+++ /dev/null
@@ -1,72 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates the display name of a single custom targeting key.
-
-To determine which custom targeting keys exist, run
-get_all_custom_targeting_keys_and_values.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'
-
-
-def main(client, key_id):
- # Initialize appropriate service.
- custom_targeting_service = client.GetService(
- 'CustomTargetingService', version='v201411')
-
- values = [{
- 'key': 'keyId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': key_id
- }
- }]
- query = 'WHERE id = :keyId'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get custom targeting keys by statement.
- response = custom_targeting_service.getCustomTargetingKeysByStatement(
- statement.ToStatement())
-
- # Update each local custom targeting key object by changing its display name.
- if 'results' in response:
- updated_keys = []
- for key in response['results']:
- if not key['displayName']:
- key['displayName'] = key['name']
- key['displayName'] += ' (Deprecated)'
- updated_keys.append(key)
- keys = custom_targeting_service.updateCustomTargetingKeys(updated_keys)
-
- # Display results.
- if keys:
- for key in keys:
- print ('Custom targeting key with id \'%s\', name \'%s\', display name '
- '\'%s\', and type \'%s\' was updated.'
- % (key['id'], key['name'], key['displayName'], key['type']))
- else:
- print 'No custom targeting keys were found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CUSTOM_TARGETING_KEY_ID)
diff --git a/examples/dfp/v201411/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201411/custom_targeting_service/update_custom_targeting_values.py
deleted file mode 100755
index 0df55b71..00000000
--- a/examples/dfp/v201411/custom_targeting_service/update_custom_targeting_values.py
+++ /dev/null
@@ -1,78 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates the display name of the custom targeting values
-belonging to a custom targeting key.
-
-To determine which custom targeting keys exist, run
-get_all_custom_targeting_keys_and_values.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'
-
-
-def main(client, key_id):
- # Initialize appropriate service.
- custom_targeting_service = client.GetService(
- 'CustomTargetingService', version='v201411')
-
- values = [{
- 'key': 'keyId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': key_id
- }
- }]
- query = 'WHERE customTargetingKeyId = :keyId'
- statement = dfp.FilterStatement(query, values)
-
- while True:
- # Get custom targeting values by statement.
- response = custom_targeting_service.getCustomTargetingValuesByStatement(
- statement.ToStatement())
-
- # Update each local custom targeting value object by changing its name.
- if 'results' in response:
- updated_values = []
- for value in response['results']:
- if not value['displayName']:
- value['displayName'] = value['name']
- value['displayName'] += ' (Deprecated)'
- updated_values.append(value)
- values = custom_targeting_service.updateCustomTargetingValues(
- updated_values)
-
- # Display results.
- for value in values:
- print ('Custom targeting value with id \'%s\', name \'%s\', and display'
- ' name \'%s\' was updated.'
- % (value['id'], value['name'], value['displayName']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- if response['totalResultSetSize'] == 0:
- print 'No custom targeting values were updated.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CUSTOM_TARGETING_KEY_ID)
diff --git a/examples/dfp/v201411/exchange_rate_service/__init__.py b/examples/dfp/v201411/exchange_rate_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201411/exchange_rate_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201411/exchange_rate_service/create_exchange_rates.py b/examples/dfp/v201411/exchange_rate_service/create_exchange_rates.py
deleted file mode 100755
index e2a4145f..00000000
--- a/examples/dfp/v201411/exchange_rate_service/create_exchange_rates.py
+++ /dev/null
@@ -1,60 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates an exchange rate.
-
-To determine which exchange rates exist, run get_all_exchange_rates.py.
-
-
-Tags: ExchangeRateService.createExchangeRates
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- exchange_rate_service = client.GetService('ExchangeRateService',
- version='v201411')
-
- # Create a new fixed exchange rate with currency code 'AUD', with direction
- # FROM_NETWORK with a value of 1.5.
- exchange_rate = {
- 'currencyCode': 'AUD',
- 'direction': 'FROM_NETWORK',
- 'exchangeRate': long(15000000000),
- 'refreshRate': 'FIXED'
- }
-
- created_exchange_rate = exchange_rate_service.createExchangeRates(
- [exchange_rate])[0]
-
- print ('Exchange rate with id \'%s,\' currency code \'%s,\' '
- 'direction \'%s,\' and exchange rate \'%.2f\' '
- 'was created.' % (created_exchange_rate['id'],
- created_exchange_rate['currencyCode'],
- created_exchange_rate['direction'],
- (float(created_exchange_rate['exchangeRate']) /
- 10000000000)))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/exchange_rate_service/get_all_exchange_rates.py b/examples/dfp/v201411/exchange_rate_service/get_all_exchange_rates.py
deleted file mode 100755
index cab6efb3..00000000
--- a/examples/dfp/v201411/exchange_rate_service/get_all_exchange_rates.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all exchange rates.
-
-To create exchange rates, run create_exchange_rates.py.
-
-Tags: ExchangeRateService.getExchangeRatesByStatement
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- exchange_rate_service = client.GetService('ExchangeRateService',
- version='v201411')
-
- # Create a filter statement.
- statement = dfp.FilterStatement('ORDER BY id ASC')
-
- # Get all exchange rates by statement.
- while True:
- response = exchange_rate_service.getExchangeRatesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for exchange_rate in response['results']:
- print ('Exchange rate with id \'%s,\' currency code \'%s,\' '
- 'direction \'%s,\' and exchange rate \'%.2f\' '
- 'was found.' % (exchange_rate['id'],
- exchange_rate['currencyCode'],
- exchange_rate['direction'],
- (float(exchange_rate['exchangeRate']) /
- 10000000000)))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/exchange_rate_service/get_exchange_rates_by_currency_code.py b/examples/dfp/v201411/exchange_rate_service/get_exchange_rates_by_currency_code.py
deleted file mode 100755
index 9b7591dd..00000000
--- a/examples/dfp/v201411/exchange_rate_service/get_exchange_rates_by_currency_code.py
+++ /dev/null
@@ -1,73 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets the exchange rate for a specific currency code.
-
-To create exchange rates, run create_exchange_rates.py.
-
-Tags: ExchangeRateService.getExchangeRatesByStatement
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-CURRENCY_CODE = 'INSERT_CURRENCY_CODE_HERE'
-
-
-def main(client, currency_code):
- # Initialize appropriate service.
- exchange_rate_service = client.GetService('ExchangeRateService',
- version='v201411')
-
- # Create a statement to get exchange rates for the specified currency code.
- values = [{
- 'key': 'currencyCode',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': currency_code
- }
- }]
- query = 'WHERE currencyCode = :currencyCode'
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Get rate cards by statement.
- while True:
- response = exchange_rate_service.getExchangeRatesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for exchange_rate in response['results']:
- print ('Exchange rate with id \'%s,\' currency code \'%s,\' '
- 'direction \'%s,\' and exchange rate \'%.2f\' '
- 'was found.' % (exchange_rate['id'],
- exchange_rate['currencyCode'],
- exchange_rate['direction'],
- (float(exchange_rate['exchangeRate']) /
- 10000000000)))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CURRENCY_CODE)
diff --git a/examples/dfp/v201411/exchange_rate_service/update_exchange_rates.py b/examples/dfp/v201411/exchange_rate_service/update_exchange_rates.py
deleted file mode 100755
index 34cdb3f3..00000000
--- a/examples/dfp/v201411/exchange_rate_service/update_exchange_rates.py
+++ /dev/null
@@ -1,79 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates the value of an exchange rate.
-
-To create exchange rates, run create_exchange_rates.py.
-
-Tags: ExchangeRateService.getExchangeRatesByStatement
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-EXCHANGE_RATE_ID = 'INSERT_EXCHANGE_RATE_ID_HERE'
-
-
-def main(client, exchange_rate_id):
- # Initialize appropriate service.
- exchange_rate_service = client.GetService('ExchangeRateService',
- version='v201411')
-
- # Create a statement to get an exchange rate by its ID.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': exchange_rate_id
- }
- }]
- query = 'WHERE id = :id'
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get rate cards by statement.
- response = exchange_rate_service.getExchangeRatesByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- exchange_rate = response['results'][0]
-
- # Update the exchange rate value to 1.5.
- exchange_rate['exchangeRate'] = long(15000000000)
-
- exchange_rates = exchange_rate_service.updateExchangeRates([exchange_rate])
-
- if exchange_rates:
- for exchange_rate in exchange_rates:
- print ('Exchange rate with id \'%s,\' currency code \'%s,\' '
- 'direction \'%s,\' and exchange rate \'%.2f\' '
- 'was updated.' % (exchange_rate['id'],
- exchange_rate['currencyCode'],
- exchange_rate['direction'],
- (float(exchange_rate['exchangeRate']) /
- 10000000000)))
- else:
- print 'No exchange rates were updated.'
- else:
- print 'No exchange rates found to update.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, EXCHANGE_RATE_ID)
diff --git a/examples/dfp/v201411/forecast_service/get_forecast.py b/examples/dfp/v201411/forecast_service/get_forecast.py
deleted file mode 100755
index e45d5c39..00000000
--- a/examples/dfp/v201411/forecast_service/get_forecast.py
+++ /dev/null
@@ -1,106 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets a forecast for a prospective line item.
-
-To determine which placements exist, run get_all_placements.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-from datetime import date
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the placement that the prospective line item will target.
-TARGET_PLACEMENT_IDS = ['INSERT_PLACEMENT_IDS_HERE']
-
-
-def main(client, target_placement_ids):
- # Initialize appropriate service.
- forecast_service = client.GetService('ForecastService', version='v201411')
-
- # Create prospective line item.
- line_item = {
- 'targeting': {
- 'inventoryTargeting': {
- 'targetedPlacementIds': target_placement_ids
- }
- },
- 'creativePlaceholders': [
- {
- 'size': {
- 'width': '300',
- 'height': '250'
- }
- },
- {
- 'size': {
- 'width': '120',
- 'height': '600'
- }
- }
- ],
- 'lineItemType': 'SPONSORSHIP',
- 'startDateTimeType': 'IMMEDIATELY',
- 'endDateTime': {
- 'date': {
- 'year': str(date.today().year + 1),
- 'month': '9',
- 'day': '30'
- },
- 'hour': '0',
- 'minute': '0',
- 'second': '0'
- },
- 'costType': 'CPM',
- 'costPerUnit': {
- 'currencyCode': 'USD',
- 'microAmount': '2000000'
- },
- 'primaryGoal': {
- 'units': '50',
- 'unitType': 'IMPRESSIONS',
- 'goalType': 'DAILY'
- },
- 'contractedUnitsBought': '100',
- 'creativeRotationType': 'EVEN',
- 'discountType': 'PERCENTAGE',
- }
-
- # Get forecast.
- forecast = forecast_service.getForecast(line_item)
- matched = long(forecast['matchedUnits'])
- available_percent = (((long(forecast['availableUnits'])/
- (matched * 1.0)) * 100)
- if matched != 0 else 0)
- contending_line_items = ([] if 'contendingLineItems' not in forecast
- else forecast['contendingLineItems'])
-
- # Display results.
- print '%s %s matched.' % (matched, forecast['unitType'].lower())
- print '%s%% %s available.' % (available_percent, forecast['unitType'].lower())
- print '%d contending line items.' % len(contending_line_items)
-
- if 'possibleUnits' in forecast:
- possible_percent = (long(forecast['possibleUnits'])/(matched * 1.0)) * 100
- print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower())
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, TARGET_PLACEMENT_IDS)
diff --git a/examples/dfp/v201411/forecast_service/get_forecast_by_id.py b/examples/dfp/v201411/forecast_service/get_forecast_by_id.py
deleted file mode 100755
index cb2b8129..00000000
--- a/examples/dfp/v201411/forecast_service/get_forecast_by_id.py
+++ /dev/null
@@ -1,56 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets a forecast for an existing line item.
-
-To determine which line items exist, run get_all_line_items.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the line item to get a forecast for.
-LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID'
-
-
-def main(client, line_item_id):
- # Initialize appropriate service.
- forecast_service = client.GetService('ForecastService', version='v201411')
-
- # Get forecast for line item.
- forecast = forecast_service.getForecastById(line_item_id)
- matched = long(forecast['matchedUnits'])
- available_percent = (((long(forecast['availableUnits'])/
- (matched * 1.0)) * 100)
- if matched != 0 else 0)
- contending_line_items = ([] if 'contendingLineItems' not in forecast
- else forecast['contendingLineItems'])
-
- # Display results.
- print '%s %s matched.' % (matched, forecast['unitType'].lower())
- print '%s%% %s available.' % (available_percent, forecast['unitType'].lower())
- print '%d contending line items.' % len(contending_line_items)
-
- if 'possibleUnits' in forecast:
- possible_percent = (long(forecast['possibleUnits'])/(matched * 1.0)) * 100
- print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower())
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, LINE_ITEM_ID)
diff --git a/examples/dfp/v201411/inventory_service/__init__.py b/examples/dfp/v201411/inventory_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201411/inventory_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201411/inventory_service/archive_ad_units.py b/examples/dfp/v201411/inventory_service/archive_ad_units.py
deleted file mode 100755
index be4d96c1..00000000
--- a/examples/dfp/v201411/inventory_service/archive_ad_units.py
+++ /dev/null
@@ -1,83 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example archives ad units.
-
-The parent ad unit and all ad units underneath it will be archived. To create ad
-units, run create_ad_units.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: InventoryService.getAdUnitsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-PARENT_AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE'
-
-
-def main(client, parent_id):
- # Initialize appropriate service.
- inventory_service = client.GetService('InventoryService', version='v201411')
-
- # Create a query to select ad units under the parent ad unit and the parent ad
- # unit.
- values = [{
- 'key': 'parentId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': parent_id
- }
- }]
- query = 'WHERE parentId = :parentId or id = :parentId'
- statement = dfp.FilterStatement(query, values)
-
- ad_units_archived = 0
-
- # Get ad units by statement.
- while True:
- response = inventory_service.getAdUnitsByStatement(
- statement.ToStatement())
- if 'results' in response:
- for ad_unit in response['results']:
- print ('Ad unit with ID \'%s\' and name \'%s\' will be archived.'
- % (ad_unit['id'], ad_unit['name']))
- # Perform action.
- result = inventory_service.performAdUnitAction(
- {'xsi_type': 'ArchiveAdUnits'}, statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- ad_units_archived += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Display results.
- if ad_units_archived > 0:
- print 'Number of ad units archived: %s' % ad_units_archived
- else:
- print 'No ad units were archived.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PARENT_AD_UNIT_ID)
diff --git a/examples/dfp/v201411/inventory_service/create_ad_units.py b/examples/dfp/v201411/inventory_service/create_ad_units.py
deleted file mode 100755
index b29ef484..00000000
--- a/examples/dfp/v201411/inventory_service/create_ad_units.py
+++ /dev/null
@@ -1,74 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new ad units.
-
-To determine which ad units exist, run get_all_ad_units.py
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: InventoryService.createAdUnits
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-PARENT_AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE'
-
-
-def main(client, parent_id):
- # Initialize appropriate service.
- inventory_service = client.GetService('InventoryService', version='v201411')
-
- # Create ad unit size.
- ad_unit_size = {
- 'size': {
- 'width': '300',
- 'height': '250'
- },
- 'environmentType': 'BROWSER'
- }
-
- # Create ad unit objects.
- ad_unit = {
- 'name': 'Ad_unit_%s' % uuid.uuid4(),
- 'parentId': parent_id,
- 'description': 'Ad unit description.',
- 'targetWindow': 'BLANK',
- 'targetPlatform': 'WEB',
- 'adUnitSizes': [ad_unit_size]
- }
-
- # Add ad units.
- ad_units = inventory_service.createAdUnits([ad_unit])
-
- # Display results.
- for ad_unit in ad_units:
- print ('Ad unit with ID \'%s\' and name \'%s\' was created.'
- % (ad_unit['id'], ad_unit['name']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PARENT_AD_UNIT_ID)
diff --git a/examples/dfp/v201411/inventory_service/get_ad_unit_hierarchy.py b/examples/dfp/v201411/inventory_service/get_ad_unit_hierarchy.py
deleted file mode 100755
index 4fef1844..00000000
--- a/examples/dfp/v201411/inventory_service/get_ad_unit_hierarchy.py
+++ /dev/null
@@ -1,118 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code gets the ad unit hierarchy and displays it as a tree.
-
-To create ad units, run create_ad_units.py
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: InventoryService.getAdUnitsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- inventory_service = client.GetService('InventoryService', version='v201411')
- statement = dfp.FilterStatement()
-
- all_ad_units = []
- # Get ad units by statement.
- while True:
- response = inventory_service.getAdUnitsByStatement(
- statement.ToStatement())
- if 'results' in response:
- all_ad_units.extend(response['results'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Find the root ad unit. root_ad_unit can also be set to child unit to only
- # build and display a portion of the tree.
- query = 'WHERE parentId IS NULL'
- root_statement = dfp.FilterStatement(query)
- response = inventory_service.getAdUnitsByStatement(
- root_statement.ToStatement())
- root_ad_unit = response['results']
-
- if root_ad_unit:
- BuildAndDisplayAdUnitTree(root_ad_unit, all_ad_units)
- else:
- print 'Could not build tree. No root ad unit found.'
-
-
-def DisplayAdUnitTree(root_ad_unit, ad_unit_tree, depth=0):
- """Helper for displaying ad unit tree.
-
- Args:
- root_ad_unit: dict the root ad unit.
- ad_unit_tree: dict the tree of ad units.
- [optional]
- depth: int the depth the tree has reached.
- """
- print '%s%s (%s)' % (GenerateTab(depth), root_ad_unit['name'],
- root_ad_unit['id'])
- if root_ad_unit['id'] in ad_unit_tree:
- for child in ad_unit_tree[root_ad_unit['id']]:
- DisplayAdUnitTree(child, ad_unit_tree, depth+1)
-
-
-def GenerateTab(depth):
- """Generate tabs to represent branching to children.
-
- Args:
- depth: int the depth the tree has reached.
-
- Returns:
- string inserted in front of the root unit.
- """
- tab_list = []
- if depth > 0:
- tab_list.append(' ')
- tab_list.append('| ' * depth)
- tab_list.append('+--')
- return ''.join(tab_list)
-
-
-def BuildAndDisplayAdUnitTree(root_ad_unit, all_ad_units):
- """Create an ad unit tree and display it.
-
- Args:
- root_ad_unit: dict the root ad unit to build the tree under.
- all_ad_units: list the list of all ad units to build the tree with.
- """
- tree = {}
- for ad_unit in all_ad_units:
- if 'parentId' in ad_unit:
- if ad_unit['parentId'] not in tree:
- tree[ad_unit['parentId']] = []
- tree[ad_unit['parentId']].append(ad_unit)
-
- DisplayAdUnitTree(root_ad_unit, tree)
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/inventory_service/get_all_ad_unit_sizes.py b/examples/dfp/v201411/inventory_service/get_all_ad_unit_sizes.py
deleted file mode 100755
index face2a14..00000000
--- a/examples/dfp/v201411/inventory_service/get_all_ad_unit_sizes.py
+++ /dev/null
@@ -1,57 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all ad unit sizes defined in a network.
-
-To create ad units, run create_ad_units.py
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: InventoryService.getAdUnitSizesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- inventory_service = client.GetService('InventoryService', version='v201411')
- statement = dfp.FilterStatement()
-
- # Get ad units by statement.
- while True:
- response = inventory_service.getAdUnitSizesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for ad_unit_size in response['results']:
- print ('Ad unit size of dimensions %s was found.' %
- (ad_unit_size['fullDisplayString']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/inventory_service/get_all_ad_units.py b/examples/dfp/v201411/inventory_service/get_all_ad_units.py
deleted file mode 100755
index 45ebe07d..00000000
--- a/examples/dfp/v201411/inventory_service/get_all_ad_units.py
+++ /dev/null
@@ -1,59 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all ad units within a network.
-
-To create ad units, run create_ad_units.py
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: InventoryService.getAdUnitsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- inventory_service = client.GetService('InventoryService', version='v201411')
- statement = dfp.FilterStatement()
-
- # Get ad units by statement.
- while True:
- response = inventory_service.getAdUnitsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for ad_unit in response['results']:
- print ('Ad unit with ID \'%s\' and name \'%s\' was found.'
- % (ad_unit['id'], ad_unit['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/inventory_service/get_top_level_ad_units.py b/examples/dfp/v201411/inventory_service/get_top_level_ad_units.py
deleted file mode 100755
index a1988c0d..00000000
--- a/examples/dfp/v201411/inventory_service/get_top_level_ad_units.py
+++ /dev/null
@@ -1,72 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all child ad units of the effective root ad unit.
-
-To create ad units, run create_ad_units.py
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: InventoryService.getAdUnitsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- inventory_service = client.GetService('InventoryService', version='v201411')
- network_service = client.GetService('NetworkService', version='v201411')
-
- root_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId']
-
- # Create a statement to select the children of the effective root ad unit.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': root_id
- }
- }]
- query = 'WHERE parentId = :id'
- statement = dfp.FilterStatement(query, values)
-
- # Get ad units by statement.
- while True:
- response = inventory_service.getAdUnitsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for ad_unit in response['results']:
- print ('Ad unit with ID \'%s\' and name \'%s\' was found.'
- % (ad_unit['id'], ad_unit['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/inventory_service/update_ad_units.py b/examples/dfp/v201411/inventory_service/update_ad_units.py
deleted file mode 100755
index 4869b99e..00000000
--- a/examples/dfp/v201411/inventory_service/update_ad_units.py
+++ /dev/null
@@ -1,91 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates ad unit sizes by adding a banner ad size.
-
-To determine which ad units exist, run get_all_ad_units.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: InventoryService.getAdUnit
-Tags: InventoryService.updateAdUnits
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-# Set the ID of the ad unit to get.
-AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE'
-
-
-def main(client, ad_unit_id):
- # Initialize appropriate service.
- inventory_service = client.GetService('InventoryService', version='v201411')
-
- # Create a statement to select a single ad unit by ID.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': ad_unit_id
- }
- }]
- query = 'WHERE id = :id'
- statement = dfp.FilterStatement(query, values)
-
- # Get ad units by statement.
- response = inventory_service.getAdUnitsByStatement(
- statement.ToStatement())
-
- # Add the size 468x60 to the ad unit.
- ad_unit_size = {
- 'size': {
- 'width': '468',
- 'height': '60'
- },
- 'environmentType': 'BROWSER'
- }
-
- if 'results' in response:
- updated_ad_units = []
- for ad_unit in response['results']:
- if 'adUnitSizes' not in ad_unit:
- ad_unit['adUnitSizes'] = []
- ad_unit['adUnitSizes'].append(ad_unit_size)
- updated_ad_units.append(ad_unit)
-
- # Update ad unit on the server.
- ad_units = inventory_service.updateAdUnits(updated_ad_units)
-
- # Display results.
- for ad_unit in ad_units:
- ad_unit_sizes = ['{%s x %s}' % (size['size']['width'],
- size['size']['height'])
- for size in ad_unit['adUnitSizes']]
- print ('Ad unit with ID \'%s\', name \'%s\', and sizes [%s] was updated'
- % (ad_unit['id'], ad_unit['name'], ','.join(ad_unit_sizes)))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, AD_UNIT_ID)
diff --git a/examples/dfp/v201411/label_service/__init__.py b/examples/dfp/v201411/label_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201411/label_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201411/label_service/create_labels.py b/examples/dfp/v201411/label_service/create_labels.py
deleted file mode 100755
index 3e26c13b..00000000
--- a/examples/dfp/v201411/label_service/create_labels.py
+++ /dev/null
@@ -1,56 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new labels.
-
-To determine which labels exist, run get_all_labels.py. This feature is only
-available to DFP premium solution networks."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- label_service = client.GetService('LabelService', version='v201411')
-
- # Create label objects.
- labels = []
- for _ in xrange(5):
- label = {
- 'name': 'Label #%s' % uuid.uuid4(),
- 'isActive': 'true',
- 'types': ['COMPETITIVE_EXCLUSION']
- }
- labels.append(label)
-
- # Add Labels.
- labels = label_service.createLabels(labels)
-
- # Display results.
- for label in labels:
- print ('Label with id \'%s\', name \'%s\', and types {%s} was found.'
- % (label['id'], label['name'], ','.join(label['types'])))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/label_service/deactivate_labels.py b/examples/dfp/v201411/label_service/deactivate_labels.py
deleted file mode 100755
index 4e172e2e..00000000
--- a/examples/dfp/v201411/label_service/deactivate_labels.py
+++ /dev/null
@@ -1,71 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example deactivates all active Labels.
-
-To determine which labels exist, run get_all_labels.py. This feature is only
-available to DFP premium solution networks."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- label_service = client.GetService('LabelService', version='v201411')
-
- # Create query.
- values = [{
- 'key': 'isActive',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'true'
- }
- }]
- query = 'WHERE isActive = :isActive'
- statement = dfp.FilterStatement(query, values)
-
- labels_deactivated = 0
-
- # Get labels by statement.
- while True:
- response = label_service.getLabelsByStatement(statement.ToStatement())
- if 'results' in response:
- for label in response['results']:
- print ('Label with id \'%s\' and name \'%s\' will be '
- 'deactivated.' % (label['id'], label['name']))
- # Perform action.
- result = label_service.performLabelAction(
- {'xsi_type': 'DeactivateLabels'}, statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- labels_deactivated += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Display results.
- if labels_deactivated > 0:
- print 'Number of labels deactivated: %s' % labels_deactivated
- else:
- print 'No labels were deactivated.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/label_service/get_all_labels.py b/examples/dfp/v201411/label_service/get_all_labels.py
deleted file mode 100755
index 340f340d..00000000
--- a/examples/dfp/v201411/label_service/get_all_labels.py
+++ /dev/null
@@ -1,54 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all labels.
-
-To create labels, run create_labels.py. This feature is only available to DFP
-premium solution networks."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- label_service = client.GetService('LabelService', version='v201411')
-
- # Create statement to get all labels
- statement = dfp.FilterStatement()
-
- # Get labels by statement.
- while True:
- response = label_service.getLabelsByStatement(statement.ToStatement())
- if 'results' in response:
- # Display results.
- for label in response['results']:
- print ('Label with id \'%s\' and name \'%s\' was found.'
- % (label['id'], label['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/label_service/get_labels_by_statement.py b/examples/dfp/v201411/label_service/get_labels_by_statement.py
deleted file mode 100755
index 35368752..00000000
--- a/examples/dfp/v201411/label_service/get_labels_by_statement.py
+++ /dev/null
@@ -1,55 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all labels ordered by name.
-
-To create a label, run create_label.py. This feature is only available to DFP
-premium solution networks.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- label_service = client.GetService('LabelService', version='v201411')
-
- # Create statement to get all labels
- statement = dfp.FilterStatement('ORDER BY name')
-
- # Get labels by statement.
- while True:
- response = label_service.getLabelsByStatement(statement.ToStatement())
- if 'results' in response:
- # Display results.
- for label in response['results']:
- print ('Label with id \'%s\' and name \'%s\' was found.'
- % (label['id'], label['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/label_service/update_labels.py b/examples/dfp/v201411/label_service/update_labels.py
deleted file mode 100755
index 3876ae7a..00000000
--- a/examples/dfp/v201411/label_service/update_labels.py
+++ /dev/null
@@ -1,71 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates the description of a single label.
-
-To determine which labels exist, run get_all_labels.py. This feature is only
-available to DFP premium solution networks."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-LABEL_ID = 'INSERT_LABEL_ID_HERE'
-
-
-def main(client, label_id):
- # Initialize appropriate service.
- label_service = client.GetService('LabelService', version='v201411')
-
- # Create a statement to select only active labels.
- values = [
- {
- 'key': 'labelId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': label_id
- }
- }
- ]
- query = 'WHERE id = :labelId'
- statement = dfp.FilterStatement(query, values)
-
- # Get labels by filter.
- response = label_service.getLabelsByStatement(statement.ToStatement())
-
- if 'results' in response:
- # Update each local label object by changing the description.
- updated_labels = []
- for label in response['results']:
- label['description'] = 'These labels are updated.'
- updated_labels.append(label)
-
- # Update labels remotely.
- labels = label_service.updateLabels(updated_labels)
-
- for label in labels:
- print ('Label with id \'%s\' and name \'%s\' was updated.'
- % (label['id'], label['name']))
- else:
- print 'No labels found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, LABEL_ID)
-
diff --git a/examples/dfp/v201411/line_item_creative_association_service/__init__.py b/examples/dfp/v201411/line_item_creative_association_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201411/line_item_creative_association_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201411/line_item_creative_association_service/create_licas.py b/examples/dfp/v201411/line_item_creative_association_service/create_licas.py
deleted file mode 100755
index bbaca276..00000000
--- a/examples/dfp/v201411/line_item_creative_association_service/create_licas.py
+++ /dev/null
@@ -1,58 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new line item creative associations (LICAs) for an
-existing line item and a set of creative ids.
-
-To determine which LICAs exist, run get_all_licas.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the line item ID and creative IDs to associate.
-LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
-CREATIVE_IDS = ['INSERT_CREATIVE_IDS_HERE']
-
-
-def main(client, line_item_id, creative_ids):
- # Initialize appropriate service.
- lica_service = client.GetService(
- 'LineItemCreativeAssociationService', version='v201411')
-
- licas = []
- for creative_id in creative_ids:
- licas.append({'creativeId': creative_id,
- 'lineItemId': line_item_id})
-
- # Create the LICAs remotely.
- licas = lica_service.createLineItemCreativeAssociations(licas)
-
- # Display results.
- if licas:
- for lica in licas:
- print ('LICA with line item id \'%s\', creative id \'%s\', and '
- 'status \'%s\' was created.' %
- (lica['lineItemId'], lica['creativeId'], lica['status']))
- else:
- print 'No LICAs created.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, LINE_ITEM_ID, CREATIVE_IDS)
diff --git a/examples/dfp/v201411/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201411/line_item_creative_association_service/deactivate_licas.py
deleted file mode 100755
index 5c2af158..00000000
--- a/examples/dfp/v201411/line_item_creative_association_service/deactivate_licas.py
+++ /dev/null
@@ -1,84 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example deactivates all LICAs for the line item.
-
-To determine which LICAs exist, run get_all_licas.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the id of the line item in which to deactivate LICAs.
-LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
-
-
-def main(client, line_item_id):
- # Initialize appropriate service.
- lica_service = client.GetService(
- 'LineItemCreativeAssociationService', version='v201411')
-
- # Create query.
- values = [{
- 'key': 'lineItemId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': line_item_id
- }
- }, {
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ACTIVE'
- }
- }]
- query = 'WHERE lineItemId = :lineItemId AND status = :status'
- statement = dfp.FilterStatement(query, values)
-
- num_deactivated_licas = 0
-
- # Get LICAs by statement.
- while True:
- response = lica_service.getLineItemCreativeAssociationsByStatement(
- statement.ToStatement())
- if 'results' in response:
- for lica in response['results']:
- print ('LICA with line item id \'%s\', creative id \'%s\', and status'
- ' \'%s\' will be deactivated.' %
- (lica['lineItemId'], lica['creativeId'], lica['status']))
-
- # Perform action.
- result = lica_service.performLineItemCreativeAssociationAction(
- {'xsi_type': 'DeactivateLineItemCreativeAssociations'},
- statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- num_deactivated_licas += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Display results.
- if num_deactivated_licas > 0:
- print 'Number of LICAs deactivated: %s' % num_deactivated_licas
- else:
- print 'No LICAs were deactivated.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, LINE_ITEM_ID)
diff --git a/examples/dfp/v201411/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201411/line_item_creative_association_service/get_all_licas.py
deleted file mode 100755
index f932e842..00000000
--- a/examples/dfp/v201411/line_item_creative_association_service/get_all_licas.py
+++ /dev/null
@@ -1,58 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all line item creative associations (LICA).
-
-To create LICAs, run create_licas.py or associate_creative_set_to_line_item.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- lica_service = client.GetService(
- 'LineItemCreativeAssociationService', version='v201411')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get line items by statement.
- while True:
- response = lica_service.getLineItemCreativeAssociationsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for lica in response['results']:
- if 'creativeSetId' in lica:
- print ('LICA with line item ID \'%s\', creative set ID \'%s\', and '
- 'status \'%s\' was found.' %
- (lica['lineItemId'], lica['creativeSetId'], lica['status']))
- else:
- print ('LICA with line item ID \'%s\', creative ID \'%s\', and status'
- ' \'%s\' was found.' % (lica['lineItemId'], lica['creativeId'],
- lica['status']))
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/line_item_creative_association_service/get_licas_by_statement.py b/examples/dfp/v201411/line_item_creative_association_service/get_licas_by_statement.py
deleted file mode 100755
index 130e8c3b..00000000
--- a/examples/dfp/v201411/line_item_creative_association_service/get_licas_by_statement.py
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all line item creative associations (LICA) for a given
-line item id.
-
-To create LICAs, run create_licas.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the id of the line item to get LICAs by.
-LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
-
-
-def main(client, line_item_id):
- # Initialize appropriate service.
- lica_service = client.GetService(
- 'LineItemCreativeAssociationService', version='v201411')
-
-# Create statement object to only select LICAs for the given line item id.
- values = [{
- 'key': 'lineItemId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': line_item_id
- }
- }]
- query = 'WHERE lineItemId = :lineItemId'
- statement = dfp.FilterStatement(query, values)
-
- while True:
- # Get LICAs by statement.
- response = lica_service.getLineItemCreativeAssociationsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- # Display results.
- for lica in response['results']:
- print ('LICA with line item id \'%s\', creative id \'%s\', and status '
- '\'%s\' was found.' % (lica['lineItemId'], lica['creativeId'],
- lica['status']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, LINE_ITEM_ID)
diff --git a/examples/dfp/v201411/line_item_creative_association_service/update_licas.py b/examples/dfp/v201411/line_item_creative_association_service/update_licas.py
deleted file mode 100755
index 21dbe952..00000000
--- a/examples/dfp/v201411/line_item_creative_association_service/update_licas.py
+++ /dev/null
@@ -1,67 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates the destination URL of all line item creative
-associations (LICA).
-
-To determine which LICAs exist, run get_all_licas.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- lica_service = client.GetService(
- 'LineItemCreativeAssociationService', version='v201411')
-
- # Create statement object to get all LICAs.
- statement = dfp.FilterStatement()
-
- while True:
- # Get LICAs by statement.
- response = lica_service.getLineItemCreativeAssociationsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- # Update each local LICA object by changing its destination URL.
- updated_licas = []
- for lica in response['results']:
- lica['destinationUrl'] = 'http://news.google.com'
- updated_licas.append(lica)
-
- # Update LICAs remotely.
- licas = lica_service.updateLineItemCreativeAssociations(updated_licas)
-
- # Display results.
- for lica in licas:
- print ('LICA with line item id \'%s\', creative id \'%s\', and status '
- '\'%s\' was updated.' % (lica['lineItemId'], lica['creativeId'],
- lica['status']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- if response['totalResultSetSize'] == 0:
- print 'No LICAs found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/line_item_service/__init__.py b/examples/dfp/v201411/line_item_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201411/line_item_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201411/line_item_service/activate_line_items.py b/examples/dfp/v201411/line_item_service/activate_line_items.py
deleted file mode 100755
index e76f4764..00000000
--- a/examples/dfp/v201411/line_item_service/activate_line_items.py
+++ /dev/null
@@ -1,86 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example activates all line items for the given order.
-
-To be activated, line items need to be in the approved state and have at least
-one creative associated with them. To approve line items, approve the order to
-which they belong by running approve_orders.py. To create LICAs, run
-create_licas.py. To determine which line items exist, run
-get_all_line_items.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the id of the order to get line items from.
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-
-
-def main(client, order_id):
- # Initialize appropriate service.
- line_item_service = client.GetService('LineItemService', version='v201411')
-
- # Create query.
- values = [{
- 'key': 'orderId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': order_id
- }
- }, {
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'NEEDS_CREATIVES'
- }
- }]
- query = 'WHERE orderId = :orderId AND status = :status'
- statement = dfp.FilterStatement(query, values)
-
- line_items_activated = 0
-
- # Get line items by statement.
- while True:
- response = line_item_service.getLineItemsByStatement(
- statement.ToStatement())
- if 'results' in response:
- for line_item in response['results']:
- print ('Line item with id \'%s\', belonging to order id \'%s\', and '
- 'name \'%s\' will be activated.' %
- (line_item['id'], line_item['orderId'], line_item['name']))
-
- # Perform action.
- result = line_item_service.performLineItemAction(
- {'xsi_type': 'ActivateLineItems'}, statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- line_items_activated += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Display results.
- if line_items_activated > 0:
- print 'Number of line items activated: %s' % line_items_activated
- else:
- print 'No line items were activated.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID)
diff --git a/examples/dfp/v201411/line_item_service/create_line_items.py b/examples/dfp/v201411/line_item_service/create_line_items.py
deleted file mode 100755
index 9f0a50c8..00000000
--- a/examples/dfp/v201411/line_item_service/create_line_items.py
+++ /dev/null
@@ -1,172 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new line items.
-
-To determine which line items exist, run get_all_line_items.py. To determine
-which orders exist, run get_all_orders.py. To determine which placements exist,
-run get_all_placements.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-from datetime import date
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set order that the created line item will belong to and add the id of a
-# placement containing ad units to target.
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-TARGETED_PLACEMENT_IDS = ['INSERT_PLACEMENT_IDS_HERE']
-
-
-def main(client, order_id, targeted_placement_ids):
- # Initialize appropriate service.
- line_item_service = client.GetService('LineItemService', version='v201411')
-
- # Create line item objects.
- line_items = []
- for i in xrange(5):
- line_item = {
- 'name': 'Line item #%s' % uuid.uuid4(),
- 'orderId': order_id,
- 'targeting': {
- 'inventoryTargeting': {
- 'targetedPlacementIds': targeted_placement_ids
- },
- 'geoTargeting': {
- 'targetedLocations': [
- {
- 'id': '2840',
- 'displayName': 'US'
- },
- {
- 'id': '20133',
- 'displayName': 'Geneva'
- },
- {
- 'id': '9000093',
- 'displayName': 'B3P',
- }
- ],
- 'excludedLocations': [
- {
- 'id': '1016367',
- 'displayName': 'Chicago',
- },
- {
- 'id': '200501',
- 'displayName': 'New York NY'
- }
- ]
- },
- 'dayPartTargeting': {
- 'dayParts': [
- {
- 'dayOfWeek': 'SATURDAY',
- 'startTime': {
- 'hour': '0',
- 'minute': 'ZERO'
- },
- 'endTime': {
- 'hour': '24',
- 'minute': 'ZERO'
- }
- },
- {
- 'dayOfWeek': 'SUNDAY',
- 'startTime': {
- 'hour': '0',
- 'minute': 'ZERO'
- },
- 'endTime': {
- 'hour': '24',
- 'minute': 'ZERO'
- }
- }
- ],
- 'timeZone': 'BROWSER'
- },
- 'userDomainTargeting': {
- 'domains': ['usa.gov'],
- 'targeted': 'false'
- },
- 'technologyTargeting': {
- 'browserTargeting': {
- 'browsers': [{'id': '500072'}],
- 'isTargeted': 'true'
- }
- }
- },
- 'creativePlaceholders': [
- {
- 'size': {
- 'width': '300',
- 'height': '250'
- }
- },
- {
- 'size': {
- 'width': '120',
- 'height': '600'
- }
- }
- ],
- 'startDateTimeType': 'IMMEDIATELY',
- 'lineItemType': 'STANDARD',
- 'endDateTime': {
- 'date': {
- 'year': str(date.today().year + 1),
- 'month': '9',
- 'day': '30'
- },
- 'hour': '0',
- 'minute': '0',
- 'second': '0'
- },
- 'costType': 'CPM',
- 'costPerUnit': {
- 'currencyCode': 'USD',
- 'microAmount': '2000000'
- },
- 'primaryGoal': {
- 'units': '50',
- 'unitType': 'IMPRESSIONS',
- 'goalType': 'LIFETIME'
- },
- 'contractedUnitsBought': '100',
- 'creativeRotationType': 'EVEN',
- 'discountType': 'PERCENTAGE',
- 'allowOverbook': 'true'
- }
- line_items.append(line_item)
-
- # Add line items.
- line_items = line_item_service.createLineItems(line_items)
-
- # Display results.
- for line_item in line_items:
- print ('Line item with id \'%s\', belonging to order id \'%s\', and named '
- '\'%s\' was created.' % (line_item['id'], line_item['orderId'],
- line_item['name']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID, TARGETED_PLACEMENT_IDS)
-
diff --git a/examples/dfp/v201411/line_item_service/create_video_line_item.py b/examples/dfp/v201411/line_item_service/create_video_line_item.py
deleted file mode 100755
index 2eb42fa6..00000000
--- a/examples/dfp/v201411/line_item_service/create_video_line_item.py
+++ /dev/null
@@ -1,151 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates a new line item to serve to video content.
-
-This feature is only available to DFP premium solution networks. To determine
-which line items exist, run get_all_line_items.py. To determine which orders
-exist, run get_all_orders.py. To create a video ad unit, run
-create_video_ad_unit.py. To create criteria for categories, run
-create_custom_targeting_keys_and_values.py"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-from datetime import date
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set order that all created line item will belong to and the video ad unit id
-# to target.
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-TARGETED_VIDEO_AD_UNIT_ID = 'INSERT_TARGETED_VIDEO_AD_UNIT_ID_HERE'
-
-# Set the custom targeting key ID and value ID representing the metadata on the
-# content to target. This would typically be a key representing a 'genre' and
-# a value representing something like 'comedy'.
-CONTENT_CUSTOM_TARGETING_KEY_ID = 'INSERT_CONTENT_CUSTOM_TARGETING_KEY_ID_HERE'
-CONTENT_CUSTOM_TARGETING_VALUE_ID = \
- 'INSERT_CONTENT_CUSTOM_TARGETING_VALUE_ID_HERE'
-
-
-def main(client, order_id, targeted_video_ad_unit_id,
- content_custom_targeting_key_id, content_custom_targeting_value_id):
- # Initialize appropriate service.
- line_item_service = client.GetService('LineItemService', version='v201411')
-
- # create custom criteria for the content metadata targeting.
- custom_criteria = {
- 'xsi_type': 'CustomCriteria',
- 'keyId': content_custom_targeting_key_id,
- 'valueIds': [content_custom_targeting_value_id],
- 'operator': 'IS'
- }
-
- # Create the custom criteria set.
- top_set = {
- 'xsi_type': 'CustomCriteriaSet',
- 'logicalOperator': 'OR',
- 'children': [custom_criteria]
- }
-
- # Create line item object.
- line_item = {
- 'name': 'Line item #%s' % uuid.uuid4(),
- 'orderId': order_id,
- 'targeting': {
- 'customTargeting': top_set,
- 'inventoryTargeting': {
- 'targetedAdUnits': [{'adUnitId': targeted_video_ad_unit_id,
- 'includeDescendants': 'true'}]
- },
- 'videoPositionTargeting': {
- 'targetedPositions': [
- {
- 'videoPosition': {
- 'positionType': 'PREROLL'
- }
- }
- ]
- }
- },
- 'creativePlaceholders': [
- {
- 'size': {
- 'width': '400',
- 'height': '300'
- },
- 'companions': [
- {
- 'size': {
- 'width': '300',
- 'height': '250'
- },
- },
- {
- 'size': {
- 'width': '728',
- 'height': '90'
- },
- }
- ]
- }
- ],
- 'environmentType': 'VIDEO_PLAYER',
- 'companionDeliveryOption': 'OPTIONAL',
- 'startDateTimeType': 'IMMEDIATELY',
- 'lineItemType': 'SPONSORSHIP',
- 'endDateTime': {
- 'date': {
- 'year': str(date.today().year + 1),
- 'month': '9',
- 'day': '30'
- },
- 'hour': '0',
- 'minute': '0',
- 'second': '0'
- },
- 'costType': 'CPM',
- 'costPerUnit': {
- 'currencyCode': 'USD',
- 'microAmount': '2000000'
- },
- 'primaryGoal': {
- 'units': '50',
- 'unitType': 'IMPRESSIONS',
- 'goalType': 'DAILY'
- },
- 'contractedUnitsBought': '100',
- 'creativeRotationType': 'OPTIMIZED',
- 'discountType': 'PERCENTAGE',
- 'allowOverbook': 'true'
- }
-
- # Add line item.
- line_item = line_item_service.createLineItem(line_item)
-
- # Display results.
- print ('Video line item with id \'%s\', belonging to order id \'%s\', and '
- 'named \'%s\' was created.' % (line_item['id'], line_item['orderId'],
- line_item['name']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID, TARGETED_VIDEO_AD_UNIT_ID,
- CONTENT_CUSTOM_TARGETING_KEY_ID, CONTENT_CUSTOM_TARGETING_VALUE_ID)
diff --git a/examples/dfp/v201411/line_item_service/get_all_line_items.py b/examples/dfp/v201411/line_item_service/get_all_line_items.py
deleted file mode 100755
index f6549c6e..00000000
--- a/examples/dfp/v201411/line_item_service/get_all_line_items.py
+++ /dev/null
@@ -1,54 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all line items.
-
-To create line items, run create_line_items.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- line_item_service = client.GetService('LineItemService', version='v201411')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get line items by statement.
- while True:
- response = line_item_service.getLineItemsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for line_item in response['results']:
- print ('Line item with id \'%s\', belonging to order id \'%s\', and '
- 'named \'%s\' was found.' %
- (line_item['id'], line_item['orderId'], line_item['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/line_item_service/get_line_items_by_statement.py b/examples/dfp/v201411/line_item_service/get_line_items_by_statement.py
deleted file mode 100755
index f04d3929..00000000
--- a/examples/dfp/v201411/line_item_service/get_line_items_by_statement.py
+++ /dev/null
@@ -1,77 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all line items that need creatives for the given
-order.
-
-To create line items, run create_line_items.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the id of the order to get line items from.
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-
-
-def main(client, order_id):
- # Initialize appropriate service.
- line_item_service = client.GetService('LineItemService', version='v201411')
-
- # Create statement object to only select line items that need creatives from a
- # given order.
- values = [{
- 'key': 'orderId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': order_id
- }
- }, {
- 'key': 'isMissingCreatives',
- 'value': {
- 'xsi_type': 'BooleanValue',
- 'value': 'true'
- }
- }]
- query = 'WHERE orderId = :orderId AND '
- 'isMissingCreatives = :isMissingCreatives'
- statement = dfp.FilterStatement(query, values)
-
- while True:
- # Get line items by statement.
- response = line_item_service.getLineItemsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- # Display results.
- for line_item in response['results']:
- print ('Line item with id \'%s\', belonging to order id \'%s\', and '
- 'named \'%s\' was found.' % (line_item['id'],
- line_item['orderId'],
- line_item['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID)
diff --git a/examples/dfp/v201411/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201411/line_item_service/get_recently_updated_line_items.py
deleted file mode 100755
index 2d7d4040..00000000
--- a/examples/dfp/v201411/line_item_service/get_recently_updated_line_items.py
+++ /dev/null
@@ -1,76 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example shows how to get recently updated line items.
-
-To create line items, run create_line_items.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import datetime
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-
-
-def main(client, order_id):
- # Initialize appropriate service.
- line_item_service = client.GetService('LineItemService', version='v201411')
-
- # Create statement object to only select line items belonging to the order and
- # have been modified in the last 3 days.
- three_days_ago = datetime.date.today() - datetime.timedelta(days=3)
- values = [{
- 'key': 'dateTimeString',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': three_days_ago.strftime('%Y-%m-%dT%H:%M:%S')
- }
- }, {
- 'key': 'orderId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': order_id
- }
- }]
- query = 'WHERE lastModifiedDateTime >= :dateTimeString AND orderId = :orderId'
- statement = dfp.FilterStatement(query, values)
-
- while True:
- # Get line items by statement.
- response = line_item_service.getLineItemsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- # Display results.
- for line_item in response['results']:
- print ('Line item with id \'%s\', belonging to order id \'%s\', and '
- 'named \'%s\' was found.' % (line_item['id'],
- line_item['orderId'],
- line_item['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID)
diff --git a/examples/dfp/v201411/line_item_service/target_custom_criteria.py b/examples/dfp/v201411/line_item_service/target_custom_criteria.py
deleted file mode 100755
index b2805e59..00000000
--- a/examples/dfp/v201411/line_item_service/target_custom_criteria.py
+++ /dev/null
@@ -1,115 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates a line item to add custom criteria targeting.
-
-To determine which line items exist, run get_all_line_items.py. To determine
-which custom targeting keys and values exist, run
-get_all_custom_targeting_keys_and_values.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import pprint
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
-KEY_ID1 = 'INSERT_TARGETING_KEY_ID_HERE'
-KEY_ID2 = 'INSERT_TARGETING_KEY_ID_HERE'
-KEY_ID3 = 'INSERT_TARGETING_KEY_ID_HERE'
-
-VALUE_ID1 = 'INSERT_TARGETING_VALUE_ID_HERE'
-VALUE_ID2 = 'INSERT_TARGETING_VALUE_ID_HERE'
-VALUE_ID3 = 'INSERT_TARGETING_VALUE_ID_HERE'
-
-
-def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2,
- value_id3):
- # Initialize appropriate service.
- line_item_service = client.GetService('LineItemService', version='v201411')
-
- # create custom criterias
- custom_criteria1 = {
- 'xsi_type': 'CustomCriteria',
- 'keyId': key_id1,
- 'valueIds': [value_id1],
- 'operator': 'IS'
- }
-
- custom_criteria2 = {
- 'xsi_type': 'CustomCriteria',
- 'keyId': key_id2,
- 'valueIds': [value_id2],
- 'operator': 'IS_NOT'
- }
-
- custom_criteria3 = {
- 'xsi_type': 'CustomCriteria',
- 'keyId': key_id3,
- 'valueIds': [value_id3],
- 'operator': 'IS'
- }
-
- # Create the custom criteria set that will resemble:
- # (custom_criteria1.key == custom_criteria1.value OR
- # (custom_criteria2.key != custom_criteria2.value AND
- # custom_criteria13.key == custom_criteria3.value))
- sub_set = {
- 'xsi_type': 'CustomCriteriaSet',
- 'logicalOperator': 'AND',
- 'children': [custom_criteria2, custom_criteria3]
- }
-
- top_set = {
- 'xsi_type': 'CustomCriteriaSet',
- 'logicalOperator': 'OR',
- 'children': [custom_criteria1, sub_set]
- }
-
- # Create statement to get the line item
- values = [{
- 'key': 'lineItemId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': line_item_id
- }
- }]
- query = 'WHERE id = :lineItemId'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Set custom criteria targeting on the line item.
- line_item = line_item_service.getLineItemsByStatement(
- statement.ToStatement())['results'][0]
- line_item['targeting']['customTargeting'] = top_set
-
- # Update line item.
- line_item = line_item_service.updateLineItems([line_item])[0]
-
- # Display results.
- if line_item:
- print ('Line item with id \'%s\' updated with custom criteria targeting:'
- % line_item['id'])
- pprint.pprint(line_item['targeting']['customTargeting'])
- else:
- print 'No line items were updated.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, LINE_ITEM_ID, KEY_ID1, KEY_ID2, KEY_ID3, VALUE_ID1,
- VALUE_ID2, VALUE_ID3)
diff --git a/examples/dfp/v201411/line_item_service/update_line_items.py b/examples/dfp/v201411/line_item_service/update_line_items.py
deleted file mode 100755
index 77cb41cb..00000000
--- a/examples/dfp/v201411/line_item_service/update_line_items.py
+++ /dev/null
@@ -1,83 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates the delivery rate of all line items in an order.
-
-To determine which line items exist, run get_all_line_items.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set id of the order to get line items from.
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-
-
-def main(client, order_id):
- # Initialize appropriate service.
- line_item_service = client.GetService('LineItemService', version='v201411')
-
- # Create statement object to only select line items with even delivery rates.
- values = [{
- 'key': 'deliveryRateType',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'EVENLY'
- }
- }, {
- 'key': 'orderId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': order_id
- }
- }]
-
- query = 'WHERE deliveryRateType = :deliveryRateType and orderId = :orderId'
- statement = dfp.FilterStatement(query, values, 500)
-
- # Get line items by statement.
- response = line_item_service.getLineItemsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- # Update each local line item by changing its delivery rate type.
- updated_line_items = []
- for line_item in response['results']:
- if not line_item['isArchived']:
- line_item['deliveryRateType'] = 'AS_FAST_AS_POSSIBLE'
- updated_line_items.append(line_item)
-
- # Update line items remotely.
- line_items = line_item_service.updateLineItems(updated_line_items)
-
- # Display results.
- if line_items:
- for line_item in line_items:
- print ('Line item with id \'%s\', belonging to order id \'%s\', named '
- '\'%s\', and delivery rate \'%s\' was updated.'
- % (line_item['id'], line_item['orderId'], line_item['name'],
- line_item['deliveryRateType']))
- else:
- print 'No line items were updated.'
- else:
- print 'No line items found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID)
diff --git a/examples/dfp/v201411/network_service/__init__.py b/examples/dfp/v201411/network_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201411/network_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201411/network_service/get_all_networks.py b/examples/dfp/v201411/network_service/get_all_networks.py
deleted file mode 100755
index 4c82ffbd..00000000
--- a/examples/dfp/v201411/network_service/get_all_networks.py
+++ /dev/null
@@ -1,46 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all networks that you have access to with the current login
-credentials.
-
-A networkCode should be left out for this request."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- network_service = client.GetService('NetworkService', version='v201411')
-
- # Get all networks that you have access to with the current login credentials.
- networks = network_service.getAllNetworks()
-
- # Display results.
- for network in networks:
- print ('Network with network code \'%s\' and display name \'%s\' was found.'
- % (network['networkCode'], network['displayName']))
-
- print '\nNumber of results found: %s' % len(networks)
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/network_service/get_current_network.py b/examples/dfp/v201411/network_service/get_current_network.py
deleted file mode 100755
index a5742ccb..00000000
--- a/examples/dfp/v201411/network_service/get_current_network.py
+++ /dev/null
@@ -1,40 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets the current network that you can make requests against."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- network_service = client.GetService('NetworkService', version='v201411')
-
- # Get the current network.
- network = network_service.getCurrentNetwork()
-
- # Display results.
- print ('Current network has network code \'%s\' and display name \'%s\'.'
- % (network['networkCode'], network['displayName']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/network_service/make_test_network.py b/examples/dfp/v201411/network_service/make_test_network.py
deleted file mode 100755
index 7e347447..00000000
--- a/examples/dfp/v201411/network_service/make_test_network.py
+++ /dev/null
@@ -1,53 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates a test network.
-
-You do not need to have a DFP account to run this example, but you do need to
-have a Google account (created at http://www.google.com/accounts/newaccount
-if you currently don't have one) that is not associated with any other DFP test
-networks. Once this network is created, you can supply the network code in your
-settings to make calls to other services.
-
-Alternatively, if you do not wish to run this example, you can create a test
-network at:
-https://dfp-playground.appspot.com
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- network_service = client.GetService('NetworkService', version='v201411')
-
- # Create a test network.
- network = network_service.MakeTestNetwork()
-
- # Display results.
- print ('Test network with network code \'%s\' and display name \'%s\' '
- 'created.' % (network['networkCode'], network['displayName']))
- print ('You may now sign in at http://www.google.com/dfp/main?networkCode=%s'
- % network['networkCode'])
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/order_service/__init__.py b/examples/dfp/v201411/order_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201411/order_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201411/order_service/approve_orders.py b/examples/dfp/v201411/order_service/approve_orders.py
deleted file mode 100755
index 51a792e4..00000000
--- a/examples/dfp/v201411/order_service/approve_orders.py
+++ /dev/null
@@ -1,75 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example approves all eligible draft and pending orders.
-
-To determine which orders exist, run get_all_orders.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import datetime
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- order_service = client.GetService('OrderService', version='v201411')
-
- # Create query.
- values = [{
- 'key': 'today',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': datetime.date.today().strftime('%Y-%m-%dT%H:%M:%S')
- }
- }]
- query = ('WHERE status in (\'DRAFT\', \'PENDING_APPROVAL\')'
- ' AND endDateTime >= :today AND isArchived = FALSE')
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
- orders_approved = 0
-
- # Get orders by statement.
- while True:
- response = order_service.getOrdersByStatement(statement.ToStatement())
- if 'results' in response:
- # Display results.
- for order in response['results']:
- print ('Order with id \'%s\', name \'%s\', and status \'%s\' will be '
- 'approved.' % (order['id'], order['name'], order['status']))
- # Perform action.
- result = order_service.performOrderAction(
- {'xsi_type': 'ApproveOrders'}, statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- orders_approved += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Display results.
- if orders_approved > 0:
- print 'Number of orders approved: %s' % orders_approved
- else:
- print 'No orders were approved.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/order_service/create_orders.py b/examples/dfp/v201411/order_service/create_orders.py
deleted file mode 100755
index fd3f3301..00000000
--- a/examples/dfp/v201411/order_service/create_orders.py
+++ /dev/null
@@ -1,60 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new orders.
-
-To determine which orders exist, run get_all_orders.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
-SALESPERSON_ID = 'INSERT_SALESPERSON_ID_HERE'
-TRAFFICKER_ID = 'INSERT_TRAFFICKER_ID_HERE'
-
-
-def main(client, company_id, salesperson_id, trafficker_id):
- # Initialize appropriate service.
- order_service = client.GetService('OrderService', version='v201411')
-
- # Create order objects.
- orders = []
- for i in xrange(5):
- order = {
- 'name': 'Order #%s' % uuid.uuid4(),
- 'advertiserId': company_id,
- 'salespersonId': salesperson_id,
- 'traffickerId': trafficker_id
- }
- orders.append(order)
-
- # Add orders.
- orders = order_service.createOrders(orders)
-
- # Display results.
- for order in orders:
- print ('Order with id \'%s\' and name \'%s\' was created.'
- % (order['id'], order['name']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, COMPANY_ID, SALESPERSON_ID, TRAFFICKER_ID)
diff --git a/examples/dfp/v201411/order_service/get_all_orders.py b/examples/dfp/v201411/order_service/get_all_orders.py
deleted file mode 100755
index addcd5e8..00000000
--- a/examples/dfp/v201411/order_service/get_all_orders.py
+++ /dev/null
@@ -1,54 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all orders.
-
-To create orders, run create_orders.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- order_service = client.GetService('OrderService', version='v201411')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get orders by statement.
- while True:
- response = order_service.getOrdersByStatement(statement.ToStatement())
- if 'results' in response:
- # Display results.
- for order in response['results']:
- print ('Order with id \'%s\', name \'%s\', and advertiser id \'%s\' was'
- ' found.' % (order['id'], order['name'], order['advertiserId']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/order_service/get_orders_by_statement.py b/examples/dfp/v201411/order_service/get_orders_by_statement.py
deleted file mode 100755
index 65ce24ad..00000000
--- a/examples/dfp/v201411/order_service/get_orders_by_statement.py
+++ /dev/null
@@ -1,63 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets an order by an ID.
-
-To create orders, run create_orders.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set id of the order to get.
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-
-
-def main(client, order_id):
- # Initialize appropriate service.
- order_service = client.GetService('OrderService', version='v201411')
-
- # Create statement object to select a single order by an ID.
- values = [{
- 'key': 'orderId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': order_id
- }
- }]
- query = 'WHERE id = :orderId'
-
- statement = dfp.FilterStatement(query, values)
-
- # Get orders by statement.
- response = order_service.getOrdersByStatement(statement.ToStatement())
- orders = []
- if 'results' in response:
- orders = response['results']
-
- # Display results.
- for order in orders:
- print ('Order with id \'%s\' name \'%s\' was found.'
- % (order['id'], order['name']))
-
- print '\nNumber of results found: %s' % len(orders)
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID)
diff --git a/examples/dfp/v201411/order_service/update_orders.py b/examples/dfp/v201411/order_service/update_orders.py
deleted file mode 100755
index 263ca6ce..00000000
--- a/examples/dfp/v201411/order_service/update_orders.py
+++ /dev/null
@@ -1,77 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates the notes of a single order specified by ID.
-
-To determine which orders exist, run get_all_orders.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-
-
-def main(client, order_id):
- # Initialize appropriate service.
- order_service = client.GetService('OrderService', version='v201411')
-
- # Create statement object to select a single order by an ID.
- values = [{
- 'key': 'orderId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': order_id
- }
- }]
- query = 'WHERE id = :orderId'
-
- statement = dfp.FilterStatement(query, values)
-
- # Get orders by statement.
- response = order_service.getOrdersByStatement(statement.ToStatement())
-
- if 'results' in response:
- # Update each local order object by changing its notes.
- updated_orders = []
- for order in response['results']:
- # Archived orders cannot be updated.
- if not order['isArchived']:
- order['notes'] = 'Spoke to advertiser. All is well.'
- updated_orders.append(order)
-
- # Update orders remotely.
- orders = order_service.updateOrders(updated_orders)
-
- # Display results.
- if orders:
- for order in orders:
- print ('Order with id \'%s\', name \'%s\', advertiser id \'%s\', and '
- 'notes \'%s\' was updated.'
- % (order['id'], order['name'], order['advertiserId'],
- order['notes']))
- else:
- print 'No orders were updated.'
- else:
- print 'No orders found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID)
-
diff --git a/examples/dfp/v201411/placement_service/create_placements.py b/examples/dfp/v201411/placement_service/create_placements.py
deleted file mode 100755
index 4a160c5e..00000000
--- a/examples/dfp/v201411/placement_service/create_placements.py
+++ /dev/null
@@ -1,110 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new placements for various ad unit sizes.
-
-To determine which placements exist, run get_all_placements.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- placement_service = client.GetService('PlacementService', version='v201411')
- inventory_service = client.GetService('InventoryService', version='v201411')
-
- # Create placement object to store medium rectangle ad units.
- medium_rectangle_ad_unit_placement = {
- 'name': 'Medium rectangle AdUnit Placement #%s' % uuid.uuid4(),
- 'description': 'Contains ad units that hold creatives of size 300x250',
- 'targetedAdUnitIds': []
- }
-
- # Create placement object to store skyscraper ad units.
- skyscraper_ad_unit_placement = {
- 'name': 'Skyscraper AdUnit Placement #%s' % uuid.uuid4(),
- 'description': 'Contains ad units that hold creatives of size 120x600',
- 'targetedAdUnitIds': []
- }
-
- # Create placement object to store banner ad units.
- banner_ad_unit_placement = {
- 'name': 'Banner AdUnit Placement #%s' % uuid.uuid4(),
- 'description': 'Contains ad units that hold creatives of size 468x60',
- 'targetedAdUnitIds': []
- }
-
- placement_list = []
-
- # Create statement to get all the ad units.
- statement = dfp.FilterStatement()
-
- while True:
- response = inventory_service.getAdUnitsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- # Separate the ad units by size.
- for ad_unit in response['results']:
- if 'adUnitSizes' in ad_unit:
- for ad_unit_size in ad_unit['adUnitSizes']:
- size = ad_unit_size['size']
- if size['width'] == '300' and size['height'] == '250':
- medium_rectangle_ad_unit_placement['targetedAdUnitIds'].append(
- ad_unit['id'])
- elif size['width'] == '120' and size['height'] == '600':
- skyscraper_ad_unit_placement['targetedAdUnitIds'].append(
- ad_unit['id'])
- elif size['width'] == '468' and size['height'] == '60':
- banner_ad_unit_placement['targetedAdUnitIds'].append(
- ad_unit['id'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Only create placements with one or more ad unit.
- if medium_rectangle_ad_unit_placement['targetedAdUnitIds']:
- placement_list.append(medium_rectangle_ad_unit_placement)
-
- if skyscraper_ad_unit_placement['targetedAdUnitIds']:
- placement_list.append(skyscraper_ad_unit_placement)
-
- if banner_ad_unit_placement['targetedAdUnitIds']:
- placement_list.append(banner_ad_unit_placement)
-
- # Add placements.
- placements = placement_service.createPlacements(placement_list)
-
- # Display results.
- for placement in placements:
- ad_unit_ids = ''
- if 'targetedAdUnitIds' in placement:
- ad_unit_ids = ', '.join(placement['targetedAdUnitIds'])
- print ('A Placement with ID \'%s\', name \'%s\', and containing ad units '
- '{%s} was created.' % (placement['id'], placement['name'],
- ad_unit_ids))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/placement_service/deactivate_placements.py b/examples/dfp/v201411/placement_service/deactivate_placements.py
deleted file mode 100755
index e83c7930..00000000
--- a/examples/dfp/v201411/placement_service/deactivate_placements.py
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example deactivates all active placements.
-
-To determine which placements exist, run get_all_placements.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-PLACEMENT_ID = 'INSERT_PLACEMENT_ID_HERE'
-
-
-def main(client, placement_id):
- # Initialize appropriate service.
- placement_service = client.GetService('PlacementService', version='v201411')
-
- # Create query.
- values = [{
- 'key': 'placementId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': placement_id
- }
- }]
- query = 'WHERE id = :placementId'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get placements by statement.
- placements = placement_service.getPlacementsByStatement(
- statement.ToStatement())
-
- for placement in placements:
- print ('Placement with id \'%s\', name \'%s\', and status \'%s\' will be '
- 'deactivated.' % (placement['id'], placement['name'],
- placement['status']))
-
- # Perform action.
- result = placement_service.performPlacementAction(
- {'xsi_type': 'DeactivatePlacements'}, statement.ToStatement())
-
- # Display results.
- if result and int(result['numChanges']) > 0:
- print 'Number of placements deactivated: %s' % result['numChanges']
- else:
- print 'No placements were deactivated.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PLACEMENT_ID)
diff --git a/examples/dfp/v201411/placement_service/get_all_placements.py b/examples/dfp/v201411/placement_service/get_all_placements.py
deleted file mode 100755
index 5bf5be02..00000000
--- a/examples/dfp/v201411/placement_service/get_all_placements.py
+++ /dev/null
@@ -1,54 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all placements.
-
-To create placements, run create_placement.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- placement_service = client.GetService('PlacementService', version='v201411')
-
- # Create statement to fetch all placements.
- statement = dfp.FilterStatement()
-
- # Get placements by statement.
- while True:
- response = placement_service.getPlacementsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for placement in response['results']:
- print ('Placement with id \'%s\' and name \'%s\' was found.'
- % (placement['id'], placement['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/placement_service/get_placements_by_statement.py b/examples/dfp/v201411/placement_service/get_placements_by_statement.py
deleted file mode 100755
index 89768f20..00000000
--- a/examples/dfp/v201411/placement_service/get_placements_by_statement.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all active placements by using a statement.
-
-To create a placement, run create_placements.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- placement_service = client.GetService('PlacementService', version='v201411')
-
- # Create a statement to only select active placements.
- values = [{
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ACTIVE'
- }
- }]
- query = 'WHERE status = :status'
- statement = dfp.FilterStatement(query, values)
-
- # Get placements by statement.
- while True:
- response = placement_service.getPlacementsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for placement in response['results']:
- print ('Placement with id \'%s\' and name \'%s\' was found.'
- % (placement['id'], placement['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/placement_service/update_placements.py b/examples/dfp/v201411/placement_service/update_placements.py
deleted file mode 100755
index ef0be169..00000000
--- a/examples/dfp/v201411/placement_service/update_placements.py
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates a single placement to allow for AdSense targeting.
-
-To determine which placements exist, run get_all_placements.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-PLACEMENT_ID = 'INSERT_PLACEMENT_ID_HERE'
-
-
-def main(client, placement_id):
- # Initialize appropriate service.
- placement_service = client.GetService('PlacementService', version='v201411')
-# Create query.
- values = [{
- 'key': 'placementId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': placement_id
- }
- }]
- query = 'WHERE id = :placementId'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get placements by statement.
- placements = placement_service.getPlacementsByStatement(
- statement.ToStatement())
-
- for placement in placements:
- if not placement['targetingDescription']:
- placement['targetingDescription'] = 'Generic description'
- placement['targetingAdLocation'] = 'All images on sports pages.'
- placement['targetingSiteName'] = 'http://code.google.com'
- placement['isAdSenseTargetingEnabled'] = 'true'
-
- # Update placements remotely.
- placements = placement_service.updatePlacements(placements)
-
- for placement in placements:
- print ('Placement with id \'%s\', name \'%s\', and AdSense targeting '
- 'enabled \'%s\' was updated.'
- % (placement['id'], placement['name'],
- placement['isAdSenseTargetingEnabled']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PLACEMENT_ID)
diff --git a/examples/dfp/v201411/premium_rate_service/__init__.py b/examples/dfp/v201411/premium_rate_service/__init__.py
deleted file mode 100755
index a426ca48..00000000
--- a/examples/dfp/v201411/premium_rate_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201411/premium_rate_service/create_premium_rates.py b/examples/dfp/v201411/premium_rate_service/create_premium_rates.py
deleted file mode 100755
index 199a469a..00000000
--- a/examples/dfp/v201411/premium_rate_service/create_premium_rates.py
+++ /dev/null
@@ -1,84 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new premium_rates.
-
-To determine which premium_rates exist, run get_all_premium_rates.py.
-"""
-
-__author__ = 'Nicholas Chen'
-
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE'
-
-
-def main(client, rate_card_id):
- # Initialize appropriate services.
- premium_rate_service = client.GetService('PremiumRateService',
- version='v201411')
-
- # Create an ad unit premium to apply to the rate card.
- ad_unit_premium_feature = {
- 'xsi_type': 'AdUnitPremiumFeature'
- }
-
- # Create a CPC based premium rate value with adjustments in milli amounts.
- # This will adjust a CPC priced proposal line item that has
- # inventory targeting specified by 10% of the cost associated with the rate
- # card (this comes from a percentage adjustment).
- cpc_premium_rate_value = {
- 'premiumFeature': ad_unit_premium_feature,
- 'rateType': 'CPC',
- 'adjustmentSize': 10000,
- 'adjustmentType': 'PERCENTAGE'
- }
-
- # Create a CPM based premium rate value with adjustments in micro amounts.
- # This will adjust a CPM priced proposal line item that has
- # inventory targeting specified by 2 units of the currency associated with
- # the rate card (this comes from absolute value adjustment).
- cpm_premium_rate_value = {
- 'premiumFeature': ad_unit_premium_feature,
- 'rateType': 'CPM',
- 'adjustmentSize': 2000000,
- 'adjustmentType': 'ABSOLUTE_VALUE'
- }
-
- # Create premium_rate objects.
- premium_rate = {
- 'rateCardId': rate_card_id,
- 'pricingMethod': 'ANY_VALUE',
- 'premiumFeature': ad_unit_premium_feature,
- 'premiumRateValues': [cpc_premium_rate_value, cpm_premium_rate_value]
- }
-
- # Add premium_rates.
- premium_rates = premium_rate_service.createPremiumRates([premium_rate])
-
- # Display results.
- for premium_rate in premium_rates:
- print ('A premium rate for \'%s\' was added to the rate card with ID'
- ' of \'%s\'.\n'
- % (premium_rate['premiumFeature']['PremiumFeature.Type'],
- premium_rate['id']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, RATE_CARD_ID)
diff --git a/examples/dfp/v201411/premium_rate_service/get_all_premium_rates.py b/examples/dfp/v201411/premium_rate_service/get_all_premium_rates.py
deleted file mode 100755
index f1cf5d7c..00000000
--- a/examples/dfp/v201411/premium_rate_service/get_all_premium_rates.py
+++ /dev/null
@@ -1,60 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all premium rates.
-
-To create premium rates, run create_premium_rates.py.
-
-Tags: PremiumRateService.getPremiumRatesByStatement
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- premium_rate_service = client.GetService('PremiumRateService',
- version='v201411')
-
- # Create a filter statement.
- statement = dfp.FilterStatement('ORDER BY id ASC')
-
- # Get premium rates by statement.
- while True:
- response = premium_rate_service.getPremiumRatesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for premium_rate in response['results']:
- print ('Premium rate with ID \'%s\' of type \'%s\' assigned to '
- ' rate card with ID \'%s\' was found.\n' % (
- premium_rate['id'],
- premium_rate['premiumFeature']['PremiumFeature.Type'],
- premium_rate['rateCardId']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/premium_rate_service/get_premium_rates_for_a_rate_card.py b/examples/dfp/v201411/premium_rate_service/get_premium_rates_for_a_rate_card.py
deleted file mode 100755
index 6db40fed..00000000
--- a/examples/dfp/v201411/premium_rate_service/get_premium_rates_for_a_rate_card.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all premium rates belonging to a specific rate card.
-
-To create premium rates, run create_premium_rates.py.
-
-Tags: PremiumRateService.getPremiumRatesByStatement
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE'
-
-
-def main(client, rate_card_id):
- # Initialize appropriate service.
- premium_rate_service = client.GetService('PremiumRateService',
- version='v201411')
-
- # Create statement object to select a single proposal by an ID.
- values = [{
- 'key': 'rateCardId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': rate_card_id
- }
- }]
- query = 'WHERE rateCardId = :rateCardId ORDER BY id ASC'
- statement = dfp.FilterStatement(query, values)
-
- # Get premium rates by statement.
- while True:
- response = premium_rate_service.getPremiumRatesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for premium_rate in response['results']:
- print ('Premium rate with ID \'%s\' of type \'%s\' assigned to '
- ' rate card with ID \'%s\' was found.\n' % (
- premium_rate['id'],
- premium_rate['premiumFeature']['PremiumFeature.Type'],
- premium_rate['rateCardId']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, RATE_CARD_ID)
diff --git a/examples/dfp/v201411/premium_rate_service/update_premium_rates.py b/examples/dfp/v201411/premium_rate_service/update_premium_rates.py
deleted file mode 100755
index bb40da22..00000000
--- a/examples/dfp/v201411/premium_rate_service/update_premium_rates.py
+++ /dev/null
@@ -1,94 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates a premium rate to add a flat fee to an existing feature.
-
-To determine which premium rates exist, run get_all_premium_rates.py.
-
-Tags: PremiumRateService.getPremiumRatesByStatement
-Tags: PremiumRateService.updatePremiumRates
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-PREMIUM_RATE_ID = 'INSERT_PREMIUM_RATE_ID_HERE'
-
-
-def main(client, premium_rate_id):
- # Initialize appropriate service.
- premium_rate_service = client.GetService('PremiumRateService',
- version='v201411')
-
- # Create statement object to select a single proposal by an ID.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': premium_rate_id
- }
- }]
- query = 'WHERE id = :id ORDER BY id ASC'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get the premium rate.
- response = premium_rate_service.getPremiumRatesByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- updated_premium_rates = []
- for premium_rate in response['results']:
- # Create a flat fee based premium rate value with a 10% increase.
- new_flat_fee_rate = {
- 'premiumFeature': premium_rate['premiumFeature'],
- 'rateType': 'CPM',
- 'adjustmentSize': 10000,
- 'adjustmentType': 'PERCENTAGE'
- }
-
- # Update the premium rate's premiumRateValues to include a flat fee
- # premium rate.
-
- existing_premium_rate_value = (
- [] if 'premiumRateValues' not in premium_rate else
- premium_rate['premiumRateValues'])
- existing_premium_rate_value.append(new_flat_fee_rate)
- premium_rate['premiumRateValues'] = existing_premium_rate_value
-
- updated_premium_rates.append(premium_rate)
-
- # Update products remotely.
- premium_rates = premium_rate_service.updatePremiumRates(
- updated_premium_rates)
-
- # Display results.
- if premium_rates:
- for premium_rate in premium_rates:
- print ('Premium rate with ID \'%s\', associated with rate card id'
- ' \'%s\' was updated.' % (premium_rate['id'],
- premium_rate['rateCardId']))
- else:
- print 'No premium rates were updated.'
- else:
- print 'No premium rates found to update.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PREMIUM_RATE_ID)
diff --git a/examples/dfp/v201411/product_service/__init__.py b/examples/dfp/v201411/product_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201411/product_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201411/product_service/get_all_products.py b/examples/dfp/v201411/product_service/get_all_products.py
deleted file mode 100755
index ee23f09d..00000000
--- a/examples/dfp/v201411/product_service/get_all_products.py
+++ /dev/null
@@ -1,55 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all products.
-
-Products are created automatically from product templates.
-
-Tags: ProductService.getProductsByStatement
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- product_service = client.GetService('ProductService', version='v201411')
-
- # Create a filter statement.
- statement = dfp.FilterStatement('ORDER BY id ASC')
-
- # Get products by statement.
- while True:
- response = product_service.getProductsByStatement(statement.ToStatement())
- if 'results' in response:
- # Display results.
- for product in response['results']:
- print ('Product with id \'%s\' and name \'%s\' was found.' % (
- product['id'], product['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/product_service/get_products_for_product_template.py b/examples/dfp/v201411/product_service/get_products_for_product_template.py
deleted file mode 100755
index 0d3b1fd1..00000000
--- a/examples/dfp/v201411/product_service/get_products_for_product_template.py
+++ /dev/null
@@ -1,64 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all products created from a product template.
-
-Tags: ProductService.getProductsByStatement
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE'
-
-
-def main(client, product_template_id):
- # Initialize appropriate service.
- product_service = client.GetService('ProductService', version='v201411')
-
- # Create a filter statement to select only products created from a single
- # a product template.
- values = [{
- 'key': 'productTemplateId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': product_template_id
- }
- }]
- query = 'WHERE productTemplateId = :productTemplateId ORDER BY id ASC'
- statement = dfp.FilterStatement(query, values)
-
- # Get products by statement.
- while True:
- response = product_service.getProductsByStatement(statement.ToStatement())
- if 'results' in response:
- # Display results.
- for product in response['results']:
- print ('Product with id \'%s\' and name \'%s\' was found.' % (
- product['id'], product['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PRODUCT_TEMPLATE_ID)
diff --git a/examples/dfp/v201411/product_service/update_products.py b/examples/dfp/v201411/product_service/update_products.py
deleted file mode 100755
index 40c9e246..00000000
--- a/examples/dfp/v201411/product_service/update_products.py
+++ /dev/null
@@ -1,75 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates a product's notes.
-
-To determine which products exist, run get_all_products.py.
-
-Tags: ProductService.getProductsByStatement
-Tags: ProductService.updateProducts
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE'
-
-
-def main(client, product_id):
- # Initialize appropriate service.
- product_service = client.GetService('ProductService', version='v201411')
-
- # Create statement object to select a single product by an ID.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': product_id
- }
- }]
- query = 'WHERE id = :id'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get products by statement.
- response = product_service.getProductsByStatement(statement.ToStatement())
-
- if 'results' in response:
- # Update each local product object by changing its notes.
- updated_products = []
- for product in response['results']:
- product['notes'] = 'Product needs further review before activation.'
- updated_products.append(product)
-
- # Update products remotely.
- products = product_service.updateProducts(updated_products)
-
- # Display results.
- if products:
- for product in products:
- print ('Product with id \'%s\', name \'%s\', and '
- 'notes \'%s\' was updated.'
- % (product['id'], product['name'], product['notes']))
- else:
- print 'No products were updated.'
- else:
- print 'No products found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PRODUCT_ID)
diff --git a/examples/dfp/v201411/product_template_service/__init__.py b/examples/dfp/v201411/product_template_service/__init__.py
deleted file mode 100755
index a426ca48..00000000
--- a/examples/dfp/v201411/product_template_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201411/product_template_service/activate_product_templates.py b/examples/dfp/v201411/product_template_service/activate_product_templates.py
deleted file mode 100755
index 3541655c..00000000
--- a/examples/dfp/v201411/product_template_service/activate_product_templates.py
+++ /dev/null
@@ -1,82 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example activates a product template.
-
-To determine which product templates exist, run get_all_product_templates.py.
-
-Tags: ProductTemplateService.getProductTemplatesByStatement
-Tags: ProductTemplateService.performProductTemplateAction
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the id of the product template to activate.
-PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE'
-
-
-def main(client, product_template_id):
- # Initialize appropriate service.
- product_template_service = client.GetService(
- 'ProductTemplateService', version='v201411')
-
- # Create query.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': product_template_id
- }
- }]
- query = 'WHERE id = :id'
- statement = dfp.FilterStatement(query, values, 1)
-
- product_templates_activated = 0
-
- # Get product_templates by statement.
- while True:
- response = product_template_service.getProductTemplatesByStatement(
- statement.ToStatement())
- if 'results' in response:
- for product_template in response['results']:
- print ('Product template with id \'%s\' and name \'%s\' will be '
- 'activated.' % (product_template['id'],
- product_template['name']))
-
- # Perform action.
- result = product_template_service.performProductTemplateAction(
- {'xsi_type': 'ActivateProductTemplates'}, statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- product_templates_activated += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Display results.
- if product_templates_activated > 0:
- print ('Number of product templates '
- 'activated: %s' % product_templates_activated)
- else:
- print 'No product templates were activated.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PRODUCT_TEMPLATE_ID)
diff --git a/examples/dfp/v201411/product_template_service/create_product_templates.py b/examples/dfp/v201411/product_template_service/create_product_templates.py
deleted file mode 100755
index 7d1d281b..00000000
--- a/examples/dfp/v201411/product_template_service/create_product_templates.py
+++ /dev/null
@@ -1,108 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates a product template.
-
-To determine which product templates exist, run get_all_product_templates.py.
-
-Tags: ProductTemplateService.createProductTemplates
-Tags: NetworkService.getCurrentNetwork
-"""
-
-__author__ = 'Nicholas Chen'
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- product_template_service = client.GetService(
- 'ProductTemplateService', version='v201411')
- network_service = client.GetService(
- 'NetworkService', version='v201411')
-
- # Create a product template.
- product_template = {
- 'name': ('Product template #%d' % uuid.uuid4()),
- 'description': ('This product template creates standard proposal line '
- 'items targeting Chrome browsers with product '
- 'segmentation on ad units and geo targeting.'),
- 'nameMacro': (' - - '
- ' - '),
- 'productType': 'DFP',
- 'rateType': 'CPM',
- 'roadblockingType': 'ONE_OR_MORE',
- 'creativePlaceholders': [
- {
- 'size': {
- 'width': '728',
- 'height': '90'
- }
- },
- {
- 'size': {
- 'width': '300',
- 'height': '250'
- }
- }
- ],
- 'lineItemType': 'STANDARD',
- 'targeting': {
- # Set browser targeting to Chrome.
- 'browserTargeting': [
- {
- 'browsers': [
- {
- 'id': '500072'
- }
- ]
- }
- ]
- },
- 'productSegmentation': {
- 'geoSegment': {
- 'targetedLocations': [
- {'id': '2840',
- 'displayName': 'US'},
- {'id': '2344',
- 'displayName': 'Hong Kong'}
- ]
- },
- 'adUnitSegments': [{
- 'adUnitId': (network_service.getCurrentNetwork()[
- 'effectiveRootAdUnitId']),
- 'includeDescendants': 'true'
- }]
- }
- }
-
- # Create product templates on the server.
- product_templates = product_template_service.createProductTemplates(
- [product_template])
-
- if product_templates:
- for product_template in product_templates:
- print ('A product template with ID \'%s\' and name \'%s\' was '
- 'created.' % (product_template['id'], product_template['name']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/product_template_service/get_all_product_templates.py b/examples/dfp/v201411/product_template_service/get_all_product_templates.py
deleted file mode 100755
index ab7f7dbf..00000000
--- a/examples/dfp/v201411/product_template_service/get_all_product_templates.py
+++ /dev/null
@@ -1,57 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all product templates.
-
-To create product templates, run create_product_template_templates.py.
-
-Tags: ProductTemplateService.getProductTemplatesByStatement
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- product_template_service = client.GetService(
- 'ProductTemplateService', version='v201411')
-
- # Create a filter statement.
- statement = dfp.FilterStatement('ORDER BY id ASC')
-
- # Get product templates by statement.
- while True:
- response = product_template_service.getProductTemplatesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for product_template in response['results']:
- print ('Product template with id \'%s\' and name \'%s\' was found.' % (
- product_template['id'], product_template['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/product_template_service/get_sponsorship_product_templates.py b/examples/dfp/v201411/product_template_service/get_sponsorship_product_templates.py
deleted file mode 100755
index b6fb40d5..00000000
--- a/examples/dfp/v201411/product_template_service/get_sponsorship_product_templates.py
+++ /dev/null
@@ -1,63 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all sponsorship product templates.
-
-Tags: ProductTemplateService.getProductTemplatesByStatement
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- product_template_service = client.GetService(
- 'ProductTemplateService', version='v201411')
-
- # Create a statement to select all sponsorship product templates.
- values = [{
- 'key': 'lineItemType',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'SPONSORSHIP'
- }
- }]
- query = 'WHERE lineItemType = :lineItemType ORDER BY id ASC'
- statement = dfp.FilterStatement(query, values)
-
- # Get product templates by statement.
- while True:
- response = product_template_service.getProductTemplatesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for product_template in response['results']:
- print ('Product template with id \'%s\' and name \'%s\' was found.' % (
- product_template['id'], product_template['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/product_template_service/update_product_templates.py b/examples/dfp/v201411/product_template_service/update_product_templates.py
deleted file mode 100755
index 3e5d562a..00000000
--- a/examples/dfp/v201411/product_template_service/update_product_templates.py
+++ /dev/null
@@ -1,101 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates a product template's GeoTargeting.
-
-To determine which product templates exist, run get_all_product_templates.py.
-
-Tags: ProductTemplateService.getProductTemplatesByStatement
-Tags: ProductTemplateService.updateProductTemplates
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE'
-
-
-def main(client, product_template_id):
- # Initialize appropriate service.
- product_template_service = client.GetService(
- 'ProductTemplateService', version='v201411')
-
- # Create a statement to select a single product template by ID.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': product_template_id
- }
- }]
- query = 'WHERE id = :id ORDER BY id ASC'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get product templates by statement.
- response = product_template_service.getProductTemplatesByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- # Update each local product template object by appending a new geo-target.
- for product_template in response['results']:
- # Create geo-targeting for Canada to append.
- location = {
- 'id': '2124',
- 'displayName': 'Canada'
- }
-
- try:
- targeting = product_template['targeting']
-
- if 'geoTargeting' in targeting:
- geo_targeting = targeting['geoTargeting']
-
- if 'targetedLocations' in geo_targeting:
- geo_targeting['targetedLocations'].append(location)
- else:
- geo_targeting['targetedLocations'] = [location]
- else:
- targeting['geoTargeting'] = {
- 'targetedLocations': [location]
- }
- except KeyError:
- product_template['targeting'] = {
- 'geoTargeting': {
- 'targetedLocations': [location]
- }
- }
-
- # Update products remotely.
- product_templates = product_template_service.updateProductTemplates(
- [product_template])
-
- # Display results.
- if product_templates:
- for product_template in product_templates:
- print ('Product template with id \'%s\' and name \'%s\' was '
- 'updated.' % (product_template['id'], product_template['name']))
- else:
- print 'No product templates were updated.'
- else:
- print 'No product templates found to update.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PRODUCT_TEMPLATE_ID)
diff --git a/examples/dfp/v201411/proposal_line_item_service/__init__.py b/examples/dfp/v201411/proposal_line_item_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201411/proposal_line_item_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201411/proposal_line_item_service/archive_proposal_line_items.py b/examples/dfp/v201411/proposal_line_item_service/archive_proposal_line_items.py
deleted file mode 100755
index f1d5e071..00000000
--- a/examples/dfp/v201411/proposal_line_item_service/archive_proposal_line_items.py
+++ /dev/null
@@ -1,82 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example archives a proposal line item.
-
-To determine which proposal line items exist, run
-get_all_proposal_line_items.py.
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the id of the proposal line item to archive.
-PROPOSAL_LINE_ITEM_ID = 'INSERT_PROPOSAL_LINE_ITEM_ID_HERE'
-
-
-def main(client, proposal_line_item_id):
- # Initialize appropriate service.
- proposal_line_item_service = client.GetService(
- 'ProposalLineItemService', version='v201411')
-
- # Create query.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': proposal_line_item_id
- }
- }]
- query = 'WHERE id = :id'
- statement = dfp.FilterStatement(query, values, 1)
-
- proposal_line_items_archived = 0
-
- # Get proposal line items by statement.
- while True:
- response = proposal_line_item_service.getProposalLineItemsByStatement(
- statement.ToStatement())
- if 'results' in response:
- for proposal_line_item in response['results']:
- print ('Proposal line item with id \'%s\', '
- 'belonging to proposal id \'%s\', and '
- 'name \'%s\' will be archived.' %
- (proposal_line_item['id'], proposal_line_item['proposalId'],
- proposal_line_item['name']))
-
- # Perform action.
- result = proposal_line_item_service.performProposalLineItemAction(
- {'xsi_type': 'ArchiveProposalLineItems'}, statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- proposal_line_items_archived += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Display results.
- if proposal_line_items_archived > 0:
- print ('Number of proposal line items '
- 'archived: %s' % proposal_line_items_archived)
- else:
- print 'No proposal line items were archived.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PROPOSAL_LINE_ITEM_ID)
diff --git a/examples/dfp/v201411/proposal_line_item_service/create_proposal_line_items.py b/examples/dfp/v201411/proposal_line_item_service/create_proposal_line_items.py
deleted file mode 100755
index 8933c4f8..00000000
--- a/examples/dfp/v201411/proposal_line_item_service/create_proposal_line_items.py
+++ /dev/null
@@ -1,120 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates a new run-of-network proposal line item.
-
-To determine which proposal line items exist, run
-get_all_proposal_line_items.py. To determine which proposals exist, run
-get_all_proposals.py.
-"""
-
-__author__ = 'Nicholas Chen'
-
-from datetime import date
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set proposal that the created proposal line item will belong to.
-PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE'
-
-# Set the ID of the product that the proposal line items should be created from.
-PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE'
-
-# Set the ID of the rate card the proposal line items should be priced from.
-RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE'
-
-
-def main(client, proposal_id, product_id, rate_card_id):
- # Initialize appropriate service.
- proposal_line_item_service = client.GetService(
- 'ProposalLineItemService', version='v201411')
- network_service = client.GetService('NetworkService', version='v201411')
-
- # Get the root ad unit to target.
- root_ad_unit_id = (
- network_service.getCurrentNetwork()['effectiveRootAdUnitId'])
-
- # Create a single proposal line item.
- proposal_line_item = {
- 'name': 'Proposal line item #%s' % uuid.uuid4(),
- 'rateCardId': rate_card_id,
- 'productId': product_id,
- 'proposalId': proposal_id,
- 'targeting': {
- 'inventoryTargeting': {
- 'targetedAdUnits': {
- 'adUnitId': root_ad_unit_id
- }
- }
- },
- 'startDateTime': {
- 'date': {
- 'year': str(date.today().year),
- 'month': str(date.today().month),
- 'day': str(date.today().day)
- },
- 'hour': '23',
- 'minute': '59',
- 'second': '59'
- },
- 'endDateTime': {
- 'date': {
- 'year': str(date.today().year + 1),
- 'month': '9',
- 'day': '30'
- },
- 'hour': '0',
- 'minute': '0',
- 'second': '0'
- },
- 'deliveryRateType': 'EVENLY',
- 'creativeRotationType': 'OPTIMIZED',
- 'billingCap': 'CAPPED_CUMULATIVE',
- 'billingSource': 'THIRD_PARTY_VOLUME',
- 'goal': {
- 'units': '1000',
- 'unitType': 'IMPRESSIONS',
- },
- 'cost': {
- 'currencyCode': 'USD',
- 'microAmount': '2000000'
- },
- 'costPerUnit': {
- 'currencyCode': 'USD',
- 'microAmount': '2000000'
- },
- 'rateType': 'CPM',
- }
-
- # Add proposal line items.
- proposal_line_items = proposal_line_item_service.createProposalLineItems(
- [proposal_line_item])
-
- # Display results.
- for proposal_line_item in proposal_line_items:
- print ('Proposal line item with id \'%s\', belonging to proposal id \'%s\''
- ', and named \'%s\' was created.' %
- (proposal_line_item['id'], proposal_line_item['proposalId'],
- proposal_line_item['name']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PROPOSAL_ID, PRODUCT_ID, RATE_CARD_ID)
-
diff --git a/examples/dfp/v201411/proposal_line_item_service/get_all_proposal_line_items.py b/examples/dfp/v201411/proposal_line_item_service/get_all_proposal_line_items.py
deleted file mode 100755
index f2ec70d4..00000000
--- a/examples/dfp/v201411/proposal_line_item_service/get_all_proposal_line_items.py
+++ /dev/null
@@ -1,58 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all proposal line items.
-
-To create proposal line items, run create_proposal_line_items.py.
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- proposal_line_item_service = client.GetService(
- 'ProposalLineItemService', version='v201411')
-
- # Create a filter statement.
- statement = dfp.FilterStatement('ORDER BY id ASC')
-
- # Get proposal line items by statement.
- while True:
- response = proposal_line_item_service.getProposalLineItemsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for idx, proposal_line_item in enumerate(response['results'],
- start=statement.offset):
- print ('%s) Proposal line item with id \'%s\', belonging to proposal id'
- ' \'%s\', and named \'%s\' was found.' %
- (idx, proposal_line_item['id'], proposal_line_item['proposalId'],
- proposal_line_item['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/dfp/v201411/proposal_line_item_service/get_proposal_line_items_for_proposal.py
deleted file mode 100755
index 71c05562..00000000
--- a/examples/dfp/v201411/proposal_line_item_service/get_proposal_line_items_for_proposal.py
+++ /dev/null
@@ -1,71 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all proposal line items that belong to a proposal.
-
-To create proposal line items, run create_proposal_line_items.py."""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the id of the proposal to get proposal line items from.
-PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE'
-
-
-def main(client, proposal_id):
- # Initialize appropriate service.
- proposal_line_item_service = client.GetService(
- 'ProposalLineItemService', version='v201411')
-
- # Create statement object to only select proposal line items belonging to a
- # given proposal.
- values = [{
- 'key': 'proposalId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': proposal_id
- }
- }]
- query = 'WHERE proposalId = :proposalId ORDER BY id ASC'
- statement = dfp.FilterStatement(query, values)
-
- while True:
- # Get proposal line items by statement.
- response = proposal_line_item_service.getProposalLineItemsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- # Display results.
- for idx, proposal_line_item in enumerate(response['results'],
- start=statement.offset):
- print ('%s) Line item with id \'%s\', belonging to proposal id \'%s\', '
- 'and named \'%s\' was found.' % (
- idx, proposal_line_item['id'],
- proposal_line_item['proposalId'],
- proposal_line_item['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PROPOSAL_ID)
diff --git a/examples/dfp/v201411/proposal_line_item_service/update_proposal_line_items.py b/examples/dfp/v201411/proposal_line_item_service/update_proposal_line_items.py
deleted file mode 100755
index 3aceda7c..00000000
--- a/examples/dfp/v201411/proposal_line_item_service/update_proposal_line_items.py
+++ /dev/null
@@ -1,78 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates a proposal line item's notes.
-
-To determine which proposal line items exist,
-run get_all_proposal_line_items.py.
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set id of the proposal line item to update.
-PROPOSAL_LINE_ITEM_ID = 'INSERT_PROPOSAL_LINE_ITEM_ID_HERE'
-
-
-def main(client, proposal_line_item_id):
- # Initialize appropriate service.
- proposal_line_item_service = client.GetService(
- 'ProposalLineItemService', version='v201411')
-
- # Create statement to select a proposal line item.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': proposal_line_item_id
- }
- }]
-
- query = 'WHERE id = :id'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get proposal line items by statement.
- response = proposal_line_item_service.getProposalLineItemsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- # Update each the proposal line item's notes field.
- proposal_line_item = response['results'][0]
- proposal_line_item['notes'] = 'Proposal line item ready for submission.'
-
- # Update proposal line items remotely.
- proposal_line_items = proposal_line_item_service.updateProposalLineItems(
- [proposal_line_item])
-
- # Display results.
- if proposal_line_items:
- for proposal_line_item in proposal_line_items:
- print ('Line item with id \'%s\', belonging to proposal id \'%s\' and,'
- ' named \'%s\' was updated.' % (
- proposal_line_item['id'], proposal_line_item['proposalId'],
- proposal_line_item['name']))
- else:
- print 'No proposal line items were updated.'
- else:
- print 'No proposal line items found to update.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PROPOSAL_LINE_ITEM_ID)
diff --git a/examples/dfp/v201411/proposal_service/__init__.py b/examples/dfp/v201411/proposal_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201411/proposal_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201411/proposal_service/create_proposals.py b/examples/dfp/v201411/proposal_service/create_proposals.py
deleted file mode 100755
index 8a296fbc..00000000
--- a/examples/dfp/v201411/proposal_service/create_proposals.py
+++ /dev/null
@@ -1,77 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new proposals.
-
-To determine which proposals exist, run get_all_proposals.py."""
-
-__author__ = 'Nicholas Chen'
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE'
-PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE'
-SECONDARY_SALESPERSON_ID = 'INSERT_SECONDARY_SALESPERSON_ID_HERE'
-PRIMARY_TRAFFICKER_ID = 'INSERT_PRIMARY_TRAFFICKER_ID_HERE'
-
-
-def main(client, advertiser_id, primary_salesperson_id,
- secondary_salesperson_id, primary_trafficker_id):
- # Initialize appropriate services.
- proposal_service = client.GetService('ProposalService', version='v201411')
- network_service = client.GetService('NetworkService', version='v201411')
-
- # Create proposal objects.
- proposal = {
- 'name': 'Proposal #%s' % uuid.uuid4(),
- 'advertiser': {
- 'companyId': advertiser_id,
- 'type': 'ADVERTISER'
- },
- 'primarySalesperson': {
- 'userId': primary_salesperson_id,
- 'split': '75000'
- },
- 'secondarySalespeople': [{
- 'userId': secondary_salesperson_id,
- 'split': '25000'
- }],
- 'primaryTraffickerId': primary_trafficker_id,
- 'probabilityOfClose': '100000',
- 'budget': {
- 'microAmount': '100000000',
- 'currencyCode': network_service.getCurrentNetwork()['currencyCode']
- },
- 'billingCap': 'CAPPED_CUMULATIVE',
- 'billingSource': 'DFP_VOLUME'
- }
-
- # Add proposals.
- proposals = proposal_service.createProposals([proposals])
-
- # Display results.
- for proposal in proposals:
- print ('Proposal with id \'%s\' and name \'%s\' was created.'
- % (proposal['id'], proposal['name']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ADVERTISER_ID, PRIMARY_SALESPERSON_ID,
- SECONDARY_SALESPERSON_ID, PRIMARY_TRAFFICKER_ID)
diff --git a/examples/dfp/v201411/proposal_service/get_all_proposals.py b/examples/dfp/v201411/proposal_service/get_all_proposals.py
deleted file mode 100755
index 8f99c808..00000000
--- a/examples/dfp/v201411/proposal_service/get_all_proposals.py
+++ /dev/null
@@ -1,53 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all proposals.
-
-To create proposals, run create_proposals.py.
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- proposal_service = client.GetService('ProposalService', version='v201411')
-
- # Create a filter statement.
- statement = dfp.FilterStatement('ORDER BY id ASC')
-
- # Get proposals by statement.
- while True:
- response = proposal_service.getProposalsByStatement(statement.ToStatement())
- if 'results' in response:
- # Display results.
- for proposal in response['results']:
- print ('Proposal with id \'%s\' and name \'%s\' was found.' % (
- proposal['id'], proposal['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/proposal_service/get_proposals_by_statement.py b/examples/dfp/v201411/proposal_service/get_proposals_by_statement.py
deleted file mode 100755
index b2882dcb..00000000
--- a/examples/dfp/v201411/proposal_service/get_proposals_by_statement.py
+++ /dev/null
@@ -1,61 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all proposals that are currently 'PENDING_APPROVAL.'
-
-To create proposals, run create_proposals.py."""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- proposal_service = client.GetService('ProposalService', version='v201411')
-
- # Create statement object to select a single proposal by an ID.
- values = [{
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'PENDING_APPROVAL'
- }
- }]
- query = 'WHERE status = :status ORDER BY id ASC'
-
- statement = dfp.FilterStatement(query, values)
-
- # Get proposals by statement.
- while True:
- response = proposal_service.getProposalsByStatement(statement.ToStatement())
- if 'results' in response:
- # Display results.
- for proposal in response['results']:
- print ('Proposal with id \'%s\' name \'%s\' was found.'
- % (proposal['id'], proposal['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/proposal_service/submit_proposals_for_approval.py b/examples/dfp/v201411/proposal_service/submit_proposals_for_approval.py
deleted file mode 100755
index 7b34c17b..00000000
--- a/examples/dfp/v201411/proposal_service/submit_proposals_for_approval.py
+++ /dev/null
@@ -1,73 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example approves a single proposal.
-
-To determine which proposals exist, run get_all_proposals.py."""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE'
-
-def main(client, proposal_id):
- # Initialize appropriate service.
- proposal_service = client.GetService('ProposalService', version='v201411')
-
- # Create query.
- values = [{
- 'key': 'proposalId',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': proposal_id
- }
- }]
- query = 'WHERE id = :proposalId'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
- proposals_approved = 0
-
- # Get proposals by statement.
- while True:
- response = proposal_service.getProposalsByStatement(statement.ToStatement())
- if 'results' in response:
- # Display results.
- for proposal in response['results']:
- print ('Proposal with id \'%s\', name \'%s\', and status \'%s\' will be'
- ' approved.' % (proposal['id'], proposal['name'],
- proposal['status']))
- # Perform action.
- result = proposal_service.performProposalAction(
- {'xsi_type': 'SubmitProposalsForApproval'}, statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- proposals_approved += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Display results.
- if proposals_approved > 0:
- print '\nNumber of proposals approved: %s' % proposals_approved
- else:
- print '\nNo proposals were approved.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PROPOSAL_ID)
diff --git a/examples/dfp/v201411/proposal_service/update_proposals.py b/examples/dfp/v201411/proposal_service/update_proposals.py
deleted file mode 100755
index 28ec32f9..00000000
--- a/examples/dfp/v201411/proposal_service/update_proposals.py
+++ /dev/null
@@ -1,72 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates the notes of a single proposal specified by ID.
-
-To determine which proposals exist, run get_all_proposals.py."""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE'
-
-
-def main(client, proposal_id):
- # Initialize appropriate service.
- proposal_service = client.GetService('ProposalService', version='v201411')
-
- # Create statement object to select a single proposal by an ID.
- values = [{
- 'key': 'proposalId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': proposal_id
- }
- }]
- query = 'WHERE id = :proposalId'
-
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get proposals by statement.
- response = proposal_service.getProposalsByStatement(statement.ToStatement())
-
- if 'results' in response:
- # Update each local proposal object by changing its notes.
- updated_proposals = []
- for proposal in response['results']:
- proposal['notes'] = 'Proposal needs further review before approval.'
- updated_proposals.append(proposal)
-
- # Update proposals remotely.
- proposals = proposal_service.updateProposals(updated_proposals)
-
- # Display results.
- if proposals:
- for proposal in proposals:
- print ('Proposal with id \'%s\', name \'%s\', and '
- 'notes \'%s\' was updated.'
- % (proposal['id'], proposal['name'], proposal['notes']))
- else:
- print 'No proposals were updated.'
- else:
- print 'No proposals found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PROPOSAL_ID)
diff --git a/examples/dfp/v201411/publisher_query_language_service/__init__.py b/examples/dfp/v201411/publisher_query_language_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201411/publisher_query_language_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201411/publisher_query_language_service/fetch_match_tables.py b/examples/dfp/v201411/publisher_query_language_service/fetch_match_tables.py
deleted file mode 100755
index bf661f14..00000000
--- a/examples/dfp/v201411/publisher_query_language_service/fetch_match_tables.py
+++ /dev/null
@@ -1,57 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example fetches data from PQL tables and creates match table files."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import tempfile
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize a report downloader.
- report_downloader = client.GetDataDownloader(version='v201411')
-
- line_items_file = tempfile.NamedTemporaryFile(
- prefix='line_items_', suffix='.csv', mode='w', delete=False)
- ad_units_file = tempfile.NamedTemporaryFile(
- prefix='ad_units_', suffix='.csv', mode='w', delete=False)
-
- line_items_pql_query = ('SELECT Name, Id, Status FROM Line_Item ORDER BY Id '
- 'ASC')
- ad_units_pql_query = 'SELECT Name, Id FROM Ad_Unit ORDER BY Id ASC'
-
- # Downloads the response from PQL select statement to the specified file
- report_downloader.DownloadPqlResultToCsv(
- line_items_pql_query, line_items_file)
- report_downloader.DownloadPqlResultToCsv(
- ad_units_pql_query, ad_units_file)
-
- line_items_file.close()
- ad_units_file.close()
-
- print ('Saved line items to... %s' % line_items_file.name)
- print ('Saved ad units to... %s' % ad_units_file.name)
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/publisher_query_language_service/get_geo_targets.py b/examples/dfp/v201411/publisher_query_language_service/get_geo_targets.py
deleted file mode 100755
index 71c0e7a6..00000000
--- a/examples/dfp/v201411/publisher_query_language_service/get_geo_targets.py
+++ /dev/null
@@ -1,65 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets geographic criteria from the Geo_Target table.
-
-The types available to filter on include 'City', 'Country', 'Region', 'State',
-'Postal_Code', and 'DMA_Region' (i.e. Metro).
-
-A full list of available geo target types can be found at
-https://developers.google.com/doubleclick-publishers/docs/reference/v201411/PublisherQueryLanguageService
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import tempfile
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize a report downloader.
- report_downloader = client.GetDataDownloader(version='v201411')
-
- output_file = tempfile.NamedTemporaryFile(
- prefix='geo_target_type_', suffix='.csv', mode='w', delete=False)
-
- # Create bind value to select geo-targets of type 'City'.
- values = [{
- 'key': 'type',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'City'
- }
- }]
-
- pql_query = ('SELECT Name, Id FROM Geo_Target '
- 'WHERE targetable = true AND Type = :type')
-
- # Downloads the response from PQL select statement to the specified file
- report_downloader.DownloadPqlResultToCsv(
- pql_query, output_file, values)
- output_file.close()
-
- print ('Saved geo targets to... %s' % output_file.name)
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/publisher_query_language_service/get_line_items_named_like.py b/examples/dfp/v201411/publisher_query_language_service/get_line_items_named_like.py
deleted file mode 100755
index 3dc35259..00000000
--- a/examples/dfp/v201411/publisher_query_language_service/get_line_items_named_like.py
+++ /dev/null
@@ -1,58 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all line items with names starting with 'line item'."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import tempfile
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize a report downloader.
- report_downloader = client.GetDataDownloader(version='v201411')
-
- output_file = tempfile.NamedTemporaryFile(
- prefix='line_items_named_like_', suffix='.csv', mode='w', delete=False)
-
- # Create bind value to select line items with names starting with 'line item'.
- values = [{
- 'key': 'name',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'line item%'
- }
- }]
-
- pql_query = ('SELECT Name, Id, Status FROM Line_Item '
- 'WHERE Name LIKE :name')
-
- # Downloads the response from PQL select statement to the specified file
- report_downloader.DownloadPqlResultToCsv(
- pql_query, output_file, values)
- output_file.close()
-
- print ('Saved line items to... %s' % output_file.name)
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/rate_card_service/__init__.py b/examples/dfp/v201411/rate_card_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201411/rate_card_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201411/rate_card_service/get_all_rate_cards.py b/examples/dfp/v201411/rate_card_service/get_all_rate_cards.py
deleted file mode 100755
index 1cf2b027..00000000
--- a/examples/dfp/v201411/rate_card_service/get_all_rate_cards.py
+++ /dev/null
@@ -1,55 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all rate cards.
-
-Tags: RateCardService.getRateCardsByStatement
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- rate_card_service = client.GetService('RateCardService', version='v201411')
-
- # Create a filter statement.
- statement = dfp.FilterStatement('ORDER BY id ASC')
-
- # Get rate cards by statement.
- while True:
- response = rate_card_service.getRateCardsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for rate_card in response['results']:
- print ('Rate card with id \'%s,\' name \'%s,\' and currency \'%s\' '
- 'was found.' % (rate_card['id'], rate_card['name'],
- rate_card['currencyCode']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/rate_card_service/get_rate_cards_priced_with_currency.py b/examples/dfp/v201411/rate_card_service/get_rate_cards_priced_with_currency.py
deleted file mode 100755
index 27497359..00000000
--- a/examples/dfp/v201411/rate_card_service/get_rate_cards_priced_with_currency.py
+++ /dev/null
@@ -1,64 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all rate cards that have a currency in US dollars.
-
-Tags: RateCardService.getRateCardsByStatement
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- rate_card_service = client.GetService('RateCardService', version='v201411')
-
- # Create a statement to get all rate cards using USD as currency.
- values = [{
- 'key': 'currencyCode',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'USD'
- }
- }]
- query = 'WHERE currencyCode = :currencyCode'
-
- statement = dfp.FilterStatement(query, values)
-
- # Get rate cards by statement.
- while True:
- response = rate_card_service.getRateCardsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for rate_card in response['results']:
- print ('Rate card with id \'%s,\' name \'%s,\' and currency \'%s\' '
- 'was found.' % (rate_card['id'], rate_card['name'],
- rate_card['currencyCode']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/report_service/__init__.py b/examples/dfp/v201411/report_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201411/report_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201411/report_service/run_delivery_report.py b/examples/dfp/v201411/report_service/run_delivery_report.py
deleted file mode 100755
index 274741b8..00000000
--- a/examples/dfp/v201411/report_service/run_delivery_report.py
+++ /dev/null
@@ -1,85 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example runs a report similar to the "Orders report" on the DFP
-website with additional attributes and can filter to include just one order.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-import tempfile
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-from googleads import errors
-
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-
-
-def main(client, order_id):
- # Create statement object to filter for an order.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': order_id
- }
- }]
- filter_statement = {'query': 'WHERE ORDER_ID = :id',
- 'values': values}
-
- # Create report job.
- report_job = {
- 'reportQuery': {
- 'dimensions': ['ORDER_ID', 'ORDER_NAME'],
- 'dimensionAttributes': ['ORDER_TRAFFICKER', 'ORDER_START_DATE_TIME',
- 'ORDER_END_DATE_TIME'],
- 'statement': filter_statement,
- 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS',
- 'AD_SERVER_CTR', 'AD_SERVER_CPM_AND_CPC_REVENUE',
- 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'],
- 'dateRangeType': 'LAST_MONTH'
- }
- }
-
- # Initialize a DataDownloader.
- report_downloader = client.GetDataDownloader(version='v201411')
-
- try:
- # Run the report and wait for it to finish.
- report_job_id = report_downloader.WaitForReport(report_job)
- except errors.DfpReportError, e:
- print 'Failed to generate report. Error was: %s' % e
-
- # Change to your preferred export format.
- export_format = 'CSV_DUMP'
-
- report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
-
- # Download report data.
- report_downloader.DownloadReportToFile(
- report_job_id, export_format, report_file)
-
- report_file.close()
-
- # Display results.
- print 'Report job with id \'%s\' downloaded to:\n%s' % (
- report_job_id, report_file.name)
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID)
diff --git a/examples/dfp/v201411/report_service/run_inventory_report.py b/examples/dfp/v201411/report_service/run_inventory_report.py
deleted file mode 100755
index 508cc250..00000000
--- a/examples/dfp/v201411/report_service/run_inventory_report.py
+++ /dev/null
@@ -1,90 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example runs a report equal to the "Whole network report" on the
-DFP website.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-import tempfile
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-from googleads import errors
-
-
-def main(client):
- # Initialize appropriate service.
- network_service = client.GetService('NetworkService', version='v201411')
- # Initialize a DataDownloader.
- report_downloader = client.GetDataDownloader(version='v201411')
-
- # Get root ad unit id for network.
- root_ad_unit_id = (
- network_service.getCurrentNetwork()['effectiveRootAdUnitId'])
-
- # Set filter statement and bind value for reportQuery.
- values = [{
- 'key': 'parent_ad_unit_id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': root_ad_unit_id
- }
- }]
- filter_statement = {'query': 'WHERE PARENT_AD_UNIT_ID = :parent_ad_unit_id',
- 'values': values}
-
- # Create report job.
- report_job = {
- 'reportQuery': {
- 'dimensions': ['DATE', 'AD_UNIT_NAME'],
- 'adUnitView': 'HIERARCHICAL',
- 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS',
- 'DYNAMIC_ALLOCATION_INVENTORY_LEVEL_IMPRESSIONS',
- 'DYNAMIC_ALLOCATION_INVENTORY_LEVEL_CLICKS',
- 'TOTAL_INVENTORY_LEVEL_IMPRESSIONS',
- 'TOTAL_INVENTORY_LEVEL_CPM_AND_CPC_REVENUE'],
- 'dateRangeType': 'LAST_WEEK',
- 'statement': filter_statement
- }
- }
-
- try:
- # Run the report and wait for it to finish.
- report_job_id = report_downloader.WaitForReport(report_job)
- except errors.DfpReportError, e:
- print 'Failed to generate report. Error was: %s' % e
-
- # Change to your preferred export format.
- export_format = 'CSV_DUMP'
-
- report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
-
- # Download report data.
- report_downloader.DownloadReportToFile(
- report_job_id, export_format, report_file)
-
- report_file.close()
-
- # Display results.
- print 'Report job with id \'%s\' downloaded to:\n%s' % (
- report_job_id, report_file.name)
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/report_service/run_reach_report.py b/examples/dfp/v201411/report_service/run_reach_report.py
deleted file mode 100755
index 747c6893..00000000
--- a/examples/dfp/v201411/report_service/run_reach_report.py
+++ /dev/null
@@ -1,66 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example runs a reach report."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-import tempfile
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-from googleads import errors
-
-
-def main(client):
- # Initialize a DataDownloader.
- report_downloader = client.GetDataDownloader(version='v201411')
-
- # Create report job.
- report_job = {
- 'reportQuery': {
- 'dimensions': ['LINE_ITEM_ID', 'LINE_ITEM_NAME'],
- 'columns': ['REACH_FREQUENCY', 'REACH_AVERAGE_REVENUE', 'REACH'],
- 'dateRangeType': 'REACH_LIFETIME'
- }
- }
-
- try:
- # Run the report and wait for it to finish.
- report_job_id = report_downloader.WaitForReport(report_job)
- except errors.DfpReportError, e:
- print 'Failed to generate report. Error was: %s' % e
-
- # Change to your preferred export format.
- export_format = 'CSV_DUMP'
-
- report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
-
- # Download report data.
- report_downloader.DownloadReportToFile(
- report_job_id, export_format, report_file)
-
- report_file.close()
-
- # Display results.
- print 'Report job with id \'%s\' downloaded to:\n%s' % (
- report_job_id, report_file.name)
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/report_service/run_report_with_custom_fields.py b/examples/dfp/v201411/report_service/run_report_with_custom_fields.py
deleted file mode 100755
index 2abb3f69..00000000
--- a/examples/dfp/v201411/report_service/run_report_with_custom_fields.py
+++ /dev/null
@@ -1,107 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example runs a report that with custom fields found in the line
-items of an order.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-import tempfile
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-from googleads import errors
-
-# Set the ID of the order to get line items from.
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-
-
-def main(client, order_id):
- # Initialize appropriate service.
- line_item_service = client.GetService('LineItemService', version='v201411')
- # Initialize a DataDownloader.
- report_downloader = client.GetDataDownloader(version='v201411')
-
- # Filter for line items of a given order.
- values = [{
- 'key': 'orderId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': order_id
- }
- }]
- query = 'WHERE orderId = :orderId'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Collect all line item custom field IDs for an order.
- custom_field_ids = set()
-
- # Get users by statement.
- while True:
- response = line_item_service.getLineItemsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Get custom field IDs from the line items of an order.
- for line_item in response['results']:
- if 'customFieldValues' in line_item:
- for custom_field_value in line_item['customFieldValues']:
- custom_field_ids.add(custom_field_value['customFieldId'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Create statement object to filter for an order.
- filter_statement = {'query': query, 'values': values}
-
- # Create report job.
- report_job = {
- 'reportQuery': {
- 'dimensions': ['LINE_ITEM_ID', 'LINE_ITEM_NAME'],
- 'statement': filter_statement,
- 'columns': ['AD_SERVER_IMPRESSIONS'],
- 'dateRangeType': 'LAST_MONTH',
- 'customFieldIds': list(custom_field_ids)
- }
- }
-
- try:
- # Run the report and wait for it to finish.
- report_job_id = report_downloader.WaitForReport(report_job)
- except errors.DfpReportError, e:
- print 'Failed to generate report. Error was: %s' % e
-
- # Change to your preferred export format.
- export_format = 'CSV_DUMP'
-
- report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
-
- # Download report data.
- report_downloader.DownloadReportToFile(
- report_job_id, export_format, report_file)
-
- report_file.close()
-
- # Display results.
- print 'Report job with id \'%s\' downloaded to:\n%s' % (
- report_job_id, report_file.name)
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID)
diff --git a/examples/dfp/v201411/report_service/run_sales_report.py b/examples/dfp/v201411/report_service/run_sales_report.py
deleted file mode 100755
index f77c2ea0..00000000
--- a/examples/dfp/v201411/report_service/run_sales_report.py
+++ /dev/null
@@ -1,67 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example runs a report equal to the "Sales by salespersons report."
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-import tempfile
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-from googleads import errors
-
-
-def main(client):
- # Initialize a DataDownloader.
- report_downloader = client.GetDataDownloader(version='v201411')
-
- # Create report job.
- report_job = {
- 'reportQuery': {
- 'dimensions': ['SALESPERSON_ID', 'SALESPERSON_NAME'],
- 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CPM_AND_CPC_REVENUE',
- 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'],
- 'dateRangeType': 'LAST_MONTH'
- }
- }
-
- try:
- # Run the report and wait for it to finish.
- report_job_id = report_downloader.WaitForReport(report_job)
- except errors.DfpReportError, e:
- print 'Failed to generate report. Error was: %s' % e
-
- # Change to your preferred export format.
- export_format = 'CSV_DUMP'
-
- report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
-
- # Download report data.
- report_downloader.DownloadReportToFile(
- report_job_id, export_format, report_file)
-
- report_file.close()
-
- # Display results.
- print 'Report job with id \'%s\' downloaded to:\n%s' % (
- report_job_id, report_file.name)
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/suggested_ad_unit_service/__init__.py b/examples/dfp/v201411/suggested_ad_unit_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201411/suggested_ad_unit_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201411/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/dfp/v201411/suggested_ad_unit_service/approve_all_suggested_ad_units.py
deleted file mode 100755
index adc975fb..00000000
--- a/examples/dfp/v201411/suggested_ad_unit_service/approve_all_suggested_ad_units.py
+++ /dev/null
@@ -1,80 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example approves all suggested ad units with 50 or more requests.
-
-This feature is only available to DFP premium solution networks.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-THRESHOLD_NUMBER_OF_REQUESTS = '50'
-
-
-def main(client):
- # Initialize appropriate service.
- suggested_ad_unit_service = client.GetService(
- 'SuggestedAdUnitService', version='v201411')
-
- values = [{
- 'key': 'numRequests',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': THRESHOLD_NUMBER_OF_REQUESTS
- }
- }]
-
- query = 'WHERE numRequests > :numRequests'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
- num_approved_suggested_ad_units = 0
-
- # Get suggested ad units by statement.
- while True:
- response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Print suggested ad units that will be approved.
- for suggested_ad_unit in response['results']:
- print ('Suggested ad unit with id \'%s\', and number of requests \'%s\''
- ' will be approved.' % (suggested_ad_unit['id'],
- suggested_ad_unit['numRequests']))
-
- # Approve suggested ad units.
- result = suggested_ad_unit_service.performSuggestedAdUnitAction(
- {'xsi_type': 'ApproveSuggestedAdUnit'},
- statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- num_approved_suggested_ad_units += int(result['numChanges'])
- else:
- break
-
- if num_approved_suggested_ad_units > 0:
- print ('Number of suggested ad units approved: %s' %
- num_approved_suggested_ad_units)
- else:
- print 'No suggested ad units were approved.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
-
diff --git a/examples/dfp/v201411/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/dfp/v201411/suggested_ad_unit_service/get_all_suggested_ad_units.py
deleted file mode 100755
index e57a1aba..00000000
--- a/examples/dfp/v201411/suggested_ad_unit_service/get_all_suggested_ad_units.py
+++ /dev/null
@@ -1,56 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all suggested ad units.
-
-To approve suggested ad units, run approve_suggested_ad_units.py. This feature
-is only available to DFP premium solution networks.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- suggested_ad_unit_service = client.GetService(
- 'SuggestedAdUnitService', version='v201411')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get suggested ad units by statement.
- while True:
- response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for suggested_ad_unit in response['results']:
- print ('Ad unit with id \'%s\' and number of requests \'%s\' was found.'
- % (suggested_ad_unit['id'], suggested_ad_unit['numRequests']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py b/examples/dfp/v201411/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py
deleted file mode 100755
index 949c5678..00000000
--- a/examples/dfp/v201411/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py
+++ /dev/null
@@ -1,65 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets suggested ad units that have more than 50 requests.
-
-This feature is only available to DFP premium solution networks.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- suggested_ad_unit_service = client.GetService(
- 'SuggestedAdUnitService', version='v201411')
-
- values = [{
- 'key': 'numRequests',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': '50'
- }
- }]
-
- query = 'WHERE numRequests > :numRequests'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Get suggested ad units by statement.
- while True:
- response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for suggested_ad_unit in response['results']:
- print ('Ad unit with id \'%s\' and number of requests \'%s\' was found.'
- % (suggested_ad_unit['id'], suggested_ad_unit['numRequests']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/team_service/__init__.py b/examples/dfp/v201411/team_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201411/team_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201411/team_service/create_teams.py b/examples/dfp/v201411/team_service/create_teams.py
deleted file mode 100755
index 36d32532..00000000
--- a/examples/dfp/v201411/team_service/create_teams.py
+++ /dev/null
@@ -1,64 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates new teams.
-
-To determine which teams exist, run get_all_teams.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: TeamService.createTeams
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- team_service = client.GetService('TeamService', version='v201411')
-
- # Create team objects.
- teams = []
- for i in xrange(5):
- team = {
- 'name': 'Team %s' % uuid.uuid4(),
- 'hasAllCompanies': 'false',
- 'hasAllInventory': 'false',
- 'teamAccessType': 'READ_WRITE'
- }
- teams.append(team)
-
- # Add Teams.
- teams = team_service.createTeams(teams)
-
- # Display results.
- for team in teams:
- print ('Team with ID \'%s\' and name \'%s\' was created.'
- % (team['id'], team['name']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/team_service/get_all_teams.py b/examples/dfp/v201411/team_service/get_all_teams.py
deleted file mode 100755
index cd91f0a4..00000000
--- a/examples/dfp/v201411/team_service/get_all_teams.py
+++ /dev/null
@@ -1,60 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all teams.
-
-To create teams, run create_teams.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: TeamService.getTeamsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- team_service = client.GetService('TeamService', version='v201411')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get users by statement.
- while True:
- response = team_service.getTeamsByStatement(statement.ToStatement())
- if 'results' in response:
- # Display results.
- for team in response['results']:
- print ('Team with ID \'%s\' and name \'%s\' was found.'
- % (team['id'], team['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/team_service/get_teams_by_statement.py b/examples/dfp/v201411/team_service/get_teams_by_statement.py
deleted file mode 100755
index 4954a652..00000000
--- a/examples/dfp/v201411/team_service/get_teams_by_statement.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets a single team by ID.
-
-To create teams, run create_teams.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: TeamService.getTeamsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-TEAM_ID = 'INSERT_TEAM_ID_HERE'
-
-
-def main(client, team_id):
- # Initialize appropriate service.
- team_service = client.GetService('TeamService', version='v201411')
-
- # Create a filter statement to select a single team by ID.
- values = [{
- 'key': 'teamId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': team_id
- }
- }]
- query = 'WHERE id = :teamId'
- statement = dfp.FilterStatement(query, values)
-
- while True:
- # Get teams by statement.
- response = team_service.getTeamsByStatement(statement.ToStatement())
- if 'results' in response:
- # Display results.
- for team in response['results']:
- print ('Team with id \'%s\' and name \'%s\' was found.'
- % (team['id'], team['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, TEAM_ID)
diff --git a/examples/dfp/v201411/team_service/update_teams.py b/examples/dfp/v201411/team_service/update_teams.py
deleted file mode 100755
index 74d28901..00000000
--- a/examples/dfp/v201411/team_service/update_teams.py
+++ /dev/null
@@ -1,84 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates teams by adding an ad unit to a team.
-
-To determine which teams exist, run get_all_teams.py. To determine which ad
-units exist, run get_all_ad_units.py
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: TeamService.getTeamsByStatement, TeamService.updateTeams
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE'
-TEAM_ID = 'INSERT_TEAM_ID_HERE'
-
-
-def main(client, ad_unit_id, team_id):
- # Initialize appropriate service.
- team_service = client.GetService('TeamService', version='v201411')
-
- # Create a filter statement to select a single team by ID.
- values = [{
- 'key': 'teamId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': team_id
- }
- }]
- query = 'WHERE id = :teamId'
- statement = dfp.FilterStatement(query, values)
-
- # Get teams by statement.
- response = team_service.getTeamsByStatement(statement.ToStatement())
-
- if 'results' in response:
- updated_teams = []
- # Update each local team object by adding the ad unit to it.
- for team in response['results']:
- ad_unit_ids = []
- if 'adUnitIds' in team:
- ad_unit_ids = team['adUnitIds']
- # Don't add the ad unit if the team has all inventory already.
- if not team['hasAllInventory']:
- ad_unit_ids.append(ad_unit_id)
- team['adUnitIds'] = ad_unit_ids
- updated_teams.append(team)
-
- # Update teams on the server.
- teams = team_service.updateTeams(updated_teams)
-
- # Display results.
- for team in teams:
- print ('Team with id \'%s\' and name \'%s\' was updated.'
- % (team['id'], team['name']))
- else:
- print 'No teams found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, AD_UNIT_ID, TEAM_ID)
diff --git a/examples/dfp/v201411/user_service/__init__.py b/examples/dfp/v201411/user_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201411/user_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201411/user_service/create_users.py b/examples/dfp/v201411/user_service/create_users.py
deleted file mode 100755
index e898770f..00000000
--- a/examples/dfp/v201411/user_service/create_users.py
+++ /dev/null
@@ -1,59 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new users.
-
-To determine which users exist, run get_all_users.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-NEW_USER_EMAIL_ADDRESS = 'INSERT_EMAIL_ADDRESS_HERE'
-NEW_USER_NAME = 'INSERT_NAME_HERE'
-
-
-def main(client, email, name):
- # Initialize appropriate service.
- user_service = client.GetService('UserService', version='v201411')
-
- # Create user objects.
- users = [
- {
- 'email': email,
- 'name': name,
- 'preferredLocale': 'en_US'
- }
- ]
- for user in users:
- # Set the system defined ID of the trafficker role.
- # To determine what other roles exist, run get_all_roles.py.
- user['roleId'] = '-7'
-
- # Add users.
- users = user_service.createUsers(users)
-
- # Display results.
- for user in users:
- print ('User with id \'%s\', email \'%s\', and role \'%s\' was created.'
- % (user['id'], user['email'], user['roleName']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, NEW_USER_EMAIL_ADDRESS, NEW_USER_NAME)
diff --git a/examples/dfp/v201411/user_service/deactivate_users.py b/examples/dfp/v201411/user_service/deactivate_users.py
deleted file mode 100755
index 69d3c83c..00000000
--- a/examples/dfp/v201411/user_service/deactivate_users.py
+++ /dev/null
@@ -1,73 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example deactivates a user.
-
-Deactivated users can no longer make requests to the API. The user making the
-request cannot deactivate itself. To determine which users exist, run
-get_all_users.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-USER_ID = 'INSERT_USER_ID_TO_DEACTIVATE_HERE'
-
-
-def main(client, user_id):
- # Initialize appropriate service.
- user_service = client.GetService('UserService', version='v201411')
-
- # Create query.
- values = [{
- 'key': 'userId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': user_id
- }
- }]
- query = 'WHERE id = :userId'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Get users by statement.
- response = user_service.getUsersByStatement(statement.ToStatement())
- users = response['results'] if 'results' in response else []
-
- for user in users:
- print ('User with id \'%s\', email \'%s\', and status \'%s\' will be '
- 'deactivated.'
- % (user['id'], user['email'],
- {'true': 'ACTIVE', 'false': 'INACTIVE'}[user['isActive']]))
- print 'Number of users to be deactivated: %s' % len(users)
-
- # Perform action.
- result = user_service.performUserAction({'xsi_type': 'DeactivateUsers'},
- statement.ToStatement())
-
- # Display results.
- if result and int(result['numChanges']) > 0:
- print 'Number of users deactivated: %s' % result['numChanges']
- else:
- print 'No users were deactivated.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, USER_ID)
diff --git a/examples/dfp/v201411/user_service/get_all_roles.py b/examples/dfp/v201411/user_service/get_all_roles.py
deleted file mode 100755
index 9584e3b3..00000000
--- a/examples/dfp/v201411/user_service/get_all_roles.py
+++ /dev/null
@@ -1,46 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all roles.
-
-This sample can be used to determine which role id is needed when getting and
-creating users."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- user_service = client.GetService('UserService', version='v201411')
-
- # Get all roles.
- roles = user_service.getAllRoles()
-
- # Display results.
- for role in roles:
- print ('Role with id \'%s\' and name \'%s\' was found.'
- % (role['id'], role['name']))
-
- print '\nNumber of results found: %s' % len(roles)
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/user_service/get_all_users.py b/examples/dfp/v201411/user_service/get_all_users.py
deleted file mode 100755
index 0b57ca40..00000000
--- a/examples/dfp/v201411/user_service/get_all_users.py
+++ /dev/null
@@ -1,50 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all users. To create users, run create_users.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- user_service = client.GetService('UserService', version='v201411')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get users by statement.
- while True:
- response = user_service.getUsersByStatement(statement.ToStatement())
- if 'results' in response:
- # Display results.
- for user in response['results']:
- print ('User with id \'%s\', email \'%s\', and role \'%s\' was found.'
- % (user['id'], user['email'], user['roleName']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/user_service/get_current_user.py b/examples/dfp/v201411/user_service/get_current_user.py
deleted file mode 100755
index 1ed7fe5e..00000000
--- a/examples/dfp/v201411/user_service/get_current_user.py
+++ /dev/null
@@ -1,40 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets the current user."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- user_service = client.GetService('UserService', version='v201411')
-
- # Get current user.
- user = user_service.getCurrentUser()
-
- # Display results.
- print ('User with id \'%s\', email \'%s\', and role \'%s\' was found.'
- % (user['id'], user['email'], user['roleName']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/user_service/get_users_by_statement.py b/examples/dfp/v201411/user_service/get_users_by_statement.py
deleted file mode 100755
index f5342b9b..00000000
--- a/examples/dfp/v201411/user_service/get_users_by_statement.py
+++ /dev/null
@@ -1,59 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets a user by its id.
-
-To create users, run create_user.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-USER_ID = 'INSERT_USER_ID_TO_FIND_HERE'
-
-
-def main(client, user_id):
- # Initialize appropriate service.
- user_service = client.GetService('UserService', version='v201411')
-
- # Create query.
- values = [{
- 'key': 'userId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': user_id
- }
- }]
- query = 'WHERE id = :userId'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Get users by statement.
- response = user_service.getUsersByStatement(statement.ToStatement())
- users = response['results'] if 'results' in response else []
-
- for user in users:
- # Display results.
- print ('User with id \'%s\', email \'%s\', and role \'%s\' was found.'
- % (user['id'], user['email'], user['roleName']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, USER_ID)
diff --git a/examples/dfp/v201411/user_service/update_users.py b/examples/dfp/v201411/user_service/update_users.py
deleted file mode 100755
index 22b9c434..00000000
--- a/examples/dfp/v201411/user_service/update_users.py
+++ /dev/null
@@ -1,66 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates a user by adding " Sr." to the end of their name.
-
-To determine which users exist, run get_all_users.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-USER_ID = 'INSERT_USER_ID_TO_UPDATE_HERE'
-
-
-def main(client, user_id):
- # Initialize appropriate service.
- user_service = client.GetService('UserService', version='v201411')
-
- # Create query.
- values = [{
- 'key': 'userId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': user_id
- }
- }]
- query = 'WHERE id = :userId'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Get users by statement.
- response = user_service.getUsersByStatement(statement.ToStatement())
-
- if 'results' in response:
- users = response['results']
- for user in users:
- user['name'] += ' Sr.'
-
- # Update users on server.
- users = user_service.updateUsers(users)
- for user in users:
- print ('User with id \'%s\' and name \'%s\' was updated.'
- % (user['id'], user['name']))
- else:
- print 'No users found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, USER_ID)
diff --git a/examples/dfp/v201411/user_team_association_service/__init__.py b/examples/dfp/v201411/user_team_association_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201411/user_team_association_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201411/user_team_association_service/create_user_team_associations.py b/examples/dfp/v201411/user_team_association_service/create_user_team_associations.py
deleted file mode 100755
index 67a6aedc..00000000
--- a/examples/dfp/v201411/user_team_association_service/create_user_team_associations.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds a user to a team by creating an association between them.
-
-To determine which teams exists, run get_all_teams.py. To determine which
-users exist, run get_all_users.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: UserTeamAssociationService.createUserTeamAssociations
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-TEAM_ID = 'INSERT_TEAM_ID_HERE'
-USER_IDS = ['INSERT_USER_IDS_TO_ASSOCIATE_TO_TEAM_HERE']
-
-
-def main(client, team_id, user_ids):
- # Initialize appropriate service.
- user_team_association_service = client.GetService(
- 'UserTeamAssociationService', version='v201411')
-
- user_team_associations = []
- for user_id in user_ids:
- user_team_associations.append(
- {
- 'teamId': team_id,
- 'userId': user_id
- })
-
- # Create the user team association on the server.
- user_team_associations = (
- user_team_association_service.createUserTeamAssociations(
- user_team_associations))
-
- # Display results.
- if user_team_associations:
- for user_team_association in user_team_associations:
- print ('A user team association between user with ID \'%s\' and team with'
- ' ID \'%s\'was created.' % (user_team_association['userId'],
- user_team_association['teamId']))
- else:
- print 'No user team associations created.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, TEAM_ID, USER_IDS)
diff --git a/examples/dfp/v201411/user_team_association_service/delete_user_team_associations.py b/examples/dfp/v201411/user_team_association_service/delete_user_team_associations.py
deleted file mode 100755
index b5d053db..00000000
--- a/examples/dfp/v201411/user_team_association_service/delete_user_team_associations.py
+++ /dev/null
@@ -1,83 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example removes the user from all its teams.
-
-To determine which users exist, run get_all_users.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: UserTeamAssociationService.performUserTeamAssociationAction
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-USER_ID = 'INSERT_USER_ID_HERE'
-
-
-def main(client, user_id):
- # Initialize appropriate service.
- user_team_association_service = client.GetService(
- 'UserTeamAssociationService', version='v201411')
-
- # Create filter text to select user team associations by the user ID.
- values = [{
- 'key': 'userId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': user_id
- }
- }]
- query = 'WHERE userId = :userId'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Get user team associations by statement.
- response = user_team_association_service.getUserTeamAssociationsByStatement(
- statement.ToStatement())
- user_team_associations = response['results'] if 'results' in response else []
-
- for user_team_association in user_team_associations:
- print ('User team association between user with ID \'%s\' and team with '
- 'ID \'%s\' will be deleted.' % (user_team_association['userId'],
- user_team_association['teamId']))
- print ('Number of teams that the user will be removed from: %s' %
- len(user_team_associations))
-
- # Perform action.
- result = user_team_association_service.performUserTeamAssociationAction(
- {'xsi_type': 'DeleteUserTeamAssociations'},
- {'query': query, 'values': values})
-
- # Display results.
- if result and int(result['numChanges']) > 0:
- print ('Number of teams that the user was removed from: %s'
- % result['numChanges'])
- else:
- print 'No user team associations were deleted.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, USER_ID)
diff --git a/examples/dfp/v201411/user_team_association_service/get_all_user_team_associations.py b/examples/dfp/v201411/user_team_association_service/get_all_user_team_associations.py
deleted file mode 100755
index ecab0241..00000000
--- a/examples/dfp/v201411/user_team_association_service/get_all_user_team_associations.py
+++ /dev/null
@@ -1,64 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all user team associations.
-
-To create user team associations, run create_user_team_assocations.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: UserTeamAssociationService.getUserTeamAssociationsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- user_team_association_service = client.GetService(
- 'UserTeamAssociationService', version='v201411')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get user team associations by statement.
- while True:
- response = user_team_association_service.getUserTeamAssociationsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for user_team_association in response['results']:
- print ('User team association between user with ID \'%s\' and team with'
- ' ID \'%s\' was found.' % (user_team_association['userId'],
- user_team_association['teamId']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/user_team_association_service/get_user_team_associations_for_user.py b/examples/dfp/v201411/user_team_association_service/get_user_team_associations_for_user.py
deleted file mode 100755
index 11fd535a..00000000
--- a/examples/dfp/v201411/user_team_association_service/get_user_team_associations_for_user.py
+++ /dev/null
@@ -1,75 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all user team associations for a single user.
-
-To determine which users exist, run get_all_users.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: UserTeamAssociationService.getUserTeamAssociation
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-USER_ID = 'INSERT_USER_ID_HERE'
-
-
-def main(client, user_id):
- # Initialize appropriate service.
- user_team_association_service = client.GetService(
- 'UserTeamAssociationService', version='v201411')
-
- # Create query.
- values = [{
- 'key': 'userId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': user_id
- }
- }]
- query = 'WHERE userId = :userId'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Get user team associations by statement.
- while True:
- response = user_team_association_service.getUserTeamAssociationsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for user_team_association in response['results']:
- print ('User team association between user with ID \'%s\' and team with'
- ' ID \'%s\' was found.' % (user_team_association['userId'],
- user_team_association['teamId']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, USER_ID)
diff --git a/examples/dfp/v201411/user_team_association_service/update_user_team_associations.py b/examples/dfp/v201411/user_team_association_service/update_user_team_associations.py
deleted file mode 100755
index 6350425e..00000000
--- a/examples/dfp/v201411/user_team_association_service/update_user_team_associations.py
+++ /dev/null
@@ -1,89 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates user team associations.
-
-It updates a user team association by setting the overridden access type to read
-only for all teams that the user belongs to. To determine which users exists,
-run get_all_users.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: UserTeamAssociationService.getUserTeamAssociationsByStatement
-Tags: UserTeamAssociationService.updateUserTeamAssociations
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-USER_ID = 'INSERT_USER_ID_TO_UPDATE_HERE'
-
-
-def main(client, user_id):
- # Initialize appropriate service.
- user_team_association_service = client.GetService(
- 'UserTeamAssociationService', version='v201411')
-
- # Create filter text to select user team associations by the user ID.
- values = [{
- 'key': 'userId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': user_id
- }
- }]
- query = 'WHERE userId = :userId'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Get user team associations by statement.
- response = user_team_association_service.getUserTeamAssociationsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- updated_user_team_associations = []
- # Update each local user team association to read only access.
- for user_team_association in response['results']:
- user_team_association['overriddenTeamAccessType'] = 'READ_ONLY'
- updated_user_team_associations.append(user_team_association)
-
- # Update user team associations on the server.
- user_team_associations = (
- user_team_association_service.updateUserTeamAssociations(
- updated_user_team_associations))
-
- # Display results.
- if user_team_associations:
- for user_team_association in user_team_associations:
- print ('User team association between user with ID \'%s\' and team with'
- ' ID \'%s\' was updated.' % (user_team_association['userId'],
- user_team_association['teamId']))
- else:
- print 'No user team associations were updated.'
- else:
- print 'No user team associations found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, USER_ID)
diff --git a/examples/dfp/v201411/workflow_request_service/__init__.py b/examples/dfp/v201411/workflow_request_service/__init__.py
deleted file mode 100755
index 02adb9a5..00000000
--- a/examples/dfp/v201411/workflow_request_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201411/workflow_request_service/approve_workflow_approval_requests.py b/examples/dfp/v201411/workflow_request_service/approve_workflow_approval_requests.py
deleted file mode 100755
index 24cc3520..00000000
--- a/examples/dfp/v201411/workflow_request_service/approve_workflow_approval_requests.py
+++ /dev/null
@@ -1,99 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example approves all workflow approval requests belonging to a proposal.
-
-To determine which workflow approval requests exist, run
-get_all_workflow_approval_requests.py.
-
-Tags: WorkflowRequestService.getWorkflowRequestsByStatement
-Tags: WorkflowRequestService.performWorkflowRequestAction
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE'
-
-
-def main(client, proposal_id):
- # Initialize appropriate service.
- workflow_request_service = client.GetService('WorkflowRequestService',
- version='v201411')
-
- # Create query.
- values = [
- {
- 'key': 'entityId',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': proposal_id
- }
- },
- {
- 'key': 'entityType',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'PROPOSAL'
- }
- },
- {
- 'key': 'type',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'WORKFLOW_APPROVAL_REQUEST'
- }
- }
- ]
- query = ('WHERE entityId = :entityId and entityType = :entityType '
- 'and type = :type')
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
- workflow_approval_requests_approved = 0
-
- # Get workflow approval requests by statement.
- while True:
- response = workflow_request_service.getWorkflowRequestsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for workflow_approval_request in response['results']:
- print ('Workflow approval request with id \'%s\' will be'
- ' approved.' % workflow_approval_request['id'])
- # Perform action.
- result = workflow_request_service.performWorkflowRequestAction(
- {'xsi_type': 'ApproveWorkflowApprovalRequests'},
- statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- workflow_approval_requests_approved += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Display results.
- if workflow_approval_requests_approved > 0:
- print ('\nNumber of workflow approval requests approved: %s' %
- workflow_approval_requests_approved)
- else:
- print '\nNo workflow approval requests were approved.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PROPOSAL_ID)
diff --git a/examples/dfp/v201411/workflow_request_service/get_workflow_approval_requests_by_statement.py b/examples/dfp/v201411/workflow_request_service/get_workflow_approval_requests_by_statement.py
deleted file mode 100755
index 6a36618a..00000000
--- a/examples/dfp/v201411/workflow_request_service/get_workflow_approval_requests_by_statement.py
+++ /dev/null
@@ -1,69 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets workflow approval requests.
-
-Workflow approval requests must be approved or rejected for a workflow to
-finish.
-
-Tags: WorkflowRequestService.getWorkflowRequestsByStatement
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- workflow_request_service = client.GetService('WorkflowRequestService',
- version='v201411')
-
- # Create statement object to select all workflow approval requests.
- values = [{
- 'key': 'type',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'WORKFLOW_APPROVAL_REQUEST'
- }
- }]
- query = 'WHERE type = :type'
-
- statement = dfp.FilterStatement(query, values)
-
- # Get proposals by statement.
- while True:
- response = workflow_request_service.getWorkflowRequestsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for workflow_request in response['results']:
- print ('Workflow approval request with id \'%s\' for %s with id \'%s\' '
- 'was found.' % (workflow_request['id'],
- workflow_request['entityType'],
- workflow_request['entityId']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/workflow_request_service/get_workflow_external_condition_requests_by_statement.py b/examples/dfp/v201411/workflow_request_service/get_workflow_external_condition_requests_by_statement.py
deleted file mode 100755
index 4378f35f..00000000
--- a/examples/dfp/v201411/workflow_request_service/get_workflow_external_condition_requests_by_statement.py
+++ /dev/null
@@ -1,69 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets workflow external condition requests.
-
-Workflow external condition requests must be triggered or skipped for a workflow
-to finish.
-
-Tags: WorkflowRequestService.getWorkflowRequestsByStatement
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- workflow_request_service = client.GetService('WorkflowRequestService',
- version='v201411')
-
- # Create statement object to select a single proposal by an ID.
- values = [{
- 'key': 'type',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'WORKFLOW_EXTERNAL_CONDITION_REQUEST'
- }
- }]
- query = 'WHERE type = :type'
-
- statement = dfp.FilterStatement(query, values)
-
- # Get proposals by statement.
- while True:
- response = workflow_request_service.getWorkflowRequestsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for workflow_request in response['results']:
- print ('Workflow external condition request with id \'%s\' for %s '
- 'with id \'%s\' was found.' % (workflow_request['id'],
- workflow_request['entityType'],
- workflow_request['entityId']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201411/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/dfp/v201411/workflow_request_service/trigger_workflow_external_condition_requests.py
deleted file mode 100755
index 3a61978f..00000000
--- a/examples/dfp/v201411/workflow_request_service/trigger_workflow_external_condition_requests.py
+++ /dev/null
@@ -1,103 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2014 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This triggers all workflow external condition requests for a proposal.
-
-Workflow external condition requests must be triggered or skipped for a workflow
-to finish. To determine which proposals exist, run get_all_proposals.py.
-
-Tags: WorkflowRequestService.getWorkflowRequestsByStatement
-Tags: WorkflowRequestService.performWorkflowRequestAction
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE'
-
-
-def main(client, proposal_id):
- # Initialize appropriate service.
- workflow_request_service = client.GetService('WorkflowRequestService',
- version='v201411')
-
- # Create query.
- values = [
- {
- 'key': 'entityId',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': proposal_id
- }
- },
- {
- 'key': 'entityType',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'PROPOSAL'
- }
- },
- {
- 'key': 'type',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'WORKFLOW_EXTERNAL_CONDITION_REQUEST'
- }
- }
- ]
- query = ('WHERE entityId = :entityId and entityType = :entityType '
- 'and type = :type')
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
- workflow_external_condition_requests_triggered = 0
-
- # Get workflow external condition requests by statement.
- while True:
- response = workflow_request_service.getWorkflowRequestsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for workflow_request in response['results']:
- print ('Workflow external condition request with id \'%s\' for %s '
- 'with id \'%s\' will be triggered.' %
- (workflow_request['id'],
- workflow_request['entityType'],
- workflow_request['entityId']))
- # Perform action.
- result = workflow_request_service.performWorkflowRequestAction(
- {'xsi_type': 'TriggerWorkflowExternalConditionRequests'},
- statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- workflow_external_condition_requests_triggered += int(
- result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Display results.
- if workflow_external_condition_requests_triggered > 0:
- print ('\nNumber of workflow external condition requests triggered: %s' %
- workflow_external_condition_requests_triggered)
- else:
- print '\nNo workflow external condition requests were triggered.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PROPOSAL_ID)
diff --git a/examples/dfp/v201502/activity_group_service/__init__.py b/examples/dfp/v201502/activity_group_service/__init__.py
deleted file mode 100755
index a426ca48..00000000
--- a/examples/dfp/v201502/activity_group_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201502/activity_group_service/create_activity_groups.py b/examples/dfp/v201502/activity_group_service/create_activity_groups.py
deleted file mode 100755
index fb039e32..00000000
--- a/examples/dfp/v201502/activity_group_service/create_activity_groups.py
+++ /dev/null
@@ -1,74 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new activity groups.
-
-To determine which activity groups exist, run get_all_activity_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ActivityGroupService.createActivityGroups
-"""
-
-__author__ = ('Vincent Tsao',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the advertiser company this activity group is associated with.
-ADVERTISER_COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
-
-
-def main(client, advertiser_company_id):
- # Initialize appropriate service.
- activity_group_service = client.GetService('ActivityGroupService',
- version='v201502')
-
- # Create a short-term activity group.
- short_term_activity_group = {
- 'name': 'Short-term activity group #%s' % uuid.uuid4(),
- 'companyIds': [advertiser_company_id],
- 'clicksLookback': '1',
- 'impressionsLookback': '1'
- }
-
- # Create a long-term activity group.
- long_term_activity_group = {
- 'name': 'Long-term activity group #%s' % uuid.uuid4(),
- 'companyIds': [advertiser_company_id],
- 'clicksLookback': '30',
- 'impressionsLookback': '30'
- }
-
- # Create the activity groups on the server.
- activity_groups = activity_group_service.createActivityGroups([
- short_term_activity_group, long_term_activity_group])
-
- # Display results.
- for activity_group in activity_groups:
- print ('Activity group with ID \'%s\' and name \'%s\' was created.'
- % (activity_group['id'], activity_group['name']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ADVERTISER_COMPANY_ID)
diff --git a/examples/dfp/v201502/activity_group_service/get_active_activity_groups.py b/examples/dfp/v201502/activity_group_service/get_active_activity_groups.py
deleted file mode 100755
index eb8d380e..00000000
--- a/examples/dfp/v201502/activity_group_service/get_active_activity_groups.py
+++ /dev/null
@@ -1,72 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all active activity groups.
-
-To create activity groups, run create_activity_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ActivityGroupService.getActivityGroupsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- activity_group_service = client.GetService('ActivityGroupService',
- version='v201502')
-
- # Create statement object to only select active activity groups.
- values = [{
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ACTIVE'
- }
- }]
- query = 'WHERE status = :status'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Get activity groups by statement.
- while True:
- response = activity_group_service.getActivityGroupsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for activity_group in response['results']:
- print ('Activity group with ID \'%s\' and name \'%s\' was found.'
- % (activity_group['id'], activity_group['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/activity_group_service/get_all_activity_groups.py b/examples/dfp/v201502/activity_group_service/get_all_activity_groups.py
deleted file mode 100755
index 1f68ec6f..00000000
--- a/examples/dfp/v201502/activity_group_service/get_all_activity_groups.py
+++ /dev/null
@@ -1,63 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all activity groups.
-
-To create activity groups, run create_activity_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ActivityGroupService.getActivityGroupsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- activity_group_service = client.GetService('ActivityGroupService',
- version='v201502')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get activity groups by statement.
- while True:
- response = activity_group_service.getActivityGroupsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for activity_group in response['results']:
- print ('Activity group with ID \'%s\' and name \'%s\' was found.'
- % (activity_group['id'], activity_group['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/activity_group_service/update_activity_groups.py b/examples/dfp/v201502/activity_group_service/update_activity_groups.py
deleted file mode 100755
index 1bfd692c..00000000
--- a/examples/dfp/v201502/activity_group_service/update_activity_groups.py
+++ /dev/null
@@ -1,80 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates activity groups.
-
-To determine which activity groups exist, run get_all_activity_groups.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ActivityGroupService.getActivityGroup
-Tags: ActivityGroupService.updateActivityGroups
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the activity group and the company to update it with.
-ACTIVITY_GROUP_ID = 'INSERT_ACTIVITY_GROUP_ID_HERE'
-ADVERTISER_COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
-
-
-def main(client, activity_group_id, advertiser_company_id):
- # Initialize appropriate service.
- activity_group_service = client.GetService('ActivityGroupService',
- version='v201502')
-
- # Create statement object to select a single activity groups by ID.
- values = [{
- 'key': 'activityGroupId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': activity_group_id
- }
- }]
- query = 'WHERE id = :activityGroupId'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get activity groups by statement.
- response = activity_group_service.getActivityGroupsByStatement(
- statement.ToStatement())
- if 'results' in response:
- updated_activity_groups = []
- for activity_group in response['results']:
- activity_group['companyIds'].append(advertiser_company_id)
- updated_activity_groups.append(activity_group)
- # Update the activity groups on the server.
- activity_groups = activity_group_service.updateActivityGroups(
- updated_activity_groups)
-
- for activity_group in activity_groups:
- print (('Activity group with ID \'%s\' and name \'%s\' was updated.')
- % (activity_group['id'], activity_group['name']))
- else:
- print 'No activity groups found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ACTIVITY_GROUP_ID, ADVERTISER_COMPANY_ID)
diff --git a/examples/dfp/v201502/activity_service/__init__.py b/examples/dfp/v201502/activity_service/__init__.py
deleted file mode 100755
index a426ca48..00000000
--- a/examples/dfp/v201502/activity_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201502/activity_service/create_activities.py b/examples/dfp/v201502/activity_service/create_activities.py
deleted file mode 100755
index 53504cc3..00000000
--- a/examples/dfp/v201502/activity_service/create_activities.py
+++ /dev/null
@@ -1,71 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new activities.
-
-To determine which activities groups exist, run get_all_activities.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ActivityService.createActivities
-"""
-
-__author__ = ('Vincent Tsao',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the activity group this activity is associated with.
-ACTIVITY_GROUP_ID = 'INSERT_ACTIVITY_GROUP_ID_HERE'
-
-
-def main(client, activity_group_id):
- # Initialize appropriate service.
- activity_service = client.GetService('ActivityService', version='v201502')
-
- # Create a daily visits activity.
- daily_visits_activity = {
- 'name': 'Activity #%s' % uuid.uuid4(),
- 'activityGroupId': activity_group_id,
- 'type': 'DAILY_VISITS'
- }
-
- # Create a custom activity.
- custom_activity = {
- 'name': 'Activity #%s' % uuid.uuid4(),
- 'activityGroupId': activity_group_id,
- 'type': 'CUSTOM'
- }
-
- # Create the activities on the server.
- activities = activity_service.createActivities([
- daily_visits_activity, custom_activity])
-
- # Display results.
- for activity in activities:
- print ('An activity with ID \'%s\', name \'%s\', and type \'%s\' was '
- 'created.' % (activity['id'], activity['name'], activity['type']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ACTIVITY_GROUP_ID)
diff --git a/examples/dfp/v201502/activity_service/get_active_activities.py b/examples/dfp/v201502/activity_service/get_active_activities.py
deleted file mode 100755
index 79dd965b..00000000
--- a/examples/dfp/v201502/activity_service/get_active_activities.py
+++ /dev/null
@@ -1,69 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all active activities.
-
-To create activities, run create_activities.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ActivityService.getActivitiesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- activity_service = client.GetService('ActivityService', version='v201502')
-
- # Create statement object to only select active activities.
- values = [{
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ACTIVE'
- }
- }]
- query = 'WHERE status = :status'
- statement = dfp.FilterStatement(query, values)
-
- # Get activities by statement.
- while True:
- response = activity_service.getActivitiesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for activity in response['results']:
- print ('Activity with ID \'%s\', name \'%s\', and type \'%s\' was '
- 'found.' % (activity['id'], activity['name'], activity['type']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/activity_service/get_all_activities.py b/examples/dfp/v201502/activity_service/get_all_activities.py
deleted file mode 100755
index 288826a5..00000000
--- a/examples/dfp/v201502/activity_service/get_all_activities.py
+++ /dev/null
@@ -1,61 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all activities.
-
-To create activities, run create_activities.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ActivityService.getActivitiesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- activity_service = client.GetService('ActivityService', version='v201502')
-
- # Create statement object to select only all activities.
- statement = dfp.FilterStatement()
-
- # Get activities by statement.
- while True:
- response = activity_service.getActivitiesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for activity in response['results']:
- print ('Activity with ID \'%s\', name \'%s\', and type \'%s\' was '
- 'found.' % (activity['id'], activity['name'], activity['type']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/activity_service/update_activities.py b/examples/dfp/v201502/activity_service/update_activities.py
deleted file mode 100755
index bcfe6a08..00000000
--- a/examples/dfp/v201502/activity_service/update_activities.py
+++ /dev/null
@@ -1,76 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates activities.
-
-To determine which activities exist, run get_all_activities.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ActivityService.updateActivities
- ActivityService.getActivitiesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the activity to update.
-ACTIVITY_ID = 'INSERT_ACTIVITY_ID_HERE'
-
-
-def main(client, activity_id):
- # Initialize appropriate service.
- activity_service = client.GetService('ActivityService', version='v201502')
-
- # Create statement object to select one activity by ID to update.
- values = [{
- 'key': 'activityId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': activity_id
- }
- }]
- query = 'WHERE id = :activityId'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get activities by statement.
- response = activity_service.getActivitiesByStatement(
- statement.ToStatement())
- if 'results' in response:
- updated_activities = []
- for activity in response['results']:
- # Update the expected URL.
- activity['expectedURL'] = 'https://google.com'
- updated_activities.append(activity)
- # Update the activity on the server.
- activities = activity_service.updateActivities(updated_activities)
-
- for updated_activity in activities:
- print (('Activity with ID \'%s\' and name \'%s\' was updated.')
- % (updated_activity['id'], updated_activity['name']))
- else:
- print 'No activities found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ACTIVITY_ID)
diff --git a/examples/dfp/v201502/audience_segment_service/__init__.py b/examples/dfp/v201502/audience_segment_service/__init__.py
deleted file mode 100755
index a426ca48..00000000
--- a/examples/dfp/v201502/audience_segment_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201502/audience_segment_service/create_audience_segments.py b/examples/dfp/v201502/audience_segment_service/create_audience_segments.py
deleted file mode 100755
index 1713f998..00000000
--- a/examples/dfp/v201502/audience_segment_service/create_audience_segments.py
+++ /dev/null
@@ -1,100 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates a new rule based first party audience segment."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the IDs of the custom criteria to be used in the segment rule.
-CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'
-CUSTOM_TARGETING_VALUE_ID = 'INSERT_CUSTOM_TARGETING_VALUE_ID_HERE'
-
-def main(client, custom_targeting_key_id, custom_targeting_value_id):
- # Initialize client object.
- client = dfp.DfpClient.LoadFromStorage()
-
- # Initialize appropriate services.
- audience_segment_service = client.GetService(
- 'AudienceSegmentService', version='v201502')
- network_service = client.GetService('NetworkService', version='v201502')
-
- # Get the root ad unit ID used to target the entire network.
- root_ad_unit_id = (
- network_service.getCurrentNetwork()['effectiveRootAdUnitId'])
-
- # Create inventory targeting (pointed at root ad unit i.e. the whole network)
- inventory_targeting = {
- 'targetedAdUnits': [
- {'adUnitId': root_ad_unit_id}
- ]
- }
-
- # Create custom criteria.
- custom_criteria = [
- {
- 'xsi_type': 'CustomCriteria',
- 'keyId': CUSTOM_TARGETING_KEY_ID,
- 'valueIds': [CUSTOM_TARGETING_VALUE_ID],
- 'operator': 'IS'
- }
- ]
-
- # Create the custom criteria set.
- top_custom_criteria_set = {
- 'logicalOperator': 'AND',
- 'children': custom_criteria
- }
-
- # Create the audience segment rule.
- rule = {
- 'inventoryRule': inventory_targeting,
- 'customCriteriaRule': top_custom_criteria_set
- }
-
- # Create an audience segment.
- audience_segment = [
- {
- 'xsi_type': 'RuleBasedFirstPartyAudienceSegment',
- 'name': ('Sports enthusiasts audience segment %s' %
- uuid.uuid4()),
- 'description': 'Sports enthusiasts between the ages of 20 and 30',
- 'pageViews': '6',
- 'recencyDays': '6',
- 'membershipExpirationDays': '88',
- 'rule': rule
- }
- ]
-
- audience_segments = (
- audience_segment_service.createAudienceSegments(audience_segment))
-
- for created_audience_segment in audience_segments:
- print ('An audience segment with ID \'%s\', name \'%s\', and type \'%s\' '
- 'was created.' % (created_audience_segment['id'],
- created_audience_segment['name'],
- created_audience_segment['type']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CUSTOM_TARGETING_KEY_ID, CUSTOM_TARGETING_VALUE_ID)
diff --git a/examples/dfp/v201502/audience_segment_service/get_all_audience_segments.py b/examples/dfp/v201502/audience_segment_service/get_all_audience_segments.py
deleted file mode 100755
index 63a910b0..00000000
--- a/examples/dfp/v201502/audience_segment_service/get_all_audience_segments.py
+++ /dev/null
@@ -1,60 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all audience segments.
-
-To create audience segments, run create_audience_segments.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize client object.
- client = dfp.DfpClient.LoadFromStorage()
-
- # Initialize appropriate service.
- audience_segment_service = client.GetService(
- 'AudienceSegmentService', version='v201502')
-
- # Create statement object to select all audience segments.
- statement = dfp.FilterStatement()
-
- # Get audience segments by statement.
- while True:
- response = audience_segment_service.getAudienceSegmentsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for segment in response['results']:
- print ('Audience segment with id \'%s\' and name '
- '\'%s\' of size %s was found.' %
- (segment['id'], segment['name'], segment['size']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/audience_segment_service/get_first_party_audience_segments.py b/examples/dfp/v201502/audience_segment_service/get_first_party_audience_segments.py
deleted file mode 100755
index 97b0ae67..00000000
--- a/examples/dfp/v201502/audience_segment_service/get_first_party_audience_segments.py
+++ /dev/null
@@ -1,69 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all first party audience segments.
-
-To create first party audience segments, run create_audience_segments.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize client object.
- client = dfp.DfpClient.LoadFromStorage()
-
- # Initialize appropriate service.
- audience_segment_service = client.GetService(
- 'AudienceSegmentService', version='v201502')
-
- # Create statement object to only select first party audience segments.
- values = [{
- 'key': 'type',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'FIRST_PARTY'
- }
- }]
- query = 'WHERE Type = :type'
- statement = dfp.FilterStatement(query, values)
-
- # Get audience segments by statement.
- while True:
- response = audience_segment_service.getAudienceSegmentsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- segments = response['results']
- for segment in segments:
- print ('Audience segment with id \'%s\' and name \'%s\' of size '
- '%s was found. ' %
- (segment['id'], segment['name'], segment['size']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201502/audience_segment_service/populate_first_party_audience_segments.py
deleted file mode 100755
index 8f8bfe6c..00000000
--- a/examples/dfp/v201502/audience_segment_service/populate_first_party_audience_segments.py
+++ /dev/null
@@ -1,84 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example populates a specific first party audience segment.
-
-To determine which first party audience segments exist, run
-get_first_party_audience_segments.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-AUDIENCE_SEGMENT_ID = 'INSERT_AUDIENCE_SEGMENT_ID_HERE'
-
-
-def main(client, audience_segment_id):
- # Initialize client object.
- client = dfp.DfpClient.LoadFromStorage()
-
- # Initialize appropriate service.
- audience_segment_service = client.GetService(
- 'AudienceSegmentService', version='v201502')
-
- # Create statement object to get the specified first party audience segment.
- values = (
- [{'key': 'type',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'FIRST_PARTY'
- }
- },
- {'key': 'audience_segment_id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': AUDIENCE_SEGMENT_ID
- }
- }])
- query = 'WHERE Type = :type AND Id = :audience_segment_id'
- statement = dfp.FilterStatement(query, values, 1)
-
- response = audience_segment_service.getAudienceSegmentsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- segments = response['results']
-
- for segment in segments:
- print ('Audience segment with id \'%s\' and name \'%s\' will be populated.'
- % (segment['id'], segment['name']))
-
- action = {
- 'xsi_type': 'PopulateAudienceSegments'
- }
-
- populated_audience_segments = (
- audience_segment_service.performAudienceSegmentAction(
- action, statement.ToStatement()))
-
- print ('%s audience segment populated' %
- populated_audience_segments['numChanges'])
- else:
- print 'No Results Found'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, AUDIENCE_SEGMENT_ID)
diff --git a/examples/dfp/v201502/audience_segment_service/update_audience_segments.py b/examples/dfp/v201502/audience_segment_service/update_audience_segments.py
deleted file mode 100755
index 39a5e03e..00000000
--- a/examples/dfp/v201502/audience_segment_service/update_audience_segments.py
+++ /dev/null
@@ -1,82 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates rule based first party audience segments.
-
-To determine which audience segments exist, run get_all_audience_segments.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-AUDIENCE_SEGMENT_ID = 'INSERT_AUDIENCE_SEGMENT_ID_HERE'
-
-
-def main(client, audience_segment_id):
- # Initialize client object.
- client = dfp.DfpClient.LoadFromStorage()
-
- # Initialize appropriate service.
- audience_segment_service = client.GetService(
- 'AudienceSegmentService', version='v201502')
-
- # Create statement object to get the specified first party audience segment.
- values = (
- [{'key': 'type',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'FIRST_PARTY'
- }
- },
- {'key': 'audience_segment_id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': AUDIENCE_SEGMENT_ID
- }
- }])
- query = 'WHERE Type = :type AND Id = :audience_segment_id'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get audience segments by statement.
- response = audience_segment_service.getAudienceSegmentsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- updated_audience_segments = []
- for audience_segment in response['results']:
- print ('Audience segment with id \'%s\' and name \'%s\' will be updated.'
- % (audience_segment['id'], audience_segment['name']))
-
- audience_segment['membershipExpirationDays'] = '180'
- updated_audience_segments.append(audience_segment)
-
- audience_segments = audience_segment_service.updateAudienceSegments(
- updated_audience_segments)
-
- for audience_segment in audience_segments:
- print ('Audience segment with id \'%s\' and name \'%s\' was updated' %
- (audience_segment['id'], audience_segment['name']))
- else:
- print 'No audience segment found to update.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, AUDIENCE_SEGMENT_ID)
diff --git a/examples/dfp/v201502/base_rate_service/__init__.py b/examples/dfp/v201502/base_rate_service/__init__.py
deleted file mode 100755
index a426ca48..00000000
--- a/examples/dfp/v201502/base_rate_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201502/base_rate_service/create_product_base_rates.py b/examples/dfp/v201502/base_rate_service/create_product_base_rates.py
deleted file mode 100755
index f6e45ecf..00000000
--- a/examples/dfp/v201502/base_rate_service/create_product_base_rates.py
+++ /dev/null
@@ -1,65 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates a product base rate.
-
-To determine which base rates exist, run get_all_base_rates.py.
-
-Tags: BaseRateService.createBaseRates
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE'
-RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE'
-
-
-def main(client, product_id, rate_card_id):
- # Initialize appropriate service.
- base_rate_service = client.GetService(
- 'BaseRateService', version='v201502')
-
- # Create a product base rate.
- product_base_rate = {
- 'xsi_type': 'ProductBaseRate',
- 'rateCardId': rate_card_id,
- 'productId': product_id,
- # Set the rate to be $2.
- 'rate': {
- 'currencyCode': 'USD',
- 'microAmount': 2000000
- }
- }
-
- # Create base rates on the server.
- base_rates = base_rate_service.createBaseRates(
- [product_base_rate])
-
- if base_rates:
- for base_rate in base_rates:
- print ('A product base rate with ID \'%s\' and rate \'%.2f\' %s was '
- 'created.' % (base_rate['id'],
- base_rate['rate']['microAmount'],
- base_rate['rate']['currencyCode']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PRODUCT_ID, RATE_CARD_ID)
diff --git a/examples/dfp/v201502/base_rate_service/create_product_template_base_rates.py b/examples/dfp/v201502/base_rate_service/create_product_template_base_rates.py
deleted file mode 100755
index aca22d0b..00000000
--- a/examples/dfp/v201502/base_rate_service/create_product_template_base_rates.py
+++ /dev/null
@@ -1,65 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates a product template base rate.
-
-To determine which base rates exist, run get_all_base_rates.py.
-
-Tags: BaseRateService.createBaseRates
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE'
-RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE'
-
-
-def main(client, product_template_id, rate_card_id):
- # Initialize appropriate service.
- base_rate_service = client.GetService(
- 'BaseRateService', version='v201502')
-
- # Create a product template base rate.
- product_template_base_rate = {
- 'xsi_type': 'ProductTemplateBaseRate',
- 'rateCardId': rate_card_id,
- 'productTemplateId': product_template_id,
- # Set the rate to be $2.
- 'rate': {
- 'currencyCode': 'USD',
- 'microAmount': 2000000
- }
- }
-
- # Create base rates on the server.
- base_rates = base_rate_service.createBaseRates(
- [product_template_base_rate])
-
- if base_rates:
- for base_rate in base_rates:
- print ('A product template base rate with ID \'%s\' and rate \'%.2f\' %s'
- ' was created.' % (base_rate['id'],
- base_rate['rate']['microAmount'],
- base_rate['rate']['currencyCode']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PRODUCT_TEMPLATE_ID, RATE_CARD_ID)
diff --git a/examples/dfp/v201502/base_rate_service/get_all_base_rates.py b/examples/dfp/v201502/base_rate_service/get_all_base_rates.py
deleted file mode 100755
index 5ef40bbe..00000000
--- a/examples/dfp/v201502/base_rate_service/get_all_base_rates.py
+++ /dev/null
@@ -1,61 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all base rates.
-
-To create product base rates, run create_product_base_rates.py
-To create product template base rates, run
-create_product_template_base_rates.py.
-
-Tags: BaseRateService.getBaseRatesByStatement
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- base_rate_service = client.GetService('BaseRateService', version='v201502')
-
- # Create a filter statement.
- statement = dfp.FilterStatement('ORDER BY id ASC')
-
- # Get base rates by statement.
- while True:
- response = base_rate_service.getBaseRatesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for base_rate in response['results']:
- print ('Base rate with ID \'%s\' and type \'%s\' belonging to '
- 'rate card ID \'%s\' was found.' % (
- base_rate['id'],
- dfp.DfpClassType(base_rate),
- base_rate['rateCardId']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/base_rate_service/get_base_rates_for_a_rate_card.py b/examples/dfp/v201502/base_rate_service/get_base_rates_for_a_rate_card.py
deleted file mode 100755
index 59792818..00000000
--- a/examples/dfp/v201502/base_rate_service/get_base_rates_for_a_rate_card.py
+++ /dev/null
@@ -1,71 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all base rates.
-
-To create product base rates, run create_product_base_rates.py
-To create product template base rates, run
-create_product_template_base_rates.py.
-
-Tags: BaseRateService.getBaseRatesByStatement
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE'
-
-
-def main(client, rate_card_id):
- # Initialize appropriate service.
- base_rate_service = client.GetService('BaseRateService', version='v201502')
-
- # Create a filter statement for base rates for a single rate card.
- values = [{
- 'key': 'rateCardId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': rate_card_id
- }
- }]
- query = 'where rateCardId = :rateCardId ORDER BY id ASC'
- statement = dfp.FilterStatement(query, values)
-
- # Get base rates by statement.
- while True:
- response = base_rate_service.getBaseRatesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for base_rate in response['results']:
- print ('Base rate with ID \'%s\' and type \'%s\' belonging to '
- 'rate card ID \'%s\' was found.' % (
- base_rate['id'],
- dfp.DfpClassType(base_rate),
- base_rate['rateCardId']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, RATE_CARD_ID)
diff --git a/examples/dfp/v201502/base_rate_service/update_base_rates.py b/examples/dfp/v201502/base_rate_service/update_base_rates.py
deleted file mode 100755
index d93d18ca..00000000
--- a/examples/dfp/v201502/base_rate_service/update_base_rates.py
+++ /dev/null
@@ -1,84 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates a base rate's value.
-
-To determine which base rates exist, run get_all_base_rates.py.
-
-Tags: BaseRateService.getBaseRatesByStatement
-Tags: BaseRateService.updateBaseRates
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-BASE_RATE_ID = 'INSERT_BASE_RATE_ID_HERE'
-
-
-def main(client, base_rate_id):
- # Initialize appropriate service.
- base_rate_service = client.GetService('BaseRateService', version='v201502')
-
- # Create a filter statement for base rates for a single rate card.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': base_rate_id
- }
- }]
- query = 'where id = :id ORDER BY id ASC'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get single base rate by statement.
- response = base_rate_service.getBaseRatesByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- # Update each local base rate object by changing its value to $3 USD.
- new_rate = {
- 'currencyCode': 'USD',
- 'microAmount': 3000000
- }
-
- updated_base_rates = []
- for base_rate in response['results']:
- base_rate['rate'] = new_rate
- updated_base_rates.append(base_rate)
-
- # Update base rates remotely.
- base_rates = base_rate_service.updateBaseRates(updated_base_rates)
-
- # Display results.
- if base_rates:
- for base_rate in base_rates:
- print ('Base rate with ID \'%s\' and type \'%s\' belonging to '
- 'rate card ID \'%s\' was updated.' % (
- base_rate['id'],
- dfp.DfpClassType(base_rate),
- base_rate['rateCardId']))
- else:
- print 'No base rates were updated.'
- else:
- print 'No base rates found to update.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, BASE_RATE_ID)
diff --git a/examples/dfp/v201502/company_service/__init__.py b/examples/dfp/v201502/company_service/__init__.py
deleted file mode 100755
index a426ca48..00000000
--- a/examples/dfp/v201502/company_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201502/company_service/create_companies.py b/examples/dfp/v201502/company_service/create_companies.py
deleted file mode 100755
index a59a1b69..00000000
--- a/examples/dfp/v201502/company_service/create_companies.py
+++ /dev/null
@@ -1,65 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new companies.
-
-To determine which companies exist, run get_all_companies.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CompanyService.createCompanies
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- company_service = client.GetService('CompanyService', version='v201502')
-
- # Create company objects.
- companies = [
- {
- 'name': 'Advertiser #%s' % uuid.uuid4(),
- 'type': 'ADVERTISER'
- },
- {
- 'name': 'Agency #%s' % uuid.uuid4(),
- 'type': 'AGENCY'
- }
- ]
-
- # Add companies.
- companies = company_service.createCompanies(companies)
-
- # Display results.
- for company in companies:
- print ('Company with ID \'%s\', name \'%s\', and type \'%s\' was created.'
- % (company['id'], company['name'], company['type']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/company_service/get_advertisers.py b/examples/dfp/v201502/company_service/get_advertisers.py
deleted file mode 100755
index 8b2568dd..00000000
--- a/examples/dfp/v201502/company_service/get_advertisers.py
+++ /dev/null
@@ -1,69 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all companies that are advertisers.
-
-To create companies, run create_companies.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CompanyService.getCompaniesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- company_service = client.GetService('CompanyService', version='v201502')
-
- # Create statement object to only select companies that are advertisers.
- values = [{
- 'key': 'type',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ADVERTISER'
- }
- }]
- query = 'WHERE type = :type'
- statement = dfp.FilterStatement(query, values)
-
- # Get companies by statement.
- while True:
- response = company_service.getCompaniesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for company in response['results']:
- print ('Company with ID \'%s\', name \'%s\', and type \'%s\' was found.'
- % (company['id'], company['name'], company['type']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/company_service/get_all_companies.py b/examples/dfp/v201502/company_service/get_all_companies.py
deleted file mode 100755
index b9405658..00000000
--- a/examples/dfp/v201502/company_service/get_all_companies.py
+++ /dev/null
@@ -1,61 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all companies.
-
-To create companies, run create_companies.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CompanyService.getCompaniesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- company_service = client.GetService('CompanyService', version='v201502')
-
- # Create statement object to select all companies.
- statement = dfp.FilterStatement()
-
- # Get companies by statement.
- while True:
- response = company_service.getCompaniesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for company in response['results']:
- print ('Company with ID \'%s\', name \'%s\', and type \'%s\' was found.'
- % (company['id'], company['name'], company['type']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/company_service/update_companies.py b/examples/dfp/v201502/company_service/update_companies.py
deleted file mode 100755
index cd45fa69..00000000
--- a/examples/dfp/v201502/company_service/update_companies.py
+++ /dev/null
@@ -1,77 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates company comments.
-
-To determine which companies exist, run get_all_companies.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CompanyService.updateCompanies
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the company to update.
-COMPANY_ID = 'INSERT_COMPANY_ID_HERE'
-
-
-def main(client, company_id):
- # Initialize appropriate service.
- company_service = client.GetService('CompanyService', version='v201502')
-
- # Create statement object to only select a single company by ID.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': company_id
- }
- }]
- query = 'WHERE id = :id'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get companies by statement.
- response = company_service.getCompaniesByStatement(
- statement.ToStatement())
- if 'results' in response:
- updated_companies = []
- for company in response['results']:
- company['comment'] += ' Updated.'
- updated_companies.append(company)
-
- # Update the companies on the server.
- companies = company_service.updateCompanies(updated_companies)
-
- # Display results.
- for company in companies:
- print (('Company with ID \'%s\', name \'%s\', and comment \'%s\''
- 'was updated.')
- % (company['id'], company['name'], company['comment']))
- else:
- print 'No companies found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, COMPANY_ID)
diff --git a/examples/dfp/v201502/contact_service/__init__.py b/examples/dfp/v201502/contact_service/__init__.py
deleted file mode 100755
index a426ca48..00000000
--- a/examples/dfp/v201502/contact_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201502/contact_service/create_contacts.py b/examples/dfp/v201502/contact_service/create_contacts.py
deleted file mode 100755
index 081bf44e..00000000
--- a/examples/dfp/v201502/contact_service/create_contacts.py
+++ /dev/null
@@ -1,74 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new contacts.
-
-To determine which contacts exist, run get_all_contacts.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContactService.createContacts
-"""
-
-__author__ = ('Vincent Tsao',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the advertiser company this contact is associated with.
-ADVERTISER_COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
-
-# Set the ID of the agency company this contact is associated with.
-AGENCY_COMPANY_ID = 'INSERT_AGENCY_COMPANY_ID_HERE'
-
-
-def main(client, advertiser_company_id, agency_company_id):
- # Initialize appropriate service.
- contact_service = client.GetService('ContactService', version='v201502')
-
- # Create an advertiser contact.
- advertiser_contact = {
- 'name': 'Mr. Advertiser #%s' % uuid.uuid4(),
- 'email': 'advertiser@advertising.com',
- 'companyId': advertiser_company_id
- }
-
- # Create an agency contact.
- agency_contact = {
- 'name': 'Ms. Agency #%s' % uuid.uuid4(),
- 'email': 'agency@agencies.com',
- 'companyId': agency_company_id
- }
-
- # Create the contacts on the server.
- contacts = contact_service.createContacts([advertiser_contact,
- agency_contact])
-
- # Display results.
- for contact in contacts:
- print ('Contact with ID \'%s\' name \'%s\' was created.'
- % (contact['id'], contact['name']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ADVERTISER_COMPANY_ID, AGENCY_COMPANY_ID)
diff --git a/examples/dfp/v201502/contact_service/get_all_contacts.py b/examples/dfp/v201502/contact_service/get_all_contacts.py
deleted file mode 100755
index a00eb9e9..00000000
--- a/examples/dfp/v201502/contact_service/get_all_contacts.py
+++ /dev/null
@@ -1,61 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all contacts.
-
-To create contacts, run create_contacts.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContactService.getContactsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- contact_service = client.GetService('ContactService', version='v201502')
-
- # Create statement object to get all contacts.
- statement = dfp.FilterStatement()
-
- # Get contacts by statement.
- while True:
- response = contact_service.getContactsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for contact in response['results']:
- print ('Contact with ID \'%s\' and name \'%s\' was found.'
- % (contact['id'], contact['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/contact_service/get_uninvited_contacts.py b/examples/dfp/v201502/contact_service/get_uninvited_contacts.py
deleted file mode 100755
index 91ffd159..00000000
--- a/examples/dfp/v201502/contact_service/get_uninvited_contacts.py
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all contacts that aren't invited yet.
-
-To create contacts, run create_contacts.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContactService.getContactsByStatement
-"""
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- contact_service = client.GetService('ContactService', version='v201502')
-
- # Create statement object to only select contacts that are uninvited.
- values = [{
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'UNINVITED'
- }
- }]
- query = 'WHERE status = :status'
- statement = dfp.FilterStatement(query, values)
-
- # Get contacts by statement.
- while True:
- response = contact_service.getContactsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for contact in response['results']:
- print ('Contact with ID \'%s\' and name \'%s\' was found.'
- % (contact['id'], contact['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/contact_service/update_contacts.py b/examples/dfp/v201502/contact_service/update_contacts.py
deleted file mode 100755
index c8d7241e..00000000
--- a/examples/dfp/v201502/contact_service/update_contacts.py
+++ /dev/null
@@ -1,79 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates contact addresses.
-
-To determine which contacts exist, run get_all_contacts.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContactService.updateContacts
- ContactService.getContactsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the contact to update.
-CONTACT_ID = 'INSERT_CONTACT_ID_HERE'
-
-
-def main(client, contact_id):
- # Initialize appropriate service.
- contact_service = client.GetService('ContactService', version='v201502')
-
- # Create statement object to select the single contact by ID.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': contact_id
- }
- }]
- query = 'WHERE id = :id'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get contacts by statement.
- response = contact_service.getContactsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- updated_contacts = []
- for contact in response['results']:
- contact['address'] = '123 New Street, New York, NY, 10011'
- updated_contacts.append(contact)
-
- # Update the contact on the server.
- contacts = contact_service.updateContacts(updated_contacts)
-
- # Display results.
- for contact in contacts:
- print (('Contact with ID \'%s\', name \'%s\', and address \'%s\' '
- 'was updated.')
- % (contact['id'], contact['name'], contact['address']))
- else:
- print 'No contacts found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CONTACT_ID)
diff --git a/examples/dfp/v201502/content_metadata_key_hierarchy_service/__init__.py b/examples/dfp/v201502/content_metadata_key_hierarchy_service/__init__.py
deleted file mode 100755
index a426ca48..00000000
--- a/examples/dfp/v201502/content_metadata_key_hierarchy_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201502/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/dfp/v201502/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py
deleted file mode 100755
index 9debd246..00000000
--- a/examples/dfp/v201502/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py
+++ /dev/null
@@ -1,81 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new content metadata key hierarchies.
-
-To determine which content metadata key hierarchies exist, run
-get_all_content_metadata_key_hierarchies.py.
-
-This feature is only available to DFP video publishers.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContentMetadataKeyHierarchyService.createContentMetadataKeyHierarchies
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the IDs of the custom targeting keys for the hierarchy.
-HIERARCHY_LEVEL_ONE_KEY_ID = 'INSERT_LEVEL_ONE_CUSTOM_TARGETING_KEY_ID_HERE'
-HIERARCHY_LEVEL_TWO_KEY_ID = 'INSERT_LEVEL_TWO_CUSTOM_TARGETING_KEY_ID_HERE'
-
-
-def main(client, hierarchy_level_one_key_id, hierarchy_level_two_key_id):
- # Initialize appropriate service.
- content_metadata_key_hierarchy_service = client.GetService(
- 'ContentMetadataKeyHierarchyService', version='v201502')
-
- hierarchy_level_1 = {
- 'customTargetingKeyId': hierarchy_level_one_key_id,
- 'hierarchyLevel': '1'
- }
-
- hierarchy_level_2 = {
- 'customTargetingKeyId': hierarchy_level_two_key_id,
- 'hierarchyLevel': '2'
- }
-
- hierarchy_levels = [hierarchy_level_1, hierarchy_level_2]
-
- # Create content metadata key hierarchy object.
- content_metadata_key_hierarchy = {
- 'name': 'Content Metadata Key Hierarchy #%s' % uuid.uuid4(),
- 'hierarchyLevels': hierarchy_levels
- }
-
- content_metadata_key_hierarchies = (
- content_metadata_key_hierarchy_service
- .createContentMetadataKeyHierarchies([content_metadata_key_hierarchy]))
-
- # Display results.
- for content_metadata_key_hierarchy in content_metadata_key_hierarchies:
- print ('Content metadata key hierarchy with id \'%s\' and name \'%s\''
- ' was created.' % (content_metadata_key_hierarchy['id'],
- content_metadata_key_hierarchy['name']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, HIERARCHY_LEVEL_ONE_KEY_ID, HIERARCHY_LEVEL_TWO_KEY_ID)
diff --git a/examples/dfp/v201502/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py b/examples/dfp/v201502/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py
deleted file mode 100755
index 25d014cb..00000000
--- a/examples/dfp/v201502/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py
+++ /dev/null
@@ -1,88 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example deletes content metadata key hierarchies.
-
-To determine which content metadata key hierarchies exist, run
-get_all_content_metadata_key_hierarchies.py.
-
-This feature is only available to DFP video publishers.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContentMetadataKeyHierarchyService.getContentMetadataKeyHierarchiesByStatement
- ContentMetadataKeyHierarchyService.perfomContentMetadataKeyHierarchyAction
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the content metadata key hierarchy to delete.
-CONTENT_METADATA_KEY_HIERARCHY_ID = (
- 'INSERT_CONTENT_METADATA_KEY_HIERARCHY_ID_HERE')
-
-
-def main(client, content_metadata_key_hierarchy_id):
- # Initialize appropriate service.
- content_metadata_key_hierarchy_service = client.GetService(
- 'ContentMetadataKeyHierarchyService', version='v201502')
-
- # Create a query to select a single content metadata key hierarchy.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': content_metadata_key_hierarchy_id
- }
- }]
-
- query = 'WHERE id = :id ORDER BY id ASC'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get a single content metadata key hierarchy by statement.
- response = (content_metadata_key_hierarchy_service
- .getContentMetadataKeyHierarchiesByStatement(
- statement.ToStatement())[0])
- content_metadata_key_hierarchies = (response['results']
- if 'results' in response else None)
-
- # Display results.
- if content_metadata_key_hierarchies:
- for content_metadata_key_hierarchy in content_metadata_key_hierarchies:
- print ('Content metadata key hierarchy with ID \'%s\' and name \'%s\' '
- 'will be deleted.' % (content_metadata_key_hierarchy['id'],
- content_metadata_key_hierarchy['name']))
-
- # Perform action.
- result = (content_metadata_key_hierarchy_service
- .performContentMetadataKeyHierarchyAction(
- {'type': 'DeleteContentMetadataKeyHierarchies'},
- statement.ToStatement()))[0]
-
- # Display results.
- print ('Number of content metadata key hierarchies deleted: %s' %
- result['numChanges'])
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CONTENT_METADATA_KEY_HIERARCHY_ID)
diff --git a/examples/dfp/v201502/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/dfp/v201502/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py
deleted file mode 100755
index 002eeb89..00000000
--- a/examples/dfp/v201502/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py
+++ /dev/null
@@ -1,66 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all content metadata key hierarchies.
-
-This feature is only available to DFP video publishers.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContentMetadataKeyHierarchyService.getContentMetadataKeyHierarchiesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- content_metadata_key_hierarchy_service = client.GetService(
- 'ContentMetadataKeyHierarchyService', version='v201502')
-
- # Create statement object to select all content.
- statement = dfp.FilterStatement()
-
- # Get content by statement.
- while True:
- response = (content_metadata_key_hierarchy_service
- .getContentMetadataKeyHierarchiesByStatement(
- statement.ToStatement())[0])
- content_metadata_key_hierarchies = (response['results']
- if 'results' in response else None)
- if content_metadata_key_hierarchies:
- # Display results.
- for content_metadata_key_hierarchy in content_metadata_key_hierarchies:
- print ('Content metadata key hierarchyy with id \'%s\' and name \'%s\''
- ' was found.' % (content_metadata_key_hierarchy['id'],
- content_metadata_key_hierarchy['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/dfp/v201502/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py
deleted file mode 100755
index d2b37dfa..00000000
--- a/examples/dfp/v201502/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py
+++ /dev/null
@@ -1,100 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates content metadata key hierarchies.
-
-To determine which content metadata key hierarchies exist, run
-get_all_content_metadata_key_hierarchies.py.
-
-This feature is only available to DFP video publishers.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContentMetadataKeyHierarchyService.getContentMetadataKeyHierarchiesByStatement
- ContentMetadataKeyHierarchyService.updateContentMetadataKeyHierarchies
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the content metadata key hierarchy to update.
-CONTENT_METADATA_KEY_HIERARCHY_ID = (
- 'INSERT_CONTENT_METADATA_KEY_HIERARCHY_ID_HERE')
-# Set the ID of the custom targeting key to be added as a hierarchy level.
-CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'
-
-
-def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id):
- # Initialize appropriate service.
- content_metadata_key_hierarchy_service = client.GetService(
- 'ContentMetadataKeyHierarchyService', version='v201502')
-
- # Create a query to select a single content metadata key hierarchy.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': content_metadata_key_hierarchy_id
- }
- }]
-
- query = 'WHERE id = :id ORDER BY id ASC'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get a single content metadata key hierarchy by statement.
- response = (content_metadata_key_hierarchy_service
- .getContentMetadataKeyHierarchiesByStatement(
- statement.ToStatement()))[0]
- content_metadata_key_hierarchies = (response['results']
- if 'results' in response else None)
-
- if content_metadata_key_hierarchies:
- content_metadata_key_hierarchy = content_metadata_key_hierarchies[0]
-
- # Update the content metadata key hierarchy by adding a hierarchy level.
- hierarchy_levels = content_metadata_key_hierarchy['hierarchyLevels']
-
- hierarchy_level = {
- 'customTargetingKeyId': custom_targeting_key_id,
- 'hierarchyLevel': str(len(hierarchy_levels) + 1)
- }
-
- content_metadata_key_hierarchy['hierarchyLevels'] = (
- hierarchy_levels.append(hierarchy_level))
-
- content_metadata_key_hierarchies = (
- content_metadata_key_hierarchy_service
- .updateContentMetadataKeyHierarchies(content_metadata_key_hierarchies))
-
- # Display results.
- for content_metadata_key_hierarchy in content_metadata_key_hierarchies:
- print ('Content metadata key hierarchy with id \'%s\' and name \'%s\''
- ' was updated.' % (content_metadata_key_hierarchy['id'],
- content_metadata_key_hierarchy['name']))
-
- else:
- print 'No content metadata key hierarchies were found'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CONTENT_METADATA_KEY_HIERARCHY_ID, CUSTOM_TARGETING_KEY_ID)
diff --git a/examples/dfp/v201502/content_service/__init__.py b/examples/dfp/v201502/content_service/__init__.py
deleted file mode 100755
index a426ca48..00000000
--- a/examples/dfp/v201502/content_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201502/content_service/get_all_content.py b/examples/dfp/v201502/content_service/get_all_content.py
deleted file mode 100755
index 5b17ca8e..00000000
--- a/examples/dfp/v201502/content_service/get_all_content.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all content.
-
-This feature is only available to DFP video publishers.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContentService.getContentByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- content_service = client.GetService('ContentService', version='v201502')
-
- # Create statement object to select all content.
- statement = dfp.FilterStatement()
-
- # Get content by statement.
- while True:
- response = content_service.getContentByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for content_item in response['results']:
- print ('Content with id \'%s\', name \'%s\', and status \'%s\' was '
- 'found.' % (content_item['id'], content_item['name'],
- content_item['status']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/content_service/get_content_by_category.py b/examples/dfp/v201502/content_service/get_content_by_category.py
deleted file mode 100755
index 34d6a713..00000000
--- a/examples/dfp/v201502/content_service/get_content_by_category.py
+++ /dev/null
@@ -1,112 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all active content categorized as a "comedy" using the
-network's content browse custom targeting key.
-
-This feature is only available to DFP video publishers.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: ContentService.getContentByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- content_service = client.GetService('ContentService', version='v201502')
- network_service = client.GetService('NetworkService', version='v201502')
- custom_targeting_service = client.GetService(
- 'CustomTargetingService', version='v201502')
-
- # Get the network's content browse custom targeting key.
- network = network_service.getCurrentNetwork()
- key_id = network['contentBrowseCustomTargetingKeyId']
-
- # Create a statement to select the categories matching the name comedy.
- values = [
- {
- 'key': 'contentBrowseCustomTargetingKeyId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': key_id
- }
- },
- {
- 'key': 'category',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'comedy'
- }
- }
- ]
- category_filter_query = ('WHERE customTargetingKeyId = '
- ':contentBrowseCustomTargetingKeyId and name = '
- ':category')
- category_filter_statement = dfp.FilterStatement(
- category_filter_query, values, 1)
-
- # Get categories matching the filter statement.
- response = custom_targeting_service.getCustomTargetingValuesByStatement(
- category_filter_statement.ToStatement())
-
- # Get the custom targeting value ID for the comedy category.
- if 'results' in response:
- category_custom_targeting_value_id = (response['results']['id'])
-
- # Create a statement to select the active content.
- content_values = [
- {
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ACTIVE'
- }
- }
- ]
- content_query = 'WHERE status = :status'
- content_statement = dfp.FilterStatement(content_query, content_values)
-
- while True:
- # Get the content by statement and custom targeting value.
- response = content_service.getContentByStatementAndCustomTargetingValue(
- content_statement.ToStatement(),
- category_custom_targeting_value_id)
- if 'results' in response:
- # Display results.
- for content_item in response['results']:
- print ('Content with id \'%s\', name \'%s\', and status \'%s\' was '
- 'found.' % (content_item['id'], content_item['name'],
- content_item['status']))
- content_statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/creative_service/__init__.py b/examples/dfp/v201502/creative_service/__init__.py
deleted file mode 100755
index a426ca48..00000000
--- a/examples/dfp/v201502/creative_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201502/creative_service/create_creative_from_template.py b/examples/dfp/v201502/creative_service/create_creative_from_template.py
deleted file mode 100755
index 6cf77f5c..00000000
--- a/examples/dfp/v201502/creative_service/create_creative_from_template.py
+++ /dev/null
@@ -1,104 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates a new template creative for a given advertiser.
-
-To determine which companies are advertisers, run get_advertisers.py.
-To determine which creative templates exist, run
-get_all_creative_templates.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeService.createCreative
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import base64
-import os
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set id of the advertiser (company) that the creative will be assigned to.
-ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
-
-
-def main(client, advertiser_id):
- # Initialize appropriate service.
- creative_service = client.GetService('CreativeService', version='v201502')
-
- # Use the image banner with optional third party tracking template.
- creative_template_id = '10000680'
-
- image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data',
- 'medium_rectangle.jpg'), 'r').read()
- image_data = base64.encodestring(image_data)
- # Create creative from templates.
- creative = {
- 'xsi_type': 'TemplateCreative',
- 'name': 'Template Creative #%s' % uuid.uuid4(),
- 'advertiserId': advertiser_id,
- 'size': {'width': '300', 'height': '250'},
- 'creativeTemplateId': creative_template_id,
- 'creativeTemplateVariableValues': [
- {
- 'xsi_type': 'AssetCreativeTemplateVariableValue',
- 'uniqueName': 'Imagefile',
- 'assetByteArray': image_data,
- 'fileName': 'image%s.jpg' % uuid.uuid4()
- },
- {
- 'xsi_type': 'LongCreativeTemplateVariableValue',
- 'uniqueName': 'Imagewidth',
- 'value': '300'
- },
- {
- 'xsi_type': 'LongCreativeTemplateVariableValue',
- 'uniqueName': 'Imageheight',
- 'value': '250'
- },
- {
- 'xsi_type': 'UrlCreativeTemplateVariableValue',
- 'uniqueName': 'ClickthroughURL',
- 'value': 'www.google.com'
- },
- {
- 'xsi_type': 'StringCreativeTemplateVariableValue',
- 'uniqueName': 'Targetwindow',
- 'value': '_blank'
- }
- ]
- }
-
- # Call service to create the creative.
- creative = creative_service.createCreative(creative)
-
- # Display results.
- print ('Template creative with id \'%s\', name \'%s\', and type \'%s\' was '
- 'created and can be previewed at %s.'
- % (creative['id'], creative['name'], dfp.DfpClassType(creative),
- creative['previewUrl']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ADVERTISER_ID)
diff --git a/examples/dfp/v201502/creative_service/create_creatives.py b/examples/dfp/v201502/creative_service/create_creatives.py
deleted file mode 100755
index 1e7183fb..00000000
--- a/examples/dfp/v201502/creative_service/create_creatives.py
+++ /dev/null
@@ -1,94 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new image creatives for a given advertiser.
-
-To determine which companies are advertisers, run get_advertisers.py.
-To determine which creatives already exist, run get_all_creatives.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeService.createCreatives
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import base64
-import os
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set id of the advertiser (company) that all creatives will be assigned to.
-ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
-
-
-def main(client, advertiser_id):
- # Initialize appropriate service.
- creative_service = client.GetService('CreativeService', version='v201502')
-
- # Create creative objects.
- creatives = []
- with open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data',
- 'medium_rectangle.jpg'), 'r') as image:
- image_data = base64.encodestring(image.read())
-
- for i in xrange(5):
- # Create creative size.
- size = {
- 'width': '300',
- 'height': '250'
- }
-
- # Create image asset.
- creative_asset = {
- 'xsi_type': 'CreativeAsset',
- 'fileName': 'image.jpg',
- 'assetByteArray': image_data,
- 'size': size
- }
-
- # Create an image creative.
- creative = {
- 'xsi_type': 'ImageCreative',
- 'name': 'Image Creative #%s' % uuid.uuid4(),
- 'advertiserId': advertiser_id,
- 'destinationUrl': 'http://google.com',
- 'size': size,
- 'primaryImageAsset': creative_asset
- }
-
- creatives.append(creative)
-
- # Add creatives.
- creatives = creative_service.createCreatives(creatives)
-
- # Display results.
- for creative in creatives:
- print ('Image creative with id \'%s\', name \'%s\', and type \'%s\' was '
- 'created and can be previewed at %s.'
- % (creative['id'], creative['name'], dfp.DfpClassType(creative),
- creative['previewUrl']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ADVERTISER_ID)
diff --git a/examples/dfp/v201502/creative_service/create_custom_creative.py b/examples/dfp/v201502/creative_service/create_custom_creative.py
deleted file mode 100755
index dcae98c8..00000000
--- a/examples/dfp/v201502/creative_service/create_custom_creative.py
+++ /dev/null
@@ -1,90 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates a custom creative for a given advertiser.
-
-This feature is only available to DFP premium solution networks. To determine
-which companies are advertisers, run get_advertisers.py. To determine
-which creative templates exist, run get_all_creative_templates.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeService.createCreative
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import base64
-import os
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set id of the advertiser (company) that the creative will be assigned to.
-ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
-
-
-def main(client, advertiser_id):
- # Initialize appropriate service.
- creative_service = client.GetService('CreativeService', version='v201502')
-
- # Get the image data for the creative.
- image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data',
- 'medium_rectangle.jpg'), 'r').read()
- image_data = base64.encodestring(image_data)
-
- # Create the HTML snippet used in the custom creative.
- html_snippet = (' Click above for '
- 'great deals!') % ('%%CLICK_URL_UNESC%%', '%%DEST_URL%%',
- '%%FILE:IMAGE_ASSET%%')
-
- # Create custom creative.
- creative = {
- 'xsi_type': 'CustomCreative',
- 'name': 'Custom Creative #%s' % uuid.uuid4(),
- 'advertiserId': advertiser_id,
- 'size': {'width': '300', 'height': '250'},
- 'destinationUrl': 'http://google.com',
- 'customCreativeAssets': [
- {
- 'xsi_type': 'CustomCreativeAsset',
- 'macroName': 'IMAGE_ASSET',
- 'assetByteArray': image_data,
- 'fileName': 'image%s.jpg' % uuid.uuid4()
- }
- ],
- 'htmlSnippet': html_snippet
- }
-
- # Call service to create the creative.
- creative = creative_service.createCreative(creative)
-
- # Display results.
- if creative:
- print ('Template creative with id \'%s\', name \'%s\', and type \'%s\' was '
- 'created and can be previewed at %s.'
- % (creative['id'], creative['name'], dfp.DfpClassType(creative),
- creative['previewUrl']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ADVERTISER_ID)
diff --git a/examples/dfp/v201502/creative_service/get_all_creatives.py b/examples/dfp/v201502/creative_service/get_all_creatives.py
deleted file mode 100755
index 436e48d7..00000000
--- a/examples/dfp/v201502/creative_service/get_all_creatives.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all creatives.
-
-To create creatives, run create_creatives.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeService.getCreativesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- creative_service = client.GetService('CreativeService', version='v201502')
-
- # Create statement object to select all creatives.
- statement = dfp.FilterStatement()
-
- # Get creatives by statement.
- while True:
- response = creative_service.getCreativesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for creative in response['results']:
- print ('Creative with id \'%s\', name \'%s\', and type \'%s\' was '
- 'found.' % (creative['id'], creative['name'],
- dfp.DfpClassType(creative)))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/creative_service/get_creatives_by_statement.py b/examples/dfp/v201502/creative_service/get_creatives_by_statement.py
deleted file mode 100755
index db2bd3b2..00000000
--- a/examples/dfp/v201502/creative_service/get_creatives_by_statement.py
+++ /dev/null
@@ -1,72 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all image creatives.
-
-To create an image creative, run create_creatives.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeService.getCreativesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- creative_service = client.GetService('CreativeService', version='v201502')
-
- # Create statement object to only select image creatives.
- values = [{
- 'key': 'creativeType',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ImageCreative'
- }
- }]
- query = 'WHERE creativeType = :creativeType'
- statement = dfp.FilterStatement(query, values)
-
- # Get creatives by statement.
- while True:
- response = creative_service.getCreativesByStatement(
- statement.ToStatement())
- creatives = response['results']
-
- if creatives:
- # Display results.
- for creative in creatives:
- print ('Creative with id \'%s\', name \'%s\', and type \'%s\' was '
- 'found.' % (creative['id'], creative['name'],
- dfp.DfpClassType(creative)))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/creative_service/update_creatives.py b/examples/dfp/v201502/creative_service/update_creatives.py
deleted file mode 100755
index 1dab62ad..00000000
--- a/examples/dfp/v201502/creative_service/update_creatives.py
+++ /dev/null
@@ -1,84 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates the destination URL of a single image creative.
-
-To determine which image creatives exist, run get_all_creatives.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeService.updateCreatives
- CreativeService.getCreativesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-IMAGE_CREATIVE_ID = 'INSERT_IMAGE_CREATIVE_ID_HERE'
-
-
-def main(client, image_creative_id):
- # Initialize appropriate service.
- creative_service = client.GetService('CreativeService', version='v201502')
-
- # Create statement object to get all image creatives.
- values = [{
- 'key': 'type',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ImageCreative'
- }
- }, {
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': image_creative_id
- }
- }]
- query = 'WHERE creativeType = :type AND id = :id'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get creatives by statement.
- response = creative_service.getCreativesByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- # Update each local creative object by changing its destination URL.
- updated_creatives = []
- for creative in response['results']:
- creative['destinationUrl'] = 'http://news.google.com'
- updated_creatives.append(creative)
-
- # Update creatives remotely.
- creatives = creative_service.updateCreatives(updated_creatives)
-
- # Display results.
- for creative in creatives:
- print ('Image creative with id \'%s\' and destination URL \'%s\' was '
- 'updated.' % (creative['id'], creative['destinationUrl']))
- else:
- print 'No creatives found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, IMAGE_CREATIVE_ID)
diff --git a/examples/dfp/v201502/creative_set_service/__init__.py b/examples/dfp/v201502/creative_set_service/__init__.py
deleted file mode 100755
index a426ca48..00000000
--- a/examples/dfp/v201502/creative_set_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201502/creative_set_service/associate_creative_set_to_line_item.py b/examples/dfp/v201502/creative_set_service/associate_creative_set_to_line_item.py
deleted file mode 100755
index dc423cc7..00000000
--- a/examples/dfp/v201502/creative_set_service/associate_creative_set_to_line_item.py
+++ /dev/null
@@ -1,59 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates a line item creative association for a creative
-set.
-
-To create creative sets, run create_creative_set.py. To create creatives, run
-create_creatives.py. To determine which LICAs exist, run get_all_licas.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: LineItemCreativeAssociationService.createLineItemCreativeAssociations
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-CREATIVE_SET_ID = 'INSERT_CREATIVE_SET_ID_HERE'
-LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
-
-
-def main(client, creative_set_id, line_item_id):
- # Initialize appropriate service.
- lica_service = client.GetService(
- 'LineItemCreativeAssociationService', version='v201502')
-
- # Create LICA for a creative set.
- lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id}
-
- # Add LICA.
- lica = lica_service.createLineItemCreativeAssociations([lica])
-
- # Display results.
- print (('LICA with line item ID \'%s\' and creative set ID \'%s\' was '
- 'created.') % (lica['lineItemId'], lica['creativeSetId']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CREATIVE_SET_ID, LINE_ITEM_ID)
diff --git a/examples/dfp/v201502/creative_set_service/create_creative_set.py b/examples/dfp/v201502/creative_set_service/create_creative_set.py
deleted file mode 100755
index 9fcb5afb..00000000
--- a/examples/dfp/v201502/creative_set_service/create_creative_set.py
+++ /dev/null
@@ -1,64 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new creative sets.
-
-To determine which creative sets exist, run get_all_creative_sets.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeSetService.createCreativeSet
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-MASTER_CREATIVE_ID = 'INSERT_MASTER_CREATIVE_ID_HERE'
-COMPANION_CREATIVE_ID = 'INSERT_COMPANION_CREATIVE_ID_HERE'
-
-
-def main(client, master_creative_id, companion_creative_id):
- # Initialize appropriate service.
- creative_set_service = client.GetService('CreativeSetService',
- version='v201502')
-
- # Create creative set objects.
- creative_set = {'name': 'Creative set #%s' % uuid.uuid4(),
- 'masterCreativeId': master_creative_id,
- 'companionCreativeIds': [companion_creative_id]}
-
- # Add creative sets.
- creative_set = creative_set_service.createCreativeSet(creative_set)
-
- # Display results.
- if creative_set:
- print (('Creative set with ID \'%s\', master creative ID \'%s\', and '
- 'companion creative IDs {%s} was created.')
- % (creative_set['id'], creative_set['masterCreativeId'],
- ','.join(creative_set['companionCreativeIds'])))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, MASTER_CREATIVE_ID, COMPANION_CREATIVE_ID)
diff --git a/examples/dfp/v201502/creative_set_service/get_all_creative_sets.py b/examples/dfp/v201502/creative_set_service/get_all_creative_sets.py
deleted file mode 100755
index 930506af..00000000
--- a/examples/dfp/v201502/creative_set_service/get_all_creative_sets.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all creative sets.
-
-To create creative sets, run create_creative_sets.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeSetService.getCreativeSetsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- creative_set_service = client.GetService('CreativeSetService',
- version='v201502')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get creative sets by statement.
- while True:
- response = creative_set_service.getCreativeSetsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for creative_set in response['results']:
- print ('Creative set with ID \'%s\' and name \'%s\' was found.'
- % (creative_set['id'], creative_set['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/creative_set_service/get_creative_sets_by_statement.py b/examples/dfp/v201502/creative_set_service/get_creative_sets_by_statement.py
deleted file mode 100755
index 010243e1..00000000
--- a/examples/dfp/v201502/creative_set_service/get_creative_sets_by_statement.py
+++ /dev/null
@@ -1,75 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all creative sets for a master creative.
-
-To create creative sets, run create_creative_sets.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeSetService.getCreativeSetsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-MASTER_CREATIVE_ID = 'INSERT_MASTER_CREATIVE_ID_HERE'
-
-
-def main(client, master_creative_id):
- # Initialize appropriate service.
- creative_set_service = client.GetService('CreativeSetService',
- version='v201502')
-
- # Create statement object to only select creative sets that have the given
- # master creative.
- values = [{
- 'key': 'masterCreativeId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': master_creative_id
- }
- }]
- query = 'WHERE masterCreativeId = :masterCreativeId'
- statement = dfp.FilterStatement(query, values)
-
- # Get creative sets by statement.
- while True:
- response = creative_set_service.getCreativeSetsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for creative_set in response['results']:
- print (('Creative set with ID \'%s\', master creative ID \'%s\', and '
- 'companion creative IDs {%s} was found.')
- % (creative_set['id'], creative_set['masterCreativeId'],
- ','.join(creative_set['companionCreativeIds'])))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, MASTER_CREATIVE_ID)
diff --git a/examples/dfp/v201502/creative_set_service/update_creative_set.py b/examples/dfp/v201502/creative_set_service/update_creative_set.py
deleted file mode 100755
index 0c34cb80..00000000
--- a/examples/dfp/v201502/creative_set_service/update_creative_set.py
+++ /dev/null
@@ -1,82 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates a creative set by adding a companion creative.
-
-To determine which creative sets exist, run get_all_creative_sets.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeSetService.updateCreativeSet
- CreativeSetService.getCreativeSetsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the creative set to update.
-CREATIVE_SET_ID = 'INSERT_CREATIVE_SET_ID_HERE'
-COMPANION_CREATIVE_ID = 'INSERT_COMPANION_CREATIVE_ID_HERE'
-
-
-def main(client, creative_set_id, companion_creative_id):
- # Initialize appropriate service.
- creative_set_service = client.GetService('CreativeSetService',
- version='v201502')
-
- # Create statement to select a single creative set by ID.
- values = [{
- 'key': 'creativeSetId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': creative_set_id
- }
- }]
- query = 'WHERE id = :creativeSetId'
- statement = dfp.FilterStatement(query, values)
-
- # Get creative set.
- response = creative_set_service.getCreativeSetsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- updated_created_sets = []
- for creative_set in response['results']:
- creative_set['companionCreativeIds'].append(companion_creative_id)
- updated_created_sets.append(creative_set)
-
- # Update the creative sets on the server.
- creative_sets = creative_set_service.updateCreativeSet(updated_created_sets)
-
- # Display results.
- for creative_set in creative_sets:
- print (('Creative set with ID \'%s\', master creative ID \'%s\', and '
- 'companion creative IDs {%s} was updated.')
- % (creative_set['id'], creative_set['masterCreativeId'],
- ','.join(creative_set['companionCreativeIds'])))
- else:
- print 'No creative sets found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CREATIVE_SET_ID, COMPANION_CREATIVE_ID)
diff --git a/examples/dfp/v201502/creative_template_service/__init__.py b/examples/dfp/v201502/creative_template_service/__init__.py
deleted file mode 100755
index a426ca48..00000000
--- a/examples/dfp/v201502/creative_template_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201502/creative_template_service/get_all_creative_templates.py b/examples/dfp/v201502/creative_template_service/get_all_creative_templates.py
deleted file mode 100755
index 7c3a5275..00000000
--- a/examples/dfp/v201502/creative_template_service/get_all_creative_templates.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all creative templates.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeTemplateService.getCreativeTemplatesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- creative_template_service = client.GetService(
- 'CreativeTemplateService', version='v201502')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get creative templates by statement.
- while True:
- response = creative_template_service.getCreativeTemplatesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for template in response['results']:
- print ('Creative template with id \'%s\', name \'%s\', and type \'%s\' '
- 'was found.' % (template['id'],
- template['name'],
- template['type']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/creative_template_service/get_creative_templates_by_statement.py b/examples/dfp/v201502/creative_template_service/get_creative_templates_by_statement.py
deleted file mode 100755
index f799e7c4..00000000
--- a/examples/dfp/v201502/creative_template_service/get_creative_templates_by_statement.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all system defined creative templates.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeTemplateService.getCreativeTemplatesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- creative_template_service = client.GetService(
- 'CreativeTemplateService', version='v201502')
-
- # Create statement object to only select system defined creative templates.
- values = [{
- 'key': 'creativeTemplateType',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'SYSTEM_DEFINED'
- }
- }]
- query = 'WHERE type = :creativeTemplateType'
- statement = dfp.FilterStatement(query, values)
-
- # Get creative templates by statement.
- while True:
- response = creative_template_service.getCreativeTemplatesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for template in response['results']:
- print ('Creative template with id \'%s\', name \'%s\', and type \'%s\' '
- 'was found.' % (template['id'],
- template['name'],
- template['type']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/creative_wrapper_service/create_creative_wrappers.py b/examples/dfp/v201502/creative_wrapper_service/create_creative_wrappers.py
deleted file mode 100755
index 36cba79c..00000000
--- a/examples/dfp/v201502/creative_wrapper_service/create_creative_wrappers.py
+++ /dev/null
@@ -1,66 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates a new creative wrapper.
-
-Creative wrappers must be associated with a LabelType.CREATIVE_WRAPPER label and
-applied to ad units by AdUnit.appliedLabels. To determine which creative
-wrappers exist, run get_all_creative_wrappers.py
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeWrapperService.createCreativeWrappers
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-LABEL_ID = 'INSERT_CREATIVE_WRAPPER_LABEL_ID_HERE'
-
-
-def main(client, label_id):
- # Initialize appropriate service.
- creative_wrapper_service = client.GetService('CreativeWrapperService',
- version='v201502')
-
- # Create creative wrapper objects.
- creative_wrapper = {
- # A label can only be associated with one creative wrapper.
- 'labelId': label_id,
- 'ordering': 'INNER',
- 'header': {'htmlSnippet': 'My creative wrapper header'},
- 'footer': {'htmlSnippet': 'My creative wrapper footer'}
- }
-
- # Add creative wrapper.
- creative_wrappers = creative_wrapper_service.createCreativeWrappers(
- [creative_wrapper])
-
- # Display results.
- for creative_wrapper in creative_wrappers:
- print ('Creative wrapper with ID \'%s\' applying to label \'%s\' was '
- 'created.' % (creative_wrapper['id'], creative_wrapper['labelId']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, LABEL_ID)
diff --git a/examples/dfp/v201502/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201502/creative_wrapper_service/deactivate_creative_wrapper.py
deleted file mode 100755
index 8c59c06d..00000000
--- a/examples/dfp/v201502/creative_wrapper_service/deactivate_creative_wrapper.py
+++ /dev/null
@@ -1,92 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example deactivates a creative wrapper belonging to a label.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeWrapperService.getCreativeWrapperByStatement
-Tags: CreativeWrapperService.performCreativeWrapperAction
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-LABEL_ID = 'INSERT_LABEL_ID_HERE'
-
-
-def main(client, label_id):
- # Initialize appropriate service.
- creative_wrapper_service = client.GetService('CreativeWrapperService',
- version='v201502')
-
- # Create a query to select the active creative wrappers for the given label.
- values = [{
- 'key': 'labelId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': label_id
- }
- }, {
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ACTIVE'
- }
- }]
- query = 'WHERE status = :status AND labelId = :labelId'
- statement = dfp.FilterStatement(query, values)
-
- creative_wrappers_deactivated = 0
-
- # Get creative wrappers by statement.
- while True:
- response = creative_wrapper_service.getCreativeWrappersByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for creative_wrapper in response['results']:
- print ('Creative wrapper with ID \'%s\' applying to label \'%s\' with '
- 'status \'%s\' will be deactivated.' %
- (creative_wrapper['id'],
- creative_wrapper['labelId'],
- creative_wrapper['status']))
- # Perform action.
- result = creative_wrapper_service.performCreativeWrapperAction(
- {'xsi_type': 'DeactivateCreativeWrappers'}, statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- creative_wrappers_deactivated += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Display results.
- if creative_wrappers_deactivated > 0:
- print ('Number of creative wrappers deactivated: %s' %
- creative_wrappers_deactivated)
- else:
- print 'No creative wrappers were deactivated.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, LABEL_ID)
diff --git a/examples/dfp/v201502/creative_wrapper_service/get_active_creative_wrappers.py b/examples/dfp/v201502/creative_wrapper_service/get_active_creative_wrappers.py
deleted file mode 100755
index 453504d1..00000000
--- a/examples/dfp/v201502/creative_wrapper_service/get_active_creative_wrappers.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all active creative wrappers.
-
-To create creative wrappers, run create_creative_wrappers.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeWrapperService.getCreativeWrappersByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- creative_wrapper_service = client.GetService('CreativeWrapperService',
- version='v201502')
-
- # Create statement object to only select active creative wrappers.
- values = [{
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ACTIVE'
- }
- }]
- query = 'WHERE status = :status'
- statement = dfp.FilterStatement(query, values)
-
- # Get creative wrappers by statement.
- while True:
- response = creative_wrapper_service.getCreativeWrappersByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for creative_wrapper in response['results']:
- print ('Creative wrapper with ID \'%s\' applying to label \'%s\' was '
- 'found.' % (creative_wrapper['id'], creative_wrapper['labelId']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/creative_wrapper_service/get_all_creative_wrappers.py b/examples/dfp/v201502/creative_wrapper_service/get_all_creative_wrappers.py
deleted file mode 100755
index 7defc209..00000000
--- a/examples/dfp/v201502/creative_wrapper_service/get_all_creative_wrappers.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all creative wrappers.
-
-To create creative wrappers, run create_creative_wrappers.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeWrapperService.getCreativeWrappersByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- creative_wrapper_service = client.GetService('CreativeWrapperService',
- version='v201502')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get creative wrappers by statement.
- while True:
- response = creative_wrapper_service.getCreativeWrappersByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for creative_wrapper in response['results']:
- print ('Creative wrapper with ID \'%s\' applying to label \'%s\' was '
- 'found.' % (creative_wrapper['id'], creative_wrapper['labelId']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/creative_wrapper_service/update_creative_wrappers.py b/examples/dfp/v201502/creative_wrapper_service/update_creative_wrappers.py
deleted file mode 100755
index 04235d0a..00000000
--- a/examples/dfp/v201502/creative_wrapper_service/update_creative_wrappers.py
+++ /dev/null
@@ -1,81 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates a creative wrapper to the 'OUTER' wrapping order.
-
-To determine which creative wrappers exist, run get_all_creative_wrappers.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CreativeWrapperService.getCreativeWrappersByStatement
-Tags: CreativeWrapperService.updateCreativeWrappers
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the creative wrapper to update.
-CREATIVE_WRAPPER_ID = 'INSERT_CREATIVE_WRAPPER_ID_HERE'
-
-
-def main(client, creative_wrapper_id):
- # Initialize appropriate service.
- creative_wrapper_service = client.GetService('CreativeWrapperService',
- version='v201502')
-
- # Create statement to get a creative wrapper by ID.
- values = [{
- 'key': 'creativeWrapperId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': creative_wrapper_id
- }
- }]
- query = 'WHERE id = :creativeWrapperId'
- statement = dfp.FilterStatement(query, values)
-
- # Get creative wrappers.
- response = creative_wrapper_service.getCreativeWrappersByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- updated_creative_wrappers = []
- for creative_wrapper in response['results']:
- creative_wrapper['ordering'] = 'OUTER'
- updated_creative_wrappers.append(creative_wrapper)
-
- # Update the creative wrappers on the server.
- creative_wrappers = creative_wrapper_service.updateCreativeWrappers(
- updated_creative_wrappers)
-
- # Display results.
- for creative_wrapper in creative_wrappers:
- print (('Creative wrapper with ID \'%s\' and wrapping order \'%s\' '
- 'was updated.') % (creative_wrapper['id'],
- creative_wrapper['ordering']))
- else:
- print 'No creative wrappers found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CREATIVE_WRAPPER_ID)
diff --git a/examples/dfp/v201502/custom_field_service/__init__.py b/examples/dfp/v201502/custom_field_service/__init__.py
deleted file mode 100755
index a426ca48..00000000
--- a/examples/dfp/v201502/custom_field_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201502/custom_field_service/create_custom_field_options.py b/examples/dfp/v201502/custom_field_service/create_custom_field_options.py
deleted file mode 100755
index a73c9a8a..00000000
--- a/examples/dfp/v201502/custom_field_service/create_custom_field_options.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates custom field options for a drop-down custom field.
-
-Once created, custom field options can be found under the options fields of the
-drop-down custom field and they cannot be deleted. To determine which custom
-fields exist, run get_all_custom_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomFieldService.createCustomFieldOptions
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the drop-down custom field to create options for.
-CUSTOM_FIELD_ID = 'INSERT_DROP_DOWN_CUSTOM_FIELD_ID_HERE'
-
-
-def main(client, custom_field_id):
- # Initialize appropriate service.
- custom_field_service = client.GetService(
- 'CustomFieldService', version='v201502')
-
- # Create custom field options.
- custom_field_options = [
- {
- 'displayName': 'Approved',
- 'customFieldId': custom_field_id
- },
- {
- 'displayName': 'Unapproved',
- 'customFieldId': custom_field_id
- }
- ]
-
- # Add custom field options.
- custom_field_options = custom_field_service.createCustomFieldOptions(
- custom_field_options)
-
- # Display results.
- for custom_field_option in custom_field_options:
- print ('Custom field option with ID \'%s\' and name \'%s\' was created.'
- % (custom_field_option['id'], custom_field_option['displayName']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CUSTOM_FIELD_ID)
diff --git a/examples/dfp/v201502/custom_field_service/create_custom_fields.py b/examples/dfp/v201502/custom_field_service/create_custom_fields.py
deleted file mode 100755
index f4f6dcb2..00000000
--- a/examples/dfp/v201502/custom_field_service/create_custom_fields.py
+++ /dev/null
@@ -1,69 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates custom fields.
-
-To determine which custom fields exist, run get_all_custom_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomFieldService.createCustomFields
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- custom_field_service = client.GetService(
- 'CustomFieldService', version='v201502')
-
- # Create custom field objects.
- custom_fields = [
- {
- 'name': 'Customer comments #%s' % uuid.uuid4(),
- 'entityType': 'LINE_ITEM',
- 'dataType': 'STRING',
- 'visibility': 'FULL'
- }, {
- 'name': 'Internal approval status #%s' % uuid.uuid4(),
- 'entityType': 'LINE_ITEM',
- 'dataType': 'DROP_DOWN',
- 'visibility': 'FULL'
- }
- ]
-
- # Add custom fields.
- custom_fields = custom_field_service.createCustomFields(custom_fields)
-
- # Display results.
- for custom_field in custom_fields:
- print ('Custom field with ID \'%s\' and name \'%s\' was created.'
- % (custom_field['id'], custom_field['name']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201502/custom_field_service/deactivate_all_line_item_custom_fields.py
deleted file mode 100755
index a3eeeb65..00000000
--- a/examples/dfp/v201502/custom_field_service/deactivate_all_line_item_custom_fields.py
+++ /dev/null
@@ -1,89 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example deactivates all active line items custom fields.
-
-To determine which custom fields exist, run get_all_custom_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomFieldService.getCustomFieldsByStatement
-Tags: CustomFieldService.performCustomFieldAction
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- custom_field_service = client.GetService(
- 'CustomFieldService', version='v201502')
-
- # Create statement to select only active custom fields that apply to
- # line items.
- values = [
- {
- 'key': 'entityType',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'LINE_ITEM'
- }
- }, {
- 'key': 'isActive',
- 'value': {
- 'xsi_type': 'BooleanValue',
- 'value': 'true'
- }
- }
- ]
- query = 'WHERE entityType = :entityType and isActive = :isActive'
- statement = dfp.FilterStatement(query, values)
-
- custom_fields_deactivated = 0
-
- # Get custom fields by statement.
- while True:
- response = custom_field_service.getCustomFieldsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for custom_field in response['results']:
- print ('Custom field with ID \'%s\' and name \'%s\' will'
- ' be deactivated.' % (custom_field['id'], custom_field['name']))
- result = custom_field_service.performCustomFieldAction(
- {'xsi_type': 'DeactivateCustomFields'}, statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- custom_fields_deactivated += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- if custom_fields_deactivated > 0:
- print 'Number of custom fields deactivated: %s' % custom_fields_deactivated
- else:
- print 'No custom fields were deactivated.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/custom_field_service/get_all_custom_fields.py b/examples/dfp/v201502/custom_field_service/get_all_custom_fields.py
deleted file mode 100755
index 8a23dfd7..00000000
--- a/examples/dfp/v201502/custom_field_service/get_all_custom_fields.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all custom fields.
-
-To create custom fields, run create_custom_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomFieldService.getCustomFieldsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- custom_field_service = client.GetService(
- 'CustomFieldService', version='v201502')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get custom fields by statement.
- while True:
- response = custom_field_service.getCustomFieldsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for custom_field in response['results']:
- print ('Custom field with ID \'%s\' and name \'%s\' was found.'
- % (custom_field['id'], custom_field['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/custom_field_service/get_all_line_item_custom_fields.py b/examples/dfp/v201502/custom_field_service/get_all_line_item_custom_fields.py
deleted file mode 100755
index 4413453a..00000000
--- a/examples/dfp/v201502/custom_field_service/get_all_line_item_custom_fields.py
+++ /dev/null
@@ -1,72 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all custom fields that apply to line items.
-
-To create custom fields, run create_custom_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomFieldService.getCustomFieldsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- custom_field_service = client.GetService(
- 'CustomFieldService', version='v201502')
-
- # Create statement to select only custom fields that apply to line items.
- values = [{
- 'key': 'entityType',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'LINE_ITEM'
- }
- }]
- query = 'WHERE entityType = :entityType'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Get custom fields by statement.
- while True:
- response = custom_field_service.getCustomFieldsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for custom_field in response['results']:
- print ('Custom field with ID \'%s\' and name \'%s\' was found.'
- % (custom_field['id'], custom_field['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/custom_field_service/set_line_item_custom_field_value.py b/examples/dfp/v201502/custom_field_service/set_line_item_custom_field_value.py
deleted file mode 100755
index 6ad309d0..00000000
--- a/examples/dfp/v201502/custom_field_service/set_line_item_custom_field_value.py
+++ /dev/null
@@ -1,160 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example sets custom field values on a line item.
-
-To determine which custom fields exist, run get_all_custom_fields.py.
-To determine which line item exist, run get_all_line_items.py.
-To create custom field options, run create_custom_field_options.py
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomFieldService.getCustomFieldsByStatement
- LineItemService.getLineItemsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the custom fields, custom field option, and line item.
-CUSTOM_FIELD_ID = 'INSERT_CUSTOM_FIELD_ID_HERE'
-DROP_DOWN_CUSTOM_FIELD_ID = 'INSERT_DROP_DOWN_CUSTOM_FIELD_ID_HERE'
-CUSTOM_FIELD_OPTION_ID = 'INSERT_CUSTOM_FIELD_OPTION_ID_HERE'
-LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
-
-
-def main(client, custom_field_id, drop_down_custom_field_id,
- custom_field_option_id, line_item_id):
- # Initialize appropriate services.
- custom_field_service = client.GetService(
- 'CustomFieldService', version='v201502')
-
- line_item_service = client.GetService('LineItemService', version='v201502')
-
- # Create statement to get a custom field.
- custom_field_values = [{
- 'key': 'customFieldId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': custom_field_id
- }
- }]
- custom_field_query = 'WHERE id = :customFieldId'
- custom_field_statement = dfp.FilterStatement(
- custom_field_query, custom_field_values, 1)
-
- # Get custom field.
- custom_field = custom_field_service.getCustomFieldsByStatement(
- custom_field_statement.ToStatement())['results'][0]
-
- # Create statement to get a drop down custom field.
- drop_down_custom_field_values = [{
- 'key': 'dropDownCustomFieldId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': drop_down_custom_field_id
- }
- }]
- drop_down_custom_field_query = 'WHERE id = :dropDownCustomFieldId'
- drop_down_custom_field_statement = dfp.FilterStatement(
- drop_down_custom_field_query, drop_down_custom_field_values, 1)
-
- # Get drop-down custom field.
- drop_down_custom_field = custom_field_service.getCustomFieldsByStatement(
- drop_down_custom_field_statement.ToStatement())['results'][0]
-
- # Create statement to get a line item.
- line_item_values = [{
- 'key': 'lineItemId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': line_item_id
- }
- }]
- line_item_query = 'WHERE id = :lineItemId'
- line_item_statement = dfp.FilterStatement(
- line_item_query, line_item_values, 1)
-
- # Get line item.
- line_item = line_item_service.getLineItemsByStatement(
- line_item_statement.ToStatement())['results'][0]
-
- if custom_field and line_item:
- # Create custom field values.
- custom_field_value = {
- 'customFieldId': custom_field['id'],
- 'xsi_type': 'CustomFieldValue',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'Custom field value'
- }
- }
-
- drop_down_custom_field_value = {
- 'customFieldId': drop_down_custom_field['id'],
- 'xsi_type': 'DropDownCustomFieldValue',
- 'customFieldOptionId': custom_field_option_id,
- }
-
- custom_field_values = [custom_field_value, drop_down_custom_field_value]
-
- old_custom_field_values = []
- if 'customFieldValues' in line_item:
- old_custom_field_values = line_item['customFieldValues']
-
- # Only add existing custom field values for different custom fields than the
- # ones you are setting.
- for old_custom_field_value in old_custom_field_values:
- if (old_custom_field_value['customFieldId'] !=
- custom_field_value['customFieldId']
- and old_custom_field_value['customFieldId'] !=
- drop_down_custom_field_value['customFieldId']):
- custom_field_values.append(old_custom_field_value)
-
- line_item['customFieldValues'] = custom_field_values
-
- # Update the line item on the server.
- line_items = line_item_service.updateLineItems([line_item])
-
- # Display results.
- for line_item in line_items:
- custom_field_value_strings = []
- for value in line_item['customFieldValues']:
- if dfp.DfpClassType(value) == 'CustomFieldValue':
- custom_field_value_string = (
- '{ID: \'%s\', value: \'%s\'}'
- % (value['customFieldId'], value['value']['value']))
- elif dfp.DfpClassType(value) == 'DropDownCustomFieldValue':
- custom_field_value_string = (
- '{ID: \'%s\', custom field option ID: \'%s\'}'
- % (value['customFieldId'], value['customFieldOptionId']))
- custom_field_value_strings.append(custom_field_value_string)
- print ('Line item with ID \'%s\' set with custom field values %s.'
- % (line_item['id'], ','.join(custom_field_value_strings)))
- else:
- print 'Line item or custom field not found.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CUSTOM_FIELD_ID, DROP_DOWN_CUSTOM_FIELD_ID,
- CUSTOM_FIELD_OPTION_ID, LINE_ITEM_ID)
diff --git a/examples/dfp/v201502/custom_field_service/update_custom_fields.py b/examples/dfp/v201502/custom_field_service/update_custom_fields.py
deleted file mode 100755
index 4259b204..00000000
--- a/examples/dfp/v201502/custom_field_service/update_custom_fields.py
+++ /dev/null
@@ -1,79 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates custom field descriptions.
-
-To determine which custom fields exist, run get_all_custom_fields.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomFieldService.updateCustomFields
- CustomFieldService.getCustomFieldByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the ID of the custom field to update.
-CUSTOM_FIELD_ID = 'INSERT_CUSTOM_FIELD_ID_HERE'
-
-
-def main(client, custom_field_id):
- # Initialize appropriate service.
- custom_field_service = client.GetService(
- 'CustomFieldService', version='v201502')
-
- # Create statement to get a custom field.
- values = [{
- 'key': 'customFieldId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': custom_field_id
- }
- }]
- query = 'WHERE id = :customFieldId'
- statement = dfp.FilterStatement(query, values)
-
- # Get custom field.
- custom_fields = custom_field_service.getCustomsFieldByStatement(
- statement.ToStatement())
-
- if custom_fields:
- for custom_field in custom_fields:
- custom_field['description'] += ' Updated.'
-
- # Update the custom field on the server.
- custom_fields = custom_field_service.updateCustomFields(custom_fields)
-
- # Display results.
- for custom_field in custom_fields:
- print (('Custom field with ID \'%s\', name \'%s\', and '
- 'description \'%s\' was updated.')
- % (custom_field['id'], custom_field['name'],
- custom_field['description']))
- else:
- print 'No custom fields found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CUSTOM_FIELD_ID)
diff --git a/examples/dfp/v201502/custom_targeting_service/__init__.py b/examples/dfp/v201502/custom_targeting_service/__init__.py
deleted file mode 100755
index a426ca48..00000000
--- a/examples/dfp/v201502/custom_targeting_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201502/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/dfp/v201502/custom_targeting_service/create_custom_targeting_keys_and_values.py
deleted file mode 100755
index 11c583c6..00000000
--- a/examples/dfp/v201502/custom_targeting_service/create_custom_targeting_keys_and_values.py
+++ /dev/null
@@ -1,136 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates new custom targeting keys and values.
-
-To determine which custom targeting keys and values exist, run
-get_all_custom_targeting_keys_and_values.py. To target these custom targeting
-keys and values, run target_custom_criteria_example.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomTargetingService.createCustomTargetingKeys
- CustomTargetingService.createCustomTargetingValues
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- custom_targeting_service = client.GetService(
- 'CustomTargetingService', version='v201502')
-
- # Create custom targeting key objects.
- keys = [
- {
- 'displayName': 'gender',
- 'name': 'g',
- 'type': 'PREDEFINED'
- },
- {
- 'displayName': 'car model',
- 'name': 'c',
- 'type': 'FREEFORM'
- },
- # Add predefined key that may be use for content targeting.
- {
- 'displayName': 'genre',
- 'name': 'genre',
- 'type': 'PREDEFINED'
- }
- ]
-
- # Add custom targeting keys.
- keys = custom_targeting_service.createCustomTargetingKeys(keys)
-
- # Display results.
- if keys:
- for key in keys:
- print ('A custom targeting key with id \'%s\', name \'%s\', and display '
- 'name \'%s\' was created.' % (key['id'], key['name'],
- key['displayName']))
- else:
- print 'No keys were created.'
-
- # Create custom targeting value objects.
- values = [
- {
- 'customTargetingKeyId': keys['id'],
- 'displayName': 'male',
- # Name is set to 1 so that the actual name can be hidden from website
- # users.
- 'name': '1',
- 'matchType': 'EXACT'
- },
- {
- 'customTargetingKeyId': keys['id'],
- 'displayName': 'female',
- # Name is set to 2 so that the actual name can be hidden from website
- # users.
- 'name': '2',
- 'matchType': 'EXACT'
- },
- {
- 'customTargetingKeyId': keys[1]['id'],
- 'displayName': 'honda civic',
- 'name': 'honda civic',
- 'matchType': 'EXACT'
- },
- {
- 'customTargetingKeyId': keys[1]['id'],
- 'displayName': 'toyota',
- 'name': 'toyota',
- 'matchType': 'EXACT'
- },
- {
- 'customTargetingKeyId': keys[2]['id'],
- 'displayName': 'comedy',
- 'name': 'comedy',
- 'matchType': 'EXACT'
- },
- {
- 'customTargetingKeyId': keys[2]['id'],
- 'displayName': 'drama',
- 'name': 'drama',
- 'matchType': 'EXACT'
- }
- ]
-
- # Add custom targeting values.
- values = custom_targeting_service.createCustomTargetingValues(values)
-
- # Display results.
- if values:
- for value in values:
- print ('A custom targeting value with id \'%s\', belonging to key with id'
- ' \'%s\', name \'%s\', and display name \'%s\' was created.'
- % (value['id'], value['customTargetingKeyId'], value['name'],
- value['displayName']))
- else:
- print 'No values were created.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/custom_targeting_service/delete_custom_targeting_keys.py b/examples/dfp/v201502/custom_targeting_service/delete_custom_targeting_keys.py
deleted file mode 100755
index 6523e417..00000000
--- a/examples/dfp/v201502/custom_targeting_service/delete_custom_targeting_keys.py
+++ /dev/null
@@ -1,85 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example deletes a custom targeting key by its name.
-
-To determine which custom targeting keys exist, run
-get_all_custom_targeting_keys_and_values.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomTargetingService.getCustomTargetingKeysByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-KEY_NAME = 'INSERT_CUSTOM_TARGETING_KEY_NAME_HERE'
-
-
-def main(client, key_name):
- # Initialize appropriate service.
- custom_targeting_service = client.GetService(
- 'CustomTargetingService', version='v201502')
-
- values = [{
- 'key': 'name',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': key_name
- }
- }]
- query = 'WHERE name = :name'
- statement = dfp.FilterStatement(query, values)
-
- deleted_custom_targeting_keys = 0
-
- # Get custom targeting keys.
- while True:
- response = custom_targeting_service.getCustomTargetingKeysByStatement(
- statement.ToStatement())
- if 'results' in response:
- key_ids = [key['id'] for key in response['results']]
- action = {'xsi_type': 'DeleteCustomTargetingKeys'}
- key_query = 'WHERE id IN (%s)' % ', '.join(key_ids)
- key_statement = dfp.FilterStatement(key_query)
-
- # Delete custom targeting keys.
- result = custom_targeting_service.performCustomTargetingKeyAction(
- action, key_statement.ToStatement())
-
- if result and int(result['numChanges']) > 0:
- deleted_custom_targeting_keys += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- if deleted_custom_targeting_keys > 0:
- print ('Number of custom targeting keys deleted: %s'
- % deleted_custom_targeting_keys)
- else:
- print 'No custom targeting keys were deleted.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, KEY_NAME)
diff --git a/examples/dfp/v201502/custom_targeting_service/delete_custom_targeting_values.py b/examples/dfp/v201502/custom_targeting_service/delete_custom_targeting_values.py
deleted file mode 100755
index cece48a7..00000000
--- a/examples/dfp/v201502/custom_targeting_service/delete_custom_targeting_values.py
+++ /dev/null
@@ -1,86 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example deletes custom targeting values for a given custom targeting
-key.
-
-To determine which custom targeting keys and values exist, run
-get_all_custom_targeting_keys_and_values.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: CustomTargetingService.getCustomTargetingValuesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'
-
-
-def main(client, key_id):
- # Initialize appropriate service.
- custom_targeting_service = client.GetService(
- 'CustomTargetingService', version='v201502')
-
- filter_values = [{
- 'key': 'keyId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': key_id
- }
- }]
- query = 'WHERE customTargetingKeyId = :keyId'
- statement = dfp.FilterStatement(query, filter_values)
-
- deleted_custom_targeting_values = 0
-
- # Get custom targeting values.
- while True:
- response = custom_targeting_service.getCustomTargetingValuesByStatement(
- statement.ToStatement())
- if 'results' in response:
- value_ids = [value['id'] for value in response['results']]
- action = {'xsi_type': 'DeleteCustomTargetingValues'}
- value_query = ('WHERE customTargetingKeyId = :keyId '
- 'AND id IN (%s)' % ', '.join(value_ids))
- value_statement = dfp.FilterStatement(value_query, filter_values)
-
- # Delete custom targeting values.
- result = custom_targeting_service.performCustomTargetingValueAction(
- action, value_statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- deleted_custom_targeting_values += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- if deleted_custom_targeting_values > 0:
- print ('Number of custom targeting values deleted: %s'
- % deleted_custom_targeting_values)
- else:
- print 'No custom targeting values were deleted.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, KEY_ID)
diff --git a/examples/dfp/v201502/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201502/custom_targeting_service/get_all_custom_targeting_keys_and_values.py
deleted file mode 100755
index 814fd723..00000000
--- a/examples/dfp/v201502/custom_targeting_service/get_all_custom_targeting_keys_and_values.py
+++ /dev/null
@@ -1,90 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all custom targeting keys and the values.
-
-To create custom targeting keys and values, run
-create_custom_targeting_keys_and_values.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- custom_targeting_service = client.GetService(
- 'CustomTargetingService', version='v201502')
-
- # Create statement to get all targeting keys.
- targeting_key_statement = dfp.FilterStatement()
-
- all_keys = []
-
- # Get custom targeting keys by statement.
- while True:
- response = custom_targeting_service.getCustomTargetingKeysByStatement(
- targeting_key_statement.ToStatement())
- if 'results' in response:
- all_keys.extend(response['results'])
- targeting_key_statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- if all_keys:
- # Create map of custom targeting key id to custom targeting values.
- key_value_map = {}
-
- # Create statement to get all targeting values.
- query = ('WHERE customTargetingKeyId IN (%s)'
- % ', '.join([key['id'] for key in all_keys]))
- targeting_value_statement = dfp.FilterStatement(query)
-
- # Get custom targeting values by statement.
- while True:
- response = custom_targeting_service.getCustomTargetingValuesByStatement(
- targeting_value_statement.ToStatement())
- if 'results' in response:
- for key in all_keys:
- for value in response['results']:
- if key['id'] == value['customTargetingKeyId']:
- if key['id'] not in key_value_map.keys():
- key_value_map[key['id']] = []
- key_value_map[key['id']].append(value)
- targeting_value_statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Display results.
- for key in all_keys:
- print ('Custom targeting key with id \'%s\', name \'%s\', display name '
- '\'%s\', and type \'%s\' was found.'
- %(key['id'], key['name'], key['displayName'], key['type']))
- if key['id'] in key_value_map.keys():
- for value in key_value_map[key['id']]:
- print ('\tCustom targeting value with id \'%s\', name \'%s\', and '
- 'display name \'%s\' was found.'
- % (value['id'], value['name'], value['displayName']))
- else:
- print 'No keys were found.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
-
diff --git a/examples/dfp/v201502/custom_targeting_service/get_custom_targeting_keys_by_statement.py b/examples/dfp/v201502/custom_targeting_service/get_custom_targeting_keys_by_statement.py
deleted file mode 100755
index 07b44b4f..00000000
--- a/examples/dfp/v201502/custom_targeting_service/get_custom_targeting_keys_by_statement.py
+++ /dev/null
@@ -1,63 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all predefined custom targeting keys.
-
-To create custom targeting keys, run create_custom_targeting_keys_and_values.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- custom_targeting_service = client.GetService(
- 'CustomTargetingService', version='v201502')
-
- values = [{
- 'key': 'type',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'PREDEFINED'
- }
- }]
- query = 'WHERE type = :type'
- statement = dfp.FilterStatement(query, values)
-
- # Get custom targeting keys by statement.
- while True:
- response = custom_targeting_service.getCustomTargetingKeysByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for key in response['results']:
- print ('Custom targeting key with id \'%s\', name \'%s\', display name '
- '\'%s\', and type \'%s\' was found.'
- % (key['id'], key['name'], key['displayName'], key['type']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/custom_targeting_service/get_custom_targeting_values_by_statement.py b/examples/dfp/v201502/custom_targeting_service/get_custom_targeting_values_by_statement.py
deleted file mode 100755
index 112a48b3..00000000
--- a/examples/dfp/v201502/custom_targeting_service/get_custom_targeting_values_by_statement.py
+++ /dev/null
@@ -1,67 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets custom targeting values for the given predefined custom
-targeting key.
-
-To create custom targeting values, run
-create_custom_targeting_keys_and_values.py. To determine which custom
-targeting keys exist, run get_all_custom_targeting_keys_and_values.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'
-
-
-def main(client, key_id):
- # Initialize appropriate service.
- custom_targeting_service = client.GetService(
- 'CustomTargetingService', version='v201502')
-
- values = [{
- 'key': 'keyId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': key_id
- }
- }]
- query = 'WHERE customTargetingKeyId = :keyId'
- statement = dfp.FilterStatement(query, values)
-
- # Get custom targeting values by statement.
- while True:
- response = custom_targeting_service.getCustomTargetingValuesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for value in response['results']:
- print ('Custom targeting value with id \'%s\', name \'%s\', and display'
- ' name \'%s\' was found.'
- % (value['id'], value['name'], value['displayName']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CUSTOM_TARGETING_KEY_ID)
diff --git a/examples/dfp/v201502/custom_targeting_service/update_custom_targeting_keys.py b/examples/dfp/v201502/custom_targeting_service/update_custom_targeting_keys.py
deleted file mode 100755
index f23fae91..00000000
--- a/examples/dfp/v201502/custom_targeting_service/update_custom_targeting_keys.py
+++ /dev/null
@@ -1,72 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates the display name of a single custom targeting key.
-
-To determine which custom targeting keys exist, run
-get_all_custom_targeting_keys_and_values.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'
-
-
-def main(client, key_id):
- # Initialize appropriate service.
- custom_targeting_service = client.GetService(
- 'CustomTargetingService', version='v201502')
-
- values = [{
- 'key': 'keyId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': key_id
- }
- }]
- query = 'WHERE id = :keyId'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get custom targeting keys by statement.
- response = custom_targeting_service.getCustomTargetingKeysByStatement(
- statement.ToStatement())
-
- # Update each local custom targeting key object by changing its display name.
- if 'results' in response:
- updated_keys = []
- for key in response['results']:
- if not key['displayName']:
- key['displayName'] = key['name']
- key['displayName'] += ' (Deprecated)'
- updated_keys.append(key)
- keys = custom_targeting_service.updateCustomTargetingKeys(updated_keys)
-
- # Display results.
- if keys:
- for key in keys:
- print ('Custom targeting key with id \'%s\', name \'%s\', display name '
- '\'%s\', and type \'%s\' was updated.'
- % (key['id'], key['name'], key['displayName'], key['type']))
- else:
- print 'No custom targeting keys were found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CUSTOM_TARGETING_KEY_ID)
diff --git a/examples/dfp/v201502/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201502/custom_targeting_service/update_custom_targeting_values.py
deleted file mode 100755
index 2d705319..00000000
--- a/examples/dfp/v201502/custom_targeting_service/update_custom_targeting_values.py
+++ /dev/null
@@ -1,78 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates the display name of the custom targeting values
-belonging to a custom targeting key.
-
-To determine which custom targeting keys exist, run
-get_all_custom_targeting_keys_and_values.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'
-
-
-def main(client, key_id):
- # Initialize appropriate service.
- custom_targeting_service = client.GetService(
- 'CustomTargetingService', version='v201502')
-
- values = [{
- 'key': 'keyId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': key_id
- }
- }]
- query = 'WHERE customTargetingKeyId = :keyId'
- statement = dfp.FilterStatement(query, values)
-
- while True:
- # Get custom targeting values by statement.
- response = custom_targeting_service.getCustomTargetingValuesByStatement(
- statement.ToStatement())
-
- # Update each local custom targeting value object by changing its name.
- if 'results' in response:
- updated_values = []
- for value in response['results']:
- if not value['displayName']:
- value['displayName'] = value['name']
- value['displayName'] += ' (Deprecated)'
- updated_values.append(value)
- values = custom_targeting_service.updateCustomTargetingValues(
- updated_values)
-
- # Display results.
- for value in values:
- print ('Custom targeting value with id \'%s\', name \'%s\', and display'
- ' name \'%s\' was updated.'
- % (value['id'], value['name'], value['displayName']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- if response['totalResultSetSize'] == 0:
- print 'No custom targeting values were updated.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CUSTOM_TARGETING_KEY_ID)
diff --git a/examples/dfp/v201502/exchange_rate_service/__init__.py b/examples/dfp/v201502/exchange_rate_service/__init__.py
deleted file mode 100755
index a426ca48..00000000
--- a/examples/dfp/v201502/exchange_rate_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201502/exchange_rate_service/create_exchange_rates.py b/examples/dfp/v201502/exchange_rate_service/create_exchange_rates.py
deleted file mode 100755
index 996b5628..00000000
--- a/examples/dfp/v201502/exchange_rate_service/create_exchange_rates.py
+++ /dev/null
@@ -1,60 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates an exchange rate.
-
-To determine which exchange rates exist, run get_all_exchange_rates.py.
-
-
-Tags: ExchangeRateService.createExchangeRates
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- exchange_rate_service = client.GetService('ExchangeRateService',
- version='v201502')
-
- # Create a new fixed exchange rate with currency code 'AUD', with direction
- # FROM_NETWORK with a value of 1.5.
- exchange_rate = {
- 'currencyCode': 'AUD',
- 'direction': 'FROM_NETWORK',
- 'exchangeRate': long(15000000000),
- 'refreshRate': 'FIXED'
- }
-
- created_exchange_rate = exchange_rate_service.createExchangeRates(
- [exchange_rate])[0]
-
- print ('Exchange rate with id \'%s,\' currency code \'%s,\' '
- 'direction \'%s,\' and exchange rate \'%.2f\' '
- 'was created.' % (created_exchange_rate['id'],
- created_exchange_rate['currencyCode'],
- created_exchange_rate['direction'],
- (float(created_exchange_rate['exchangeRate']) /
- 10000000000)))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/exchange_rate_service/get_all_exchange_rates.py b/examples/dfp/v201502/exchange_rate_service/get_all_exchange_rates.py
deleted file mode 100755
index 6002f471..00000000
--- a/examples/dfp/v201502/exchange_rate_service/get_all_exchange_rates.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all exchange rates.
-
-To create exchange rates, run create_exchange_rates.py.
-
-Tags: ExchangeRateService.getExchangeRatesByStatement
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- exchange_rate_service = client.GetService('ExchangeRateService',
- version='v201502')
-
- # Create a filter statement.
- statement = dfp.FilterStatement('ORDER BY id ASC')
-
- # Get all exchange rates by statement.
- while True:
- response = exchange_rate_service.getExchangeRatesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for exchange_rate in response['results']:
- print ('Exchange rate with id \'%s,\' currency code \'%s,\' '
- 'direction \'%s,\' and exchange rate \'%.2f\' '
- 'was found.' % (exchange_rate['id'],
- exchange_rate['currencyCode'],
- exchange_rate['direction'],
- (float(exchange_rate['exchangeRate']) /
- 10000000000)))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/exchange_rate_service/get_exchange_rates_by_currency_code.py b/examples/dfp/v201502/exchange_rate_service/get_exchange_rates_by_currency_code.py
deleted file mode 100755
index c2ff187c..00000000
--- a/examples/dfp/v201502/exchange_rate_service/get_exchange_rates_by_currency_code.py
+++ /dev/null
@@ -1,73 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets the exchange rate for a specific currency code.
-
-To create exchange rates, run create_exchange_rates.py.
-
-Tags: ExchangeRateService.getExchangeRatesByStatement
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-CURRENCY_CODE = 'INSERT_CURRENCY_CODE_HERE'
-
-
-def main(client, currency_code):
- # Initialize appropriate service.
- exchange_rate_service = client.GetService('ExchangeRateService',
- version='v201502')
-
- # Create a statement to get exchange rates for the specified currency code.
- values = [{
- 'key': 'currencyCode',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': currency_code
- }
- }]
- query = 'WHERE currencyCode = :currencyCode'
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Get rate cards by statement.
- while True:
- response = exchange_rate_service.getExchangeRatesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for exchange_rate in response['results']:
- print ('Exchange rate with id \'%s,\' currency code \'%s,\' '
- 'direction \'%s,\' and exchange rate \'%.2f\' '
- 'was found.' % (exchange_rate['id'],
- exchange_rate['currencyCode'],
- exchange_rate['direction'],
- (float(exchange_rate['exchangeRate']) /
- 10000000000)))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, CURRENCY_CODE)
diff --git a/examples/dfp/v201502/exchange_rate_service/update_exchange_rates.py b/examples/dfp/v201502/exchange_rate_service/update_exchange_rates.py
deleted file mode 100755
index b390da34..00000000
--- a/examples/dfp/v201502/exchange_rate_service/update_exchange_rates.py
+++ /dev/null
@@ -1,79 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates the value of an exchange rate.
-
-To create exchange rates, run create_exchange_rates.py.
-
-Tags: ExchangeRateService.getExchangeRatesByStatement
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-EXCHANGE_RATE_ID = 'INSERT_EXCHANGE_RATE_ID_HERE'
-
-
-def main(client, exchange_rate_id):
- # Initialize appropriate service.
- exchange_rate_service = client.GetService('ExchangeRateService',
- version='v201502')
-
- # Create a statement to get an exchange rate by its ID.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': exchange_rate_id
- }
- }]
- query = 'WHERE id = :id'
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get rate cards by statement.
- response = exchange_rate_service.getExchangeRatesByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- exchange_rate = response['results'][0]
-
- # Update the exchange rate value to 1.5.
- exchange_rate['exchangeRate'] = long(15000000000)
-
- exchange_rates = exchange_rate_service.updateExchangeRates([exchange_rate])
-
- if exchange_rates:
- for exchange_rate in exchange_rates:
- print ('Exchange rate with id \'%s,\' currency code \'%s,\' '
- 'direction \'%s,\' and exchange rate \'%.2f\' '
- 'was updated.' % (exchange_rate['id'],
- exchange_rate['currencyCode'],
- exchange_rate['direction'],
- (float(exchange_rate['exchangeRate']) /
- 10000000000)))
- else:
- print 'No exchange rates were updated.'
- else:
- print 'No exchange rates found to update.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, EXCHANGE_RATE_ID)
diff --git a/examples/dfp/v201502/forecast_service/get_availability_forecast.py b/examples/dfp/v201502/forecast_service/get_availability_forecast.py
deleted file mode 100755
index 3186d647..00000000
--- a/examples/dfp/v201502/forecast_service/get_availability_forecast.py
+++ /dev/null
@@ -1,130 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets a forecast for a prospective line item.
-
-The prospective line item targets the entire network. The targeting can be
-modified to determine forecasts for other criteria such as custom criteria
-targeting (in addition to targeting the whole network). See
-create_line_items.py for an example of how to create more complex targeting.
-
-Tags: ForecastService.getAvailabilityForecast
-Tags: NetworkService.getCurrentNetwork
-"""
-
-__author__ = 'Nicholas Chen'
-
-from datetime import date
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- forecast_service = client.GetService('ForecastService', version='v201502')
- network_service = client.GetService('NetworkService', version='v201502')
-
- # get the root ad unit ID to target the entire network.
- root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId']
-
- # Create prospective line item.
- line_item = {
- 'targeting': {
- 'inventoryTargeting': {
- 'targetedAdUnits': [
- {
- 'includeDescendants': True,
- 'adUnitId': root_ad_unit_id,
- }
- ]
- }
- },
- 'creativePlaceholders': [
- {
- 'size': {
- 'width': '300',
- 'height': '250'
- }
- },
- {
- 'size': {
- 'width': '120',
- 'height': '600'
- }
- }
- ],
- 'lineItemType': 'SPONSORSHIP',
- 'startDateTimeType': 'IMMEDIATELY',
- 'endDateTime': {
- 'date': {
- 'year': str(date.today().year + 1),
- 'month': '9',
- 'day': '30'
- },
- 'hour': '0',
- 'minute': '0',
- 'second': '0',
- 'timeZoneID': 'America/New_York'
- },
- 'costType': 'CPM',
- 'costPerUnit': {
- 'currencyCode': 'USD',
- 'microAmount': '2000000'
- },
- 'primaryGoal': {
- 'units': '50',
- 'unitType': 'IMPRESSIONS',
- 'goalType': 'DAILY'
- },
- 'contractedUnitsBought': '100',
- 'creativeRotationType': 'EVEN',
- 'discountType': 'PERCENTAGE',
- }
-
- prospective_line_item = {
- 'lineItem': line_item
- }
-
- # Set forecasting options.
- forecast_options = {
- 'includeContendingLineItems': True,
- 'includeTargetingCriteriaBreakdown': True,
- }
-
- # Get forecast.
- forecast = forecast_service.getAvailabilityForecast(
- prospective_line_item, forecast_options)
- matched = long(forecast['matchedUnits'])
- available_percent = (((long(forecast['availableUnits'])/
- (matched * 1.0)) * 100)
- if matched != 0 else 0)
- contending_line_items = ([] if 'contendingLineItems' not in forecast
- else forecast['contendingLineItems'])
-
- # Display results.
- print '%s %s matched.' % (matched, forecast['unitType'].lower())
- print '%s%% %s available.' % (available_percent, forecast['unitType'].lower())
- print '%d contending line items.' % len(contending_line_items)
-
- if 'possibleUnits' in forecast and matched:
- possible_percent = (long(forecast['possibleUnits'])/(matched * 1.0)) * 100
- print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower())
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/forecast_service/get_availability_forecast_for_line_item.py b/examples/dfp/v201502/forecast_service/get_availability_forecast_for_line_item.py
deleted file mode 100755
index 16ccd4cd..00000000
--- a/examples/dfp/v201502/forecast_service/get_availability_forecast_for_line_item.py
+++ /dev/null
@@ -1,65 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets an availability forecast for an existing line item.
-
-To determine which line items exist, run get_all_line_items.py.
-
-Tags: ForecastService.getAvailabilityForecastById
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the line item to get a forecast for.
-LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
-
-
-def main(client, line_item_id):
- # Initialize appropriate service.
- forecast_service = client.GetService('ForecastService', version='v201502')
-
- # Set forecasting options.
- forecast_options = {
- 'includeContendingLineItems': True,
- 'includeTargetingCriteriaBreakdown': True,
- }
-
- # Get forecast for line item.
- forecast = forecast_service.getAvailabilityForecastById(
- line_item_id, forecast_options)
- matched = long(forecast['matchedUnits'])
- available_percent = (((long(forecast['availableUnits'])/
- (matched * 1.0)) * 100)
- if matched != 0 else 0)
- contending_line_items = ([] if 'contendingLineItems' not in forecast
- else forecast['contendingLineItems'])
-
- # Display results.
- print '%s %s matched.' % (matched, forecast['unitType'].lower())
- print '%s%% %s available.' % (available_percent, forecast['unitType'].lower())
- print '%d contending line items.' % len(contending_line_items)
-
- if 'possibleUnits' in forecast and matched:
- possible_percent = (long(forecast['possibleUnits'])/(matched * 1.0)) * 100
- print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower())
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, LINE_ITEM_ID)
diff --git a/examples/dfp/v201502/forecast_service/get_delivery_forecast_for_line_items.py b/examples/dfp/v201502/forecast_service/get_delivery_forecast_for_line_items.py
deleted file mode 100755
index 877be0ec..00000000
--- a/examples/dfp/v201502/forecast_service/get_delivery_forecast_for_line_items.py
+++ /dev/null
@@ -1,54 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets a delivery forecast for two existing line items.
-
-To determine which line items exist, run get_all_line_items.py.
-
-Tags: ForecastService.getDeliveryForecastByIds
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the line items to get forecasts for.
-LINE_ITEM_ID_1 = 'INSERT_LINE_ITEM_ID_1_HERE'
-LINE_ITEM_ID_2 = 'INSERT_LINE_ITEM_ID_2_HERE'
-
-
-def main(client, line_item_id1, line_item_id2):
- # Initialize appropriate service.
- forecast_service = client.GetService('ForecastService', version='v201502')
-
- # Get forecast for line item.
- forecast = forecast_service.getDeliveryForecastByIds(
- [line_item_id1, line_item_id2], None)
-
- for single_forecast in forecast['lineItemDeliveryForecasts']:
- unit_type = single_forecast['unitType']
- print ('Forecast for line item %d:%n%t%d %s matched%n%t%d %s delivered%n%t'
- '%d %s predicted%n' % (
- single_forecast['lineItemId'], single_forecast['matchedUnits'],
- unit_type, single_forecast['deliveredUnits'], unit_type,
- single_forecast['predictedDeliveryUnits'], unit_type))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, LINE_ITEM_ID_1, LINE_ITEM_ID_2)
diff --git a/examples/dfp/v201502/inventory_service/__init__.py b/examples/dfp/v201502/inventory_service/__init__.py
deleted file mode 100755
index a426ca48..00000000
--- a/examples/dfp/v201502/inventory_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201502/inventory_service/archive_ad_units.py b/examples/dfp/v201502/inventory_service/archive_ad_units.py
deleted file mode 100755
index eac46431..00000000
--- a/examples/dfp/v201502/inventory_service/archive_ad_units.py
+++ /dev/null
@@ -1,83 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example archives ad units.
-
-The parent ad unit and all ad units underneath it will be archived. To create ad
-units, run create_ad_units.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: InventoryService.getAdUnitsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-PARENT_AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE'
-
-
-def main(client, parent_id):
- # Initialize appropriate service.
- inventory_service = client.GetService('InventoryService', version='v201502')
-
- # Create a query to select ad units under the parent ad unit and the parent ad
- # unit.
- values = [{
- 'key': 'parentId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': parent_id
- }
- }]
- query = 'WHERE parentId = :parentId or id = :parentId'
- statement = dfp.FilterStatement(query, values)
-
- ad_units_archived = 0
-
- # Get ad units by statement.
- while True:
- response = inventory_service.getAdUnitsByStatement(
- statement.ToStatement())
- if 'results' in response:
- for ad_unit in response['results']:
- print ('Ad unit with ID \'%s\' and name \'%s\' will be archived.'
- % (ad_unit['id'], ad_unit['name']))
- # Perform action.
- result = inventory_service.performAdUnitAction(
- {'xsi_type': 'ArchiveAdUnits'}, statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- ad_units_archived += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Display results.
- if ad_units_archived > 0:
- print 'Number of ad units archived: %s' % ad_units_archived
- else:
- print 'No ad units were archived.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PARENT_AD_UNIT_ID)
diff --git a/examples/dfp/v201502/inventory_service/create_ad_units.py b/examples/dfp/v201502/inventory_service/create_ad_units.py
deleted file mode 100755
index 6aaab080..00000000
--- a/examples/dfp/v201502/inventory_service/create_ad_units.py
+++ /dev/null
@@ -1,74 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new ad units.
-
-To determine which ad units exist, run get_all_ad_units.py
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: InventoryService.createAdUnits
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-PARENT_AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE'
-
-
-def main(client, parent_id):
- # Initialize appropriate service.
- inventory_service = client.GetService('InventoryService', version='v201502')
-
- # Create ad unit size.
- ad_unit_size = {
- 'size': {
- 'width': '300',
- 'height': '250'
- },
- 'environmentType': 'BROWSER'
- }
-
- # Create ad unit objects.
- ad_unit = {
- 'name': 'Ad_unit_%s' % uuid.uuid4(),
- 'parentId': parent_id,
- 'description': 'Ad unit description.',
- 'targetWindow': 'BLANK',
- 'targetPlatform': 'WEB',
- 'adUnitSizes': [ad_unit_size]
- }
-
- # Add ad units.
- ad_units = inventory_service.createAdUnits([ad_unit])
-
- # Display results.
- for ad_unit in ad_units:
- print ('Ad unit with ID \'%s\' and name \'%s\' was created.'
- % (ad_unit['id'], ad_unit['name']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PARENT_AD_UNIT_ID)
diff --git a/examples/dfp/v201502/inventory_service/get_ad_unit_hierarchy.py b/examples/dfp/v201502/inventory_service/get_ad_unit_hierarchy.py
deleted file mode 100755
index 4863f219..00000000
--- a/examples/dfp/v201502/inventory_service/get_ad_unit_hierarchy.py
+++ /dev/null
@@ -1,118 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code gets the ad unit hierarchy and displays it as a tree.
-
-To create ad units, run create_ad_units.py
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: InventoryService.getAdUnitsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- inventory_service = client.GetService('InventoryService', version='v201502')
- statement = dfp.FilterStatement()
-
- all_ad_units = []
- # Get ad units by statement.
- while True:
- response = inventory_service.getAdUnitsByStatement(
- statement.ToStatement())
- if 'results' in response:
- all_ad_units.extend(response['results'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Find the root ad unit. root_ad_unit can also be set to child unit to only
- # build and display a portion of the tree.
- query = 'WHERE parentId IS NULL'
- root_statement = dfp.FilterStatement(query)
- response = inventory_service.getAdUnitsByStatement(
- root_statement.ToStatement())
- root_ad_unit = response['results']
-
- if root_ad_unit:
- BuildAndDisplayAdUnitTree(root_ad_unit, all_ad_units)
- else:
- print 'Could not build tree. No root ad unit found.'
-
-
-def DisplayAdUnitTree(root_ad_unit, ad_unit_tree, depth=0):
- """Helper for displaying ad unit tree.
-
- Args:
- root_ad_unit: dict the root ad unit.
- ad_unit_tree: dict the tree of ad units.
- [optional]
- depth: int the depth the tree has reached.
- """
- print '%s%s (%s)' % (GenerateTab(depth), root_ad_unit['name'],
- root_ad_unit['id'])
- if root_ad_unit['id'] in ad_unit_tree:
- for child in ad_unit_tree[root_ad_unit['id']]:
- DisplayAdUnitTree(child, ad_unit_tree, depth+1)
-
-
-def GenerateTab(depth):
- """Generate tabs to represent branching to children.
-
- Args:
- depth: int the depth the tree has reached.
-
- Returns:
- string inserted in front of the root unit.
- """
- tab_list = []
- if depth > 0:
- tab_list.append(' ')
- tab_list.append('| ' * depth)
- tab_list.append('+--')
- return ''.join(tab_list)
-
-
-def BuildAndDisplayAdUnitTree(root_ad_unit, all_ad_units):
- """Create an ad unit tree and display it.
-
- Args:
- root_ad_unit: dict the root ad unit to build the tree under.
- all_ad_units: list the list of all ad units to build the tree with.
- """
- tree = {}
- for ad_unit in all_ad_units:
- if 'parentId' in ad_unit:
- if ad_unit['parentId'] not in tree:
- tree[ad_unit['parentId']] = []
- tree[ad_unit['parentId']].append(ad_unit)
-
- DisplayAdUnitTree(root_ad_unit, tree)
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/inventory_service/get_all_ad_unit_sizes.py b/examples/dfp/v201502/inventory_service/get_all_ad_unit_sizes.py
deleted file mode 100755
index a6a0e0c0..00000000
--- a/examples/dfp/v201502/inventory_service/get_all_ad_unit_sizes.py
+++ /dev/null
@@ -1,57 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all ad unit sizes defined in a network.
-
-To create ad units, run create_ad_units.py
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: InventoryService.getAdUnitSizesByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- inventory_service = client.GetService('InventoryService', version='v201502')
- statement = dfp.FilterStatement()
-
- # Get ad units by statement.
- while True:
- response = inventory_service.getAdUnitSizesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for ad_unit_size in response['results']:
- print ('Ad unit size of dimensions %s was found.' %
- (ad_unit_size['fullDisplayString']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/inventory_service/get_all_ad_units.py b/examples/dfp/v201502/inventory_service/get_all_ad_units.py
deleted file mode 100755
index a18169f7..00000000
--- a/examples/dfp/v201502/inventory_service/get_all_ad_units.py
+++ /dev/null
@@ -1,59 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all ad units within a network.
-
-To create ad units, run create_ad_units.py
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: InventoryService.getAdUnitsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- inventory_service = client.GetService('InventoryService', version='v201502')
- statement = dfp.FilterStatement()
-
- # Get ad units by statement.
- while True:
- response = inventory_service.getAdUnitsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for ad_unit in response['results']:
- print ('Ad unit with ID \'%s\' and name \'%s\' was found.'
- % (ad_unit['id'], ad_unit['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/inventory_service/get_top_level_ad_units.py b/examples/dfp/v201502/inventory_service/get_top_level_ad_units.py
deleted file mode 100755
index 086380a7..00000000
--- a/examples/dfp/v201502/inventory_service/get_top_level_ad_units.py
+++ /dev/null
@@ -1,72 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all child ad units of the effective root ad unit.
-
-To create ad units, run create_ad_units.py
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: InventoryService.getAdUnitsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- inventory_service = client.GetService('InventoryService', version='v201502')
- network_service = client.GetService('NetworkService', version='v201502')
-
- root_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId']
-
- # Create a statement to select the children of the effective root ad unit.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': root_id
- }
- }]
- query = 'WHERE parentId = :id'
- statement = dfp.FilterStatement(query, values)
-
- # Get ad units by statement.
- while True:
- response = inventory_service.getAdUnitsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for ad_unit in response['results']:
- print ('Ad unit with ID \'%s\' and name \'%s\' was found.'
- % (ad_unit['id'], ad_unit['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/inventory_service/update_ad_units.py b/examples/dfp/v201502/inventory_service/update_ad_units.py
deleted file mode 100755
index f37e90d7..00000000
--- a/examples/dfp/v201502/inventory_service/update_ad_units.py
+++ /dev/null
@@ -1,91 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates ad unit sizes by adding a banner ad size.
-
-To determine which ad units exist, run get_all_ad_units.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: InventoryService.getAdUnit
-Tags: InventoryService.updateAdUnits
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-# Set the ID of the ad unit to get.
-AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE'
-
-
-def main(client, ad_unit_id):
- # Initialize appropriate service.
- inventory_service = client.GetService('InventoryService', version='v201502')
-
- # Create a statement to select a single ad unit by ID.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': ad_unit_id
- }
- }]
- query = 'WHERE id = :id'
- statement = dfp.FilterStatement(query, values)
-
- # Get ad units by statement.
- response = inventory_service.getAdUnitsByStatement(
- statement.ToStatement())
-
- # Add the size 468x60 to the ad unit.
- ad_unit_size = {
- 'size': {
- 'width': '468',
- 'height': '60'
- },
- 'environmentType': 'BROWSER'
- }
-
- if 'results' in response:
- updated_ad_units = []
- for ad_unit in response['results']:
- if 'adUnitSizes' not in ad_unit:
- ad_unit['adUnitSizes'] = []
- ad_unit['adUnitSizes'].append(ad_unit_size)
- updated_ad_units.append(ad_unit)
-
- # Update ad unit on the server.
- ad_units = inventory_service.updateAdUnits(updated_ad_units)
-
- # Display results.
- for ad_unit in ad_units:
- ad_unit_sizes = ['{%s x %s}' % (size['size']['width'],
- size['size']['height'])
- for size in ad_unit['adUnitSizes']]
- print ('Ad unit with ID \'%s\', name \'%s\', and sizes [%s] was updated'
- % (ad_unit['id'], ad_unit['name'], ','.join(ad_unit_sizes)))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, AD_UNIT_ID)
diff --git a/examples/dfp/v201502/label_service/__init__.py b/examples/dfp/v201502/label_service/__init__.py
deleted file mode 100755
index a426ca48..00000000
--- a/examples/dfp/v201502/label_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201502/label_service/create_labels.py b/examples/dfp/v201502/label_service/create_labels.py
deleted file mode 100755
index 8d8d80d6..00000000
--- a/examples/dfp/v201502/label_service/create_labels.py
+++ /dev/null
@@ -1,56 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new labels.
-
-To determine which labels exist, run get_all_labels.py. This feature is only
-available to DFP premium solution networks."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- label_service = client.GetService('LabelService', version='v201502')
-
- # Create label objects.
- labels = []
- for _ in xrange(5):
- label = {
- 'name': 'Label #%s' % uuid.uuid4(),
- 'isActive': 'true',
- 'types': ['COMPETITIVE_EXCLUSION']
- }
- labels.append(label)
-
- # Add Labels.
- labels = label_service.createLabels(labels)
-
- # Display results.
- for label in labels:
- print ('Label with id \'%s\', name \'%s\', and types {%s} was found.'
- % (label['id'], label['name'], ','.join(label['types'])))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/label_service/deactivate_labels.py b/examples/dfp/v201502/label_service/deactivate_labels.py
deleted file mode 100755
index 91529f52..00000000
--- a/examples/dfp/v201502/label_service/deactivate_labels.py
+++ /dev/null
@@ -1,71 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example deactivates all active Labels.
-
-To determine which labels exist, run get_all_labels.py. This feature is only
-available to DFP premium solution networks."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- label_service = client.GetService('LabelService', version='v201502')
-
- # Create query.
- values = [{
- 'key': 'isActive',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'true'
- }
- }]
- query = 'WHERE isActive = :isActive'
- statement = dfp.FilterStatement(query, values)
-
- labels_deactivated = 0
-
- # Get labels by statement.
- while True:
- response = label_service.getLabelsByStatement(statement.ToStatement())
- if 'results' in response:
- for label in response['results']:
- print ('Label with id \'%s\' and name \'%s\' will be '
- 'deactivated.' % (label['id'], label['name']))
- # Perform action.
- result = label_service.performLabelAction(
- {'xsi_type': 'DeactivateLabels'}, statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- labels_deactivated += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Display results.
- if labels_deactivated > 0:
- print 'Number of labels deactivated: %s' % labels_deactivated
- else:
- print 'No labels were deactivated.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/label_service/get_all_labels.py b/examples/dfp/v201502/label_service/get_all_labels.py
deleted file mode 100755
index 97290f58..00000000
--- a/examples/dfp/v201502/label_service/get_all_labels.py
+++ /dev/null
@@ -1,54 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all labels.
-
-To create labels, run create_labels.py. This feature is only available to DFP
-premium solution networks."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- label_service = client.GetService('LabelService', version='v201502')
-
- # Create statement to get all labels
- statement = dfp.FilterStatement()
-
- # Get labels by statement.
- while True:
- response = label_service.getLabelsByStatement(statement.ToStatement())
- if 'results' in response:
- # Display results.
- for label in response['results']:
- print ('Label with id \'%s\' and name \'%s\' was found.'
- % (label['id'], label['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/label_service/get_labels_by_statement.py b/examples/dfp/v201502/label_service/get_labels_by_statement.py
deleted file mode 100755
index ffba7047..00000000
--- a/examples/dfp/v201502/label_service/get_labels_by_statement.py
+++ /dev/null
@@ -1,55 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all labels ordered by name.
-
-To create a label, run create_label.py. This feature is only available to DFP
-premium solution networks.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- label_service = client.GetService('LabelService', version='v201502')
-
- # Create statement to get all labels
- statement = dfp.FilterStatement('ORDER BY name')
-
- # Get labels by statement.
- while True:
- response = label_service.getLabelsByStatement(statement.ToStatement())
- if 'results' in response:
- # Display results.
- for label in response['results']:
- print ('Label with id \'%s\' and name \'%s\' was found.'
- % (label['id'], label['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/label_service/update_labels.py b/examples/dfp/v201502/label_service/update_labels.py
deleted file mode 100755
index b4a205ed..00000000
--- a/examples/dfp/v201502/label_service/update_labels.py
+++ /dev/null
@@ -1,71 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates the description of a single label.
-
-To determine which labels exist, run get_all_labels.py. This feature is only
-available to DFP premium solution networks."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-LABEL_ID = 'INSERT_LABEL_ID_HERE'
-
-
-def main(client, label_id):
- # Initialize appropriate service.
- label_service = client.GetService('LabelService', version='v201502')
-
- # Create a statement to select only active labels.
- values = [
- {
- 'key': 'labelId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': label_id
- }
- }
- ]
- query = 'WHERE id = :labelId'
- statement = dfp.FilterStatement(query, values)
-
- # Get labels by filter.
- response = label_service.getLabelsByStatement(statement.ToStatement())
-
- if 'results' in response:
- # Update each local label object by changing the description.
- updated_labels = []
- for label in response['results']:
- label['description'] = 'These labels are updated.'
- updated_labels.append(label)
-
- # Update labels remotely.
- labels = label_service.updateLabels(updated_labels)
-
- for label in labels:
- print ('Label with id \'%s\' and name \'%s\' was updated.'
- % (label['id'], label['name']))
- else:
- print 'No labels found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, LABEL_ID)
-
diff --git a/examples/dfp/v201502/line_item_creative_association_service/__init__.py b/examples/dfp/v201502/line_item_creative_association_service/__init__.py
deleted file mode 100755
index a426ca48..00000000
--- a/examples/dfp/v201502/line_item_creative_association_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201502/line_item_creative_association_service/create_licas.py b/examples/dfp/v201502/line_item_creative_association_service/create_licas.py
deleted file mode 100755
index 3229a437..00000000
--- a/examples/dfp/v201502/line_item_creative_association_service/create_licas.py
+++ /dev/null
@@ -1,58 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new line item creative associations (LICAs) for an
-existing line item and a set of creative ids.
-
-To determine which LICAs exist, run get_all_licas.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the line item ID and creative IDs to associate.
-LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
-CREATIVE_IDS = ['INSERT_CREATIVE_IDS_HERE']
-
-
-def main(client, line_item_id, creative_ids):
- # Initialize appropriate service.
- lica_service = client.GetService(
- 'LineItemCreativeAssociationService', version='v201502')
-
- licas = []
- for creative_id in creative_ids:
- licas.append({'creativeId': creative_id,
- 'lineItemId': line_item_id})
-
- # Create the LICAs remotely.
- licas = lica_service.createLineItemCreativeAssociations(licas)
-
- # Display results.
- if licas:
- for lica in licas:
- print ('LICA with line item id \'%s\', creative id \'%s\', and '
- 'status \'%s\' was created.' %
- (lica['lineItemId'], lica['creativeId'], lica['status']))
- else:
- print 'No LICAs created.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, LINE_ITEM_ID, CREATIVE_IDS)
diff --git a/examples/dfp/v201502/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201502/line_item_creative_association_service/deactivate_licas.py
deleted file mode 100755
index f57ce3cd..00000000
--- a/examples/dfp/v201502/line_item_creative_association_service/deactivate_licas.py
+++ /dev/null
@@ -1,84 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example deactivates all LICAs for the line item.
-
-To determine which LICAs exist, run get_all_licas.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the id of the line item in which to deactivate LICAs.
-LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
-
-
-def main(client, line_item_id):
- # Initialize appropriate service.
- lica_service = client.GetService(
- 'LineItemCreativeAssociationService', version='v201502')
-
- # Create query.
- values = [{
- 'key': 'lineItemId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': line_item_id
- }
- }, {
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ACTIVE'
- }
- }]
- query = 'WHERE lineItemId = :lineItemId AND status = :status'
- statement = dfp.FilterStatement(query, values)
-
- num_deactivated_licas = 0
-
- # Get LICAs by statement.
- while True:
- response = lica_service.getLineItemCreativeAssociationsByStatement(
- statement.ToStatement())
- if 'results' in response:
- for lica in response['results']:
- print ('LICA with line item id \'%s\', creative id \'%s\', and status'
- ' \'%s\' will be deactivated.' %
- (lica['lineItemId'], lica['creativeId'], lica['status']))
-
- # Perform action.
- result = lica_service.performLineItemCreativeAssociationAction(
- {'xsi_type': 'DeactivateLineItemCreativeAssociations'},
- statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- num_deactivated_licas += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Display results.
- if num_deactivated_licas > 0:
- print 'Number of LICAs deactivated: %s' % num_deactivated_licas
- else:
- print 'No LICAs were deactivated.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, LINE_ITEM_ID)
diff --git a/examples/dfp/v201502/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201502/line_item_creative_association_service/get_all_licas.py
deleted file mode 100755
index 06e972a6..00000000
--- a/examples/dfp/v201502/line_item_creative_association_service/get_all_licas.py
+++ /dev/null
@@ -1,58 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all line item creative associations (LICA).
-
-To create LICAs, run create_licas.py or associate_creative_set_to_line_item.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- lica_service = client.GetService(
- 'LineItemCreativeAssociationService', version='v201502')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get line items by statement.
- while True:
- response = lica_service.getLineItemCreativeAssociationsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for lica in response['results']:
- if 'creativeSetId' in lica:
- print ('LICA with line item ID \'%s\', creative set ID \'%s\', and '
- 'status \'%s\' was found.' %
- (lica['lineItemId'], lica['creativeSetId'], lica['status']))
- else:
- print ('LICA with line item ID \'%s\', creative ID \'%s\', and status'
- ' \'%s\' was found.' % (lica['lineItemId'], lica['creativeId'],
- lica['status']))
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/line_item_creative_association_service/get_licas_by_statement.py b/examples/dfp/v201502/line_item_creative_association_service/get_licas_by_statement.py
deleted file mode 100755
index 980424be..00000000
--- a/examples/dfp/v201502/line_item_creative_association_service/get_licas_by_statement.py
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all line item creative associations (LICA) for a given
-line item id.
-
-To create LICAs, run create_licas.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the id of the line item to get LICAs by.
-LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
-
-
-def main(client, line_item_id):
- # Initialize appropriate service.
- lica_service = client.GetService(
- 'LineItemCreativeAssociationService', version='v201502')
-
-# Create statement object to only select LICAs for the given line item id.
- values = [{
- 'key': 'lineItemId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': line_item_id
- }
- }]
- query = 'WHERE lineItemId = :lineItemId'
- statement = dfp.FilterStatement(query, values)
-
- while True:
- # Get LICAs by statement.
- response = lica_service.getLineItemCreativeAssociationsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- # Display results.
- for lica in response['results']:
- print ('LICA with line item id \'%s\', creative id \'%s\', and status '
- '\'%s\' was found.' % (lica['lineItemId'], lica['creativeId'],
- lica['status']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, LINE_ITEM_ID)
diff --git a/examples/dfp/v201502/line_item_creative_association_service/update_licas.py b/examples/dfp/v201502/line_item_creative_association_service/update_licas.py
deleted file mode 100755
index 404006a7..00000000
--- a/examples/dfp/v201502/line_item_creative_association_service/update_licas.py
+++ /dev/null
@@ -1,67 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates the destination URL of all line item creative
-associations (LICA).
-
-To determine which LICAs exist, run get_all_licas.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- lica_service = client.GetService(
- 'LineItemCreativeAssociationService', version='v201502')
-
- # Create statement object to get all LICAs.
- statement = dfp.FilterStatement()
-
- while True:
- # Get LICAs by statement.
- response = lica_service.getLineItemCreativeAssociationsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- # Update each local LICA object by changing its destination URL.
- updated_licas = []
- for lica in response['results']:
- lica['destinationUrl'] = 'http://news.google.com'
- updated_licas.append(lica)
-
- # Update LICAs remotely.
- licas = lica_service.updateLineItemCreativeAssociations(updated_licas)
-
- # Display results.
- for lica in licas:
- print ('LICA with line item id \'%s\', creative id \'%s\', and status '
- '\'%s\' was updated.' % (lica['lineItemId'], lica['creativeId'],
- lica['status']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- if response['totalResultSetSize'] == 0:
- print 'No LICAs found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/line_item_service/__init__.py b/examples/dfp/v201502/line_item_service/__init__.py
deleted file mode 100755
index a426ca48..00000000
--- a/examples/dfp/v201502/line_item_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201502/line_item_service/activate_line_items.py b/examples/dfp/v201502/line_item_service/activate_line_items.py
deleted file mode 100755
index da82d8e9..00000000
--- a/examples/dfp/v201502/line_item_service/activate_line_items.py
+++ /dev/null
@@ -1,86 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example activates all line items for the given order.
-
-To be activated, line items need to be in the approved state and have at least
-one creative associated with them. To approve line items, approve the order to
-which they belong by running approve_orders.py. To create LICAs, run
-create_licas.py. To determine which line items exist, run
-get_all_line_items.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the id of the order to get line items from.
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-
-
-def main(client, order_id):
- # Initialize appropriate service.
- line_item_service = client.GetService('LineItemService', version='v201502')
-
- # Create query.
- values = [{
- 'key': 'orderId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': order_id
- }
- }, {
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'NEEDS_CREATIVES'
- }
- }]
- query = 'WHERE orderId = :orderId AND status = :status'
- statement = dfp.FilterStatement(query, values)
-
- line_items_activated = 0
-
- # Get line items by statement.
- while True:
- response = line_item_service.getLineItemsByStatement(
- statement.ToStatement())
- if 'results' in response:
- for line_item in response['results']:
- print ('Line item with id \'%s\', belonging to order id \'%s\', and '
- 'name \'%s\' will be activated.' %
- (line_item['id'], line_item['orderId'], line_item['name']))
-
- # Perform action.
- result = line_item_service.performLineItemAction(
- {'xsi_type': 'ActivateLineItems'}, statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- line_items_activated += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Display results.
- if line_items_activated > 0:
- print 'Number of line items activated: %s' % line_items_activated
- else:
- print 'No line items were activated.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID)
diff --git a/examples/dfp/v201502/line_item_service/create_line_items.py b/examples/dfp/v201502/line_item_service/create_line_items.py
deleted file mode 100755
index 9ee57e26..00000000
--- a/examples/dfp/v201502/line_item_service/create_line_items.py
+++ /dev/null
@@ -1,172 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new line items.
-
-To determine which line items exist, run get_all_line_items.py. To determine
-which orders exist, run get_all_orders.py. To determine which placements exist,
-run get_all_placements.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-from datetime import date
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set order that the created line item will belong to and add the id of a
-# placement containing ad units to target.
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-TARGETED_PLACEMENT_IDS = ['INSERT_PLACEMENT_IDS_HERE']
-
-
-def main(client, order_id, targeted_placement_ids):
- # Initialize appropriate service.
- line_item_service = client.GetService('LineItemService', version='v201502')
-
- # Create line item objects.
- line_items = []
- for i in xrange(5):
- line_item = {
- 'name': 'Line item #%s' % uuid.uuid4(),
- 'orderId': order_id,
- 'targeting': {
- 'inventoryTargeting': {
- 'targetedPlacementIds': targeted_placement_ids
- },
- 'geoTargeting': {
- 'targetedLocations': [
- {
- 'id': '2840',
- 'displayName': 'US'
- },
- {
- 'id': '20133',
- 'displayName': 'Geneva'
- },
- {
- 'id': '9000093',
- 'displayName': 'B3P',
- }
- ],
- 'excludedLocations': [
- {
- 'id': '1016367',
- 'displayName': 'Chicago',
- },
- {
- 'id': '200501',
- 'displayName': 'New York NY'
- }
- ]
- },
- 'dayPartTargeting': {
- 'dayParts': [
- {
- 'dayOfWeek': 'SATURDAY',
- 'startTime': {
- 'hour': '0',
- 'minute': 'ZERO'
- },
- 'endTime': {
- 'hour': '24',
- 'minute': 'ZERO'
- }
- },
- {
- 'dayOfWeek': 'SUNDAY',
- 'startTime': {
- 'hour': '0',
- 'minute': 'ZERO'
- },
- 'endTime': {
- 'hour': '24',
- 'minute': 'ZERO'
- }
- }
- ],
- 'timeZone': 'BROWSER'
- },
- 'userDomainTargeting': {
- 'domains': ['usa.gov'],
- 'targeted': 'false'
- },
- 'technologyTargeting': {
- 'browserTargeting': {
- 'browsers': [{'id': '500072'}],
- 'isTargeted': 'true'
- }
- }
- },
- 'creativePlaceholders': [
- {
- 'size': {
- 'width': '300',
- 'height': '250'
- }
- },
- {
- 'size': {
- 'width': '120',
- 'height': '600'
- }
- }
- ],
- 'startDateTimeType': 'IMMEDIATELY',
- 'lineItemType': 'STANDARD',
- 'endDateTime': {
- 'date': {
- 'year': str(date.today().year + 1),
- 'month': '9',
- 'day': '30'
- },
- 'hour': '0',
- 'minute': '0',
- 'second': '0'
- },
- 'costType': 'CPM',
- 'costPerUnit': {
- 'currencyCode': 'USD',
- 'microAmount': '2000000'
- },
- 'primaryGoal': {
- 'units': '50',
- 'unitType': 'IMPRESSIONS',
- 'goalType': 'LIFETIME'
- },
- 'contractedUnitsBought': '100',
- 'creativeRotationType': 'EVEN',
- 'discountType': 'PERCENTAGE',
- 'allowOverbook': 'true'
- }
- line_items.append(line_item)
-
- # Add line items.
- line_items = line_item_service.createLineItems(line_items)
-
- # Display results.
- for line_item in line_items:
- print ('Line item with id \'%s\', belonging to order id \'%s\', and named '
- '\'%s\' was created.' % (line_item['id'], line_item['orderId'],
- line_item['name']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID, TARGETED_PLACEMENT_IDS)
-
diff --git a/examples/dfp/v201502/line_item_service/create_video_line_item.py b/examples/dfp/v201502/line_item_service/create_video_line_item.py
deleted file mode 100755
index 827ff738..00000000
--- a/examples/dfp/v201502/line_item_service/create_video_line_item.py
+++ /dev/null
@@ -1,141 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates a new line item to serve to video content.
-
-This feature is only available to DFP premium solution networks. To determine
-which line items exist, run get_all_line_items.py. To determine which orders
-exist, run get_all_orders.py. To create a video ad unit, run
-create_video_ad_unit.py. To create criteria for categories, run
-create_custom_targeting_keys_and_values.py"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-from datetime import date
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set order that all created line item will belong to and the video ad unit id
-# to target.
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-TARGETED_VIDEO_AD_UNIT_ID = 'INSERT_TARGETED_VIDEO_AD_UNIT_ID_HERE'
-
-# Set the custom targeting value ID representing the metadata
-# on the content to target. This would typically be from a key representing
-# a "genre" and the value representing something like "comedy". The value
-# must be from a key in a content metadata key hierarchy.
-CONTENT_CUSTOM_TARGETING_VALUE_ID = \
- 'INSERT_CONTENT_CUSTOM_TARGETING_VALUE_ID_HERE'
-
-
-def main(client, order_id, targeted_video_ad_unit_id,
- content_custom_targeting_value_id):
- # Initialize appropriate service.
- line_item_service = client.GetService('LineItemService', version='v201502')
-
- # Create line item object.
- line_item = {
- 'name': 'Line item #%s' % uuid.uuid4(),
- 'orderId': order_id,
- 'targeting': {
- 'contentTargeting': {
- 'targetedContentMetadata': [
- {'customTargetingValueIds': [
- content_custom_targeting_value_id]}
- ]
- },
- 'inventoryTargeting': {
- 'targetedAdUnits': [{'adUnitId': targeted_video_ad_unit_id,
- 'includeDescendants': 'true'}]
- },
- 'videoPositionTargeting': {
- 'targetedPositions': [
- {
- 'videoPosition': {
- 'positionType': 'PREROLL'
- }
- }
- ]
- }
- },
- 'creativePlaceholders': [
- {
- 'size': {
- 'width': '400',
- 'height': '300'
- },
- 'companions': [
- {
- 'size': {
- 'width': '300',
- 'height': '250'
- },
- },
- {
- 'size': {
- 'width': '728',
- 'height': '90'
- },
- }
- ]
- }
- ],
- 'environmentType': 'VIDEO_PLAYER',
- 'companionDeliveryOption': 'OPTIONAL',
- 'startDateTimeType': 'IMMEDIATELY',
- 'lineItemType': 'SPONSORSHIP',
- 'endDateTime': {
- 'date': {
- 'year': str(date.today().year + 1),
- 'month': '9',
- 'day': '30'
- },
- 'hour': '0',
- 'minute': '0',
- 'second': '0'
- },
- 'costType': 'CPM',
- 'costPerUnit': {
- 'currencyCode': 'USD',
- 'microAmount': '2000000'
- },
- 'primaryGoal': {
- 'units': '50',
- 'unitType': 'IMPRESSIONS',
- 'goalType': 'DAILY'
- },
- 'contractedUnitsBought': '100',
- 'creativeRotationType': 'OPTIMIZED',
- 'discountType': 'PERCENTAGE',
- 'allowOverbook': 'true'
- }
-
- # Add line item.
- line_item = line_item_service.createLineItem(line_item)
-
- # Display results.
- print ('Video line item with id \'%s\', belonging to order id \'%s\', and '
- 'named \'%s\' was created.' % (line_item['id'], line_item['orderId'],
- line_item['name']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID, TARGETED_VIDEO_AD_UNIT_ID,
- CONTENT_CUSTOM_TARGETING_VALUE_ID)
diff --git a/examples/dfp/v201502/line_item_service/get_all_line_items.py b/examples/dfp/v201502/line_item_service/get_all_line_items.py
deleted file mode 100755
index 18cf1895..00000000
--- a/examples/dfp/v201502/line_item_service/get_all_line_items.py
+++ /dev/null
@@ -1,54 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all line items.
-
-To create line items, run create_line_items.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- line_item_service = client.GetService('LineItemService', version='v201502')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get line items by statement.
- while True:
- response = line_item_service.getLineItemsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for line_item in response['results']:
- print ('Line item with id \'%s\', belonging to order id \'%s\', and '
- 'named \'%s\' was found.' %
- (line_item['id'], line_item['orderId'], line_item['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/line_item_service/get_line_items_by_statement.py b/examples/dfp/v201502/line_item_service/get_line_items_by_statement.py
deleted file mode 100755
index c46929fd..00000000
--- a/examples/dfp/v201502/line_item_service/get_line_items_by_statement.py
+++ /dev/null
@@ -1,77 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all line items that need creatives for the given
-order.
-
-To create line items, run create_line_items.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the id of the order to get line items from.
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-
-
-def main(client, order_id):
- # Initialize appropriate service.
- line_item_service = client.GetService('LineItemService', version='v201502')
-
- # Create statement object to only select line items that need creatives from a
- # given order.
- values = [{
- 'key': 'orderId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': order_id
- }
- }, {
- 'key': 'isMissingCreatives',
- 'value': {
- 'xsi_type': 'BooleanValue',
- 'value': 'true'
- }
- }]
- query = 'WHERE orderId = :orderId AND '
- 'isMissingCreatives = :isMissingCreatives'
- statement = dfp.FilterStatement(query, values)
-
- while True:
- # Get line items by statement.
- response = line_item_service.getLineItemsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- # Display results.
- for line_item in response['results']:
- print ('Line item with id \'%s\', belonging to order id \'%s\', and '
- 'named \'%s\' was found.' % (line_item['id'],
- line_item['orderId'],
- line_item['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID)
diff --git a/examples/dfp/v201502/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201502/line_item_service/get_recently_updated_line_items.py
deleted file mode 100755
index 9301c8f5..00000000
--- a/examples/dfp/v201502/line_item_service/get_recently_updated_line_items.py
+++ /dev/null
@@ -1,76 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example shows how to get recently updated line items.
-
-To create line items, run create_line_items.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import datetime
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-
-
-def main(client, order_id):
- # Initialize appropriate service.
- line_item_service = client.GetService('LineItemService', version='v201502')
-
- # Create statement object to only select line items belonging to the order and
- # have been modified in the last 3 days.
- three_days_ago = datetime.date.today() - datetime.timedelta(days=3)
- values = [{
- 'key': 'dateTimeString',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': three_days_ago.strftime('%Y-%m-%dT%H:%M:%S')
- }
- }, {
- 'key': 'orderId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': order_id
- }
- }]
- query = 'WHERE lastModifiedDateTime >= :dateTimeString AND orderId = :orderId'
- statement = dfp.FilterStatement(query, values)
-
- while True:
- # Get line items by statement.
- response = line_item_service.getLineItemsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- # Display results.
- for line_item in response['results']:
- print ('Line item with id \'%s\', belonging to order id \'%s\', and '
- 'named \'%s\' was found.' % (line_item['id'],
- line_item['orderId'],
- line_item['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID)
diff --git a/examples/dfp/v201502/line_item_service/target_custom_criteria.py b/examples/dfp/v201502/line_item_service/target_custom_criteria.py
deleted file mode 100755
index 46ad56d6..00000000
--- a/examples/dfp/v201502/line_item_service/target_custom_criteria.py
+++ /dev/null
@@ -1,115 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates a line item to add custom criteria targeting.
-
-To determine which line items exist, run get_all_line_items.py. To determine
-which custom targeting keys and values exist, run
-get_all_custom_targeting_keys_and_values.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import pprint
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
-KEY_ID1 = 'INSERT_TARGETING_KEY_ID_HERE'
-KEY_ID2 = 'INSERT_TARGETING_KEY_ID_HERE'
-KEY_ID3 = 'INSERT_TARGETING_KEY_ID_HERE'
-
-VALUE_ID1 = 'INSERT_TARGETING_VALUE_ID_HERE'
-VALUE_ID2 = 'INSERT_TARGETING_VALUE_ID_HERE'
-VALUE_ID3 = 'INSERT_TARGETING_VALUE_ID_HERE'
-
-
-def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2,
- value_id3):
- # Initialize appropriate service.
- line_item_service = client.GetService('LineItemService', version='v201502')
-
- # create custom criterias
- custom_criteria1 = {
- 'xsi_type': 'CustomCriteria',
- 'keyId': key_id1,
- 'valueIds': [value_id1],
- 'operator': 'IS'
- }
-
- custom_criteria2 = {
- 'xsi_type': 'CustomCriteria',
- 'keyId': key_id2,
- 'valueIds': [value_id2],
- 'operator': 'IS_NOT'
- }
-
- custom_criteria3 = {
- 'xsi_type': 'CustomCriteria',
- 'keyId': key_id3,
- 'valueIds': [value_id3],
- 'operator': 'IS'
- }
-
- # Create the custom criteria set that will resemble:
- # (custom_criteria1.key == custom_criteria1.value OR
- # (custom_criteria2.key != custom_criteria2.value AND
- # custom_criteria13.key == custom_criteria3.value))
- sub_set = {
- 'xsi_type': 'CustomCriteriaSet',
- 'logicalOperator': 'AND',
- 'children': [custom_criteria2, custom_criteria3]
- }
-
- top_set = {
- 'xsi_type': 'CustomCriteriaSet',
- 'logicalOperator': 'OR',
- 'children': [custom_criteria1, sub_set]
- }
-
- # Create statement to get the line item
- values = [{
- 'key': 'lineItemId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': line_item_id
- }
- }]
- query = 'WHERE id = :lineItemId'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Set custom criteria targeting on the line item.
- line_item = line_item_service.getLineItemsByStatement(
- statement.ToStatement())['results'][0]
- line_item['targeting']['customTargeting'] = top_set
-
- # Update line item.
- line_item = line_item_service.updateLineItems([line_item])[0]
-
- # Display results.
- if line_item:
- print ('Line item with id \'%s\' updated with custom criteria targeting:'
- % line_item['id'])
- pprint.pprint(line_item['targeting']['customTargeting'])
- else:
- print 'No line items were updated.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, LINE_ITEM_ID, KEY_ID1, KEY_ID2, KEY_ID3, VALUE_ID1,
- VALUE_ID2, VALUE_ID3)
diff --git a/examples/dfp/v201502/line_item_service/update_line_items.py b/examples/dfp/v201502/line_item_service/update_line_items.py
deleted file mode 100755
index fd7af4da..00000000
--- a/examples/dfp/v201502/line_item_service/update_line_items.py
+++ /dev/null
@@ -1,83 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates the delivery rate of all line items in an order.
-
-To determine which line items exist, run get_all_line_items.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set id of the order to get line items from.
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-
-
-def main(client, order_id):
- # Initialize appropriate service.
- line_item_service = client.GetService('LineItemService', version='v201502')
-
- # Create statement object to only select line items with even delivery rates.
- values = [{
- 'key': 'deliveryRateType',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'EVENLY'
- }
- }, {
- 'key': 'orderId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': order_id
- }
- }]
-
- query = 'WHERE deliveryRateType = :deliveryRateType and orderId = :orderId'
- statement = dfp.FilterStatement(query, values, 500)
-
- # Get line items by statement.
- response = line_item_service.getLineItemsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- # Update each local line item by changing its delivery rate type.
- updated_line_items = []
- for line_item in response['results']:
- if not line_item['isArchived']:
- line_item['deliveryRateType'] = 'AS_FAST_AS_POSSIBLE'
- updated_line_items.append(line_item)
-
- # Update line items remotely.
- line_items = line_item_service.updateLineItems(updated_line_items)
-
- # Display results.
- if line_items:
- for line_item in line_items:
- print ('Line item with id \'%s\', belonging to order id \'%s\', named '
- '\'%s\', and delivery rate \'%s\' was updated.'
- % (line_item['id'], line_item['orderId'], line_item['name'],
- line_item['deliveryRateType']))
- else:
- print 'No line items were updated.'
- else:
- print 'No line items found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID)
diff --git a/examples/dfp/v201502/network_service/__init__.py b/examples/dfp/v201502/network_service/__init__.py
deleted file mode 100755
index a426ca48..00000000
--- a/examples/dfp/v201502/network_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201502/network_service/get_all_networks.py b/examples/dfp/v201502/network_service/get_all_networks.py
deleted file mode 100755
index cc8c6236..00000000
--- a/examples/dfp/v201502/network_service/get_all_networks.py
+++ /dev/null
@@ -1,46 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all networks that you have access to with the current login
-credentials.
-
-A networkCode should be left out for this request."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- network_service = client.GetService('NetworkService', version='v201502')
-
- # Get all networks that you have access to with the current login credentials.
- networks = network_service.getAllNetworks()
-
- # Display results.
- for network in networks:
- print ('Network with network code \'%s\' and display name \'%s\' was found.'
- % (network['networkCode'], network['displayName']))
-
- print '\nNumber of results found: %s' % len(networks)
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/network_service/get_current_network.py b/examples/dfp/v201502/network_service/get_current_network.py
deleted file mode 100755
index ad37d3f8..00000000
--- a/examples/dfp/v201502/network_service/get_current_network.py
+++ /dev/null
@@ -1,40 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets the current network that you can make requests against."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- network_service = client.GetService('NetworkService', version='v201502')
-
- # Get the current network.
- network = network_service.getCurrentNetwork()
-
- # Display results.
- print ('Current network has network code \'%s\' and display name \'%s\'.'
- % (network['networkCode'], network['displayName']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/network_service/make_test_network.py b/examples/dfp/v201502/network_service/make_test_network.py
deleted file mode 100755
index 54560848..00000000
--- a/examples/dfp/v201502/network_service/make_test_network.py
+++ /dev/null
@@ -1,53 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates a test network.
-
-You do not need to have a DFP account to run this example, but you do need to
-have a Google account (created at http://www.google.com/accounts/newaccount
-if you currently don't have one) that is not associated with any other DFP test
-networks. Once this network is created, you can supply the network code in your
-settings to make calls to other services.
-
-Alternatively, if you do not wish to run this example, you can create a test
-network at:
-https://dfp-playground.appspot.com
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- network_service = client.GetService('NetworkService', version='v201502')
-
- # Create a test network.
- network = network_service.MakeTestNetwork()
-
- # Display results.
- print ('Test network with network code \'%s\' and display name \'%s\' '
- 'created.' % (network['networkCode'], network['displayName']))
- print ('You may now sign in at http://www.google.com/dfp/main?networkCode=%s'
- % network['networkCode'])
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/order_service/__init__.py b/examples/dfp/v201502/order_service/__init__.py
deleted file mode 100755
index a426ca48..00000000
--- a/examples/dfp/v201502/order_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201502/order_service/approve_orders.py b/examples/dfp/v201502/order_service/approve_orders.py
deleted file mode 100755
index 25461c20..00000000
--- a/examples/dfp/v201502/order_service/approve_orders.py
+++ /dev/null
@@ -1,75 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example approves all eligible draft and pending orders.
-
-To determine which orders exist, run get_all_orders.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import datetime
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- order_service = client.GetService('OrderService', version='v201502')
-
- # Create query.
- values = [{
- 'key': 'today',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': datetime.date.today().strftime('%Y-%m-%dT%H:%M:%S')
- }
- }]
- query = ('WHERE status in (\'DRAFT\', \'PENDING_APPROVAL\')'
- ' AND endDateTime >= :today AND isArchived = FALSE')
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
- orders_approved = 0
-
- # Get orders by statement.
- while True:
- response = order_service.getOrdersByStatement(statement.ToStatement())
- if 'results' in response:
- # Display results.
- for order in response['results']:
- print ('Order with id \'%s\', name \'%s\', and status \'%s\' will be '
- 'approved.' % (order['id'], order['name'], order['status']))
- # Perform action.
- result = order_service.performOrderAction(
- {'xsi_type': 'ApproveOrders'}, statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- orders_approved += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Display results.
- if orders_approved > 0:
- print 'Number of orders approved: %s' % orders_approved
- else:
- print 'No orders were approved.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/order_service/create_orders.py b/examples/dfp/v201502/order_service/create_orders.py
deleted file mode 100755
index 2bd42259..00000000
--- a/examples/dfp/v201502/order_service/create_orders.py
+++ /dev/null
@@ -1,60 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new orders.
-
-To determine which orders exist, run get_all_orders.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE'
-SALESPERSON_ID = 'INSERT_SALESPERSON_ID_HERE'
-TRAFFICKER_ID = 'INSERT_TRAFFICKER_ID_HERE'
-
-
-def main(client, company_id, salesperson_id, trafficker_id):
- # Initialize appropriate service.
- order_service = client.GetService('OrderService', version='v201502')
-
- # Create order objects.
- orders = []
- for i in xrange(5):
- order = {
- 'name': 'Order #%s' % uuid.uuid4(),
- 'advertiserId': company_id,
- 'salespersonId': salesperson_id,
- 'traffickerId': trafficker_id
- }
- orders.append(order)
-
- # Add orders.
- orders = order_service.createOrders(orders)
-
- # Display results.
- for order in orders:
- print ('Order with id \'%s\' and name \'%s\' was created.'
- % (order['id'], order['name']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, COMPANY_ID, SALESPERSON_ID, TRAFFICKER_ID)
diff --git a/examples/dfp/v201502/order_service/get_all_orders.py b/examples/dfp/v201502/order_service/get_all_orders.py
deleted file mode 100755
index b38eaf6c..00000000
--- a/examples/dfp/v201502/order_service/get_all_orders.py
+++ /dev/null
@@ -1,54 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all orders.
-
-To create orders, run create_orders.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- order_service = client.GetService('OrderService', version='v201502')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get orders by statement.
- while True:
- response = order_service.getOrdersByStatement(statement.ToStatement())
- if 'results' in response:
- # Display results.
- for order in response['results']:
- print ('Order with id \'%s\', name \'%s\', and advertiser id \'%s\' was'
- ' found.' % (order['id'], order['name'], order['advertiserId']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/order_service/get_orders_by_statement.py b/examples/dfp/v201502/order_service/get_orders_by_statement.py
deleted file mode 100755
index ee3c96f8..00000000
--- a/examples/dfp/v201502/order_service/get_orders_by_statement.py
+++ /dev/null
@@ -1,63 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets an order by an ID.
-
-To create orders, run create_orders.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set id of the order to get.
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-
-
-def main(client, order_id):
- # Initialize appropriate service.
- order_service = client.GetService('OrderService', version='v201502')
-
- # Create statement object to select a single order by an ID.
- values = [{
- 'key': 'orderId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': order_id
- }
- }]
- query = 'WHERE id = :orderId'
-
- statement = dfp.FilterStatement(query, values)
-
- # Get orders by statement.
- response = order_service.getOrdersByStatement(statement.ToStatement())
- orders = []
- if 'results' in response:
- orders = response['results']
-
- # Display results.
- for order in orders:
- print ('Order with id \'%s\' name \'%s\' was found.'
- % (order['id'], order['name']))
-
- print '\nNumber of results found: %s' % len(orders)
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID)
diff --git a/examples/dfp/v201502/order_service/update_orders.py b/examples/dfp/v201502/order_service/update_orders.py
deleted file mode 100755
index 7512049c..00000000
--- a/examples/dfp/v201502/order_service/update_orders.py
+++ /dev/null
@@ -1,77 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates the notes of a single order specified by ID.
-
-To determine which orders exist, run get_all_orders.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-
-
-def main(client, order_id):
- # Initialize appropriate service.
- order_service = client.GetService('OrderService', version='v201502')
-
- # Create statement object to select a single order by an ID.
- values = [{
- 'key': 'orderId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': order_id
- }
- }]
- query = 'WHERE id = :orderId'
-
- statement = dfp.FilterStatement(query, values)
-
- # Get orders by statement.
- response = order_service.getOrdersByStatement(statement.ToStatement())
-
- if 'results' in response:
- # Update each local order object by changing its notes.
- updated_orders = []
- for order in response['results']:
- # Archived orders cannot be updated.
- if not order['isArchived']:
- order['notes'] = 'Spoke to advertiser. All is well.'
- updated_orders.append(order)
-
- # Update orders remotely.
- orders = order_service.updateOrders(updated_orders)
-
- # Display results.
- if orders:
- for order in orders:
- print ('Order with id \'%s\', name \'%s\', advertiser id \'%s\', and '
- 'notes \'%s\' was updated.'
- % (order['id'], order['name'], order['advertiserId'],
- order['notes']))
- else:
- print 'No orders were updated.'
- else:
- print 'No orders found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID)
-
diff --git a/examples/dfp/v201502/placement_service/create_placements.py b/examples/dfp/v201502/placement_service/create_placements.py
deleted file mode 100755
index e09a5c76..00000000
--- a/examples/dfp/v201502/placement_service/create_placements.py
+++ /dev/null
@@ -1,110 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new placements for various ad unit sizes.
-
-To determine which placements exist, run get_all_placements.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- placement_service = client.GetService('PlacementService', version='v201502')
- inventory_service = client.GetService('InventoryService', version='v201502')
-
- # Create placement object to store medium rectangle ad units.
- medium_rectangle_ad_unit_placement = {
- 'name': 'Medium rectangle AdUnit Placement #%s' % uuid.uuid4(),
- 'description': 'Contains ad units that hold creatives of size 300x250',
- 'targetedAdUnitIds': []
- }
-
- # Create placement object to store skyscraper ad units.
- skyscraper_ad_unit_placement = {
- 'name': 'Skyscraper AdUnit Placement #%s' % uuid.uuid4(),
- 'description': 'Contains ad units that hold creatives of size 120x600',
- 'targetedAdUnitIds': []
- }
-
- # Create placement object to store banner ad units.
- banner_ad_unit_placement = {
- 'name': 'Banner AdUnit Placement #%s' % uuid.uuid4(),
- 'description': 'Contains ad units that hold creatives of size 468x60',
- 'targetedAdUnitIds': []
- }
-
- placement_list = []
-
- # Create statement to get all the ad units.
- statement = dfp.FilterStatement()
-
- while True:
- response = inventory_service.getAdUnitsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- # Separate the ad units by size.
- for ad_unit in response['results']:
- if 'adUnitSizes' in ad_unit:
- for ad_unit_size in ad_unit['adUnitSizes']:
- size = ad_unit_size['size']
- if size['width'] == '300' and size['height'] == '250':
- medium_rectangle_ad_unit_placement['targetedAdUnitIds'].append(
- ad_unit['id'])
- elif size['width'] == '120' and size['height'] == '600':
- skyscraper_ad_unit_placement['targetedAdUnitIds'].append(
- ad_unit['id'])
- elif size['width'] == '468' and size['height'] == '60':
- banner_ad_unit_placement['targetedAdUnitIds'].append(
- ad_unit['id'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Only create placements with one or more ad unit.
- if medium_rectangle_ad_unit_placement['targetedAdUnitIds']:
- placement_list.append(medium_rectangle_ad_unit_placement)
-
- if skyscraper_ad_unit_placement['targetedAdUnitIds']:
- placement_list.append(skyscraper_ad_unit_placement)
-
- if banner_ad_unit_placement['targetedAdUnitIds']:
- placement_list.append(banner_ad_unit_placement)
-
- # Add placements.
- placements = placement_service.createPlacements(placement_list)
-
- # Display results.
- for placement in placements:
- ad_unit_ids = ''
- if 'targetedAdUnitIds' in placement:
- ad_unit_ids = ', '.join(placement['targetedAdUnitIds'])
- print ('A Placement with ID \'%s\', name \'%s\', and containing ad units '
- '{%s} was created.' % (placement['id'], placement['name'],
- ad_unit_ids))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/placement_service/deactivate_placements.py b/examples/dfp/v201502/placement_service/deactivate_placements.py
deleted file mode 100755
index 9f888b11..00000000
--- a/examples/dfp/v201502/placement_service/deactivate_placements.py
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example deactivates all active placements.
-
-To determine which placements exist, run get_all_placements.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-PLACEMENT_ID = 'INSERT_PLACEMENT_ID_HERE'
-
-
-def main(client, placement_id):
- # Initialize appropriate service.
- placement_service = client.GetService('PlacementService', version='v201502')
-
- # Create query.
- values = [{
- 'key': 'placementId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': placement_id
- }
- }]
- query = 'WHERE id = :placementId'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get placements by statement.
- placements = placement_service.getPlacementsByStatement(
- statement.ToStatement())
-
- for placement in placements:
- print ('Placement with id \'%s\', name \'%s\', and status \'%s\' will be '
- 'deactivated.' % (placement['id'], placement['name'],
- placement['status']))
-
- # Perform action.
- result = placement_service.performPlacementAction(
- {'xsi_type': 'DeactivatePlacements'}, statement.ToStatement())
-
- # Display results.
- if result and int(result['numChanges']) > 0:
- print 'Number of placements deactivated: %s' % result['numChanges']
- else:
- print 'No placements were deactivated.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PLACEMENT_ID)
diff --git a/examples/dfp/v201502/placement_service/get_all_placements.py b/examples/dfp/v201502/placement_service/get_all_placements.py
deleted file mode 100755
index adfbde6c..00000000
--- a/examples/dfp/v201502/placement_service/get_all_placements.py
+++ /dev/null
@@ -1,54 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all placements.
-
-To create placements, run create_placement.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- placement_service = client.GetService('PlacementService', version='v201502')
-
- # Create statement to fetch all placements.
- statement = dfp.FilterStatement()
-
- # Get placements by statement.
- while True:
- response = placement_service.getPlacementsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for placement in response['results']:
- print ('Placement with id \'%s\' and name \'%s\' was found.'
- % (placement['id'], placement['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/placement_service/get_placements_by_statement.py b/examples/dfp/v201502/placement_service/get_placements_by_statement.py
deleted file mode 100755
index 8f501a17..00000000
--- a/examples/dfp/v201502/placement_service/get_placements_by_statement.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all active placements by using a statement.
-
-To create a placement, run create_placements.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- placement_service = client.GetService('PlacementService', version='v201502')
-
- # Create a statement to only select active placements.
- values = [{
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'ACTIVE'
- }
- }]
- query = 'WHERE status = :status'
- statement = dfp.FilterStatement(query, values)
-
- # Get placements by statement.
- while True:
- response = placement_service.getPlacementsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for placement in response['results']:
- print ('Placement with id \'%s\' and name \'%s\' was found.'
- % (placement['id'], placement['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/placement_service/update_placements.py b/examples/dfp/v201502/placement_service/update_placements.py
deleted file mode 100755
index ada64131..00000000
--- a/examples/dfp/v201502/placement_service/update_placements.py
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates a single placement to allow for AdSense targeting.
-
-To determine which placements exist, run get_all_placements.py.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-PLACEMENT_ID = 'INSERT_PLACEMENT_ID_HERE'
-
-
-def main(client, placement_id):
- # Initialize appropriate service.
- placement_service = client.GetService('PlacementService', version='v201502')
-# Create query.
- values = [{
- 'key': 'placementId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': placement_id
- }
- }]
- query = 'WHERE id = :placementId'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get placements by statement.
- placements = placement_service.getPlacementsByStatement(
- statement.ToStatement())
-
- for placement in placements:
- if not placement['targetingDescription']:
- placement['targetingDescription'] = 'Generic description'
- placement['targetingAdLocation'] = 'All images on sports pages.'
- placement['targetingSiteName'] = 'http://code.google.com'
- placement['isAdSenseTargetingEnabled'] = 'true'
-
- # Update placements remotely.
- placements = placement_service.updatePlacements(placements)
-
- for placement in placements:
- print ('Placement with id \'%s\', name \'%s\', and AdSense targeting '
- 'enabled \'%s\' was updated.'
- % (placement['id'], placement['name'],
- placement['isAdSenseTargetingEnabled']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PLACEMENT_ID)
diff --git a/examples/dfp/v201502/premium_rate_service/__init__.py b/examples/dfp/v201502/premium_rate_service/__init__.py
deleted file mode 100755
index a426ca48..00000000
--- a/examples/dfp/v201502/premium_rate_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201502/premium_rate_service/create_premium_rates.py b/examples/dfp/v201502/premium_rate_service/create_premium_rates.py
deleted file mode 100755
index b4f59725..00000000
--- a/examples/dfp/v201502/premium_rate_service/create_premium_rates.py
+++ /dev/null
@@ -1,84 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new premium_rates.
-
-To determine which premium_rates exist, run get_all_premium_rates.py.
-"""
-
-__author__ = 'Nicholas Chen'
-
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE'
-
-
-def main(client, rate_card_id):
- # Initialize appropriate services.
- premium_rate_service = client.GetService('PremiumRateService',
- version='v201502')
-
- # Create an ad unit premium to apply to the rate card.
- ad_unit_premium_feature = {
- 'xsi_type': 'AdUnitPremiumFeature'
- }
-
- # Create a CPC based premium rate value with adjustments in milli amounts.
- # This will adjust a CPC priced proposal line item that has
- # inventory targeting specified by 10% of the cost associated with the rate
- # card (this comes from a percentage adjustment).
- cpc_premium_rate_value = {
- 'premiumFeature': ad_unit_premium_feature,
- 'rateType': 'CPC',
- 'adjustmentSize': 10000,
- 'adjustmentType': 'PERCENTAGE'
- }
-
- # Create a CPM based premium rate value with adjustments in micro amounts.
- # This will adjust a CPM priced proposal line item that has
- # inventory targeting specified by 2 units of the currency associated with
- # the rate card (this comes from absolute value adjustment).
- cpm_premium_rate_value = {
- 'premiumFeature': ad_unit_premium_feature,
- 'rateType': 'CPM',
- 'adjustmentSize': 2000000,
- 'adjustmentType': 'ABSOLUTE_VALUE'
- }
-
- # Create premium_rate objects.
- premium_rate = {
- 'rateCardId': rate_card_id,
- 'pricingMethod': 'ANY_VALUE',
- 'premiumFeature': ad_unit_premium_feature,
- 'premiumRateValues': [cpc_premium_rate_value, cpm_premium_rate_value]
- }
-
- # Add premium_rates.
- premium_rates = premium_rate_service.createPremiumRates([premium_rate])
-
- # Display results.
- for premium_rate in premium_rates:
- print ('A premium rate for \'%s\' was added to the rate card with ID'
- ' of \'%s\'.\n'
- % (dfp.DfpClassType(premium_rate['premiumFeature']),
- premium_rate['id']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, RATE_CARD_ID)
diff --git a/examples/dfp/v201502/premium_rate_service/get_all_premium_rates.py b/examples/dfp/v201502/premium_rate_service/get_all_premium_rates.py
deleted file mode 100755
index 54443214..00000000
--- a/examples/dfp/v201502/premium_rate_service/get_all_premium_rates.py
+++ /dev/null
@@ -1,60 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all premium rates.
-
-To create premium rates, run create_premium_rates.py.
-
-Tags: PremiumRateService.getPremiumRatesByStatement
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- premium_rate_service = client.GetService('PremiumRateService',
- version='v201502')
-
- # Create a filter statement.
- statement = dfp.FilterStatement('ORDER BY id ASC')
-
- # Get premium rates by statement.
- while True:
- response = premium_rate_service.getPremiumRatesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for premium_rate in response['results']:
- print ('Premium rate with ID \'%s\' of type \'%s\' assigned to '
- ' rate card with ID \'%s\' was found.\n' % (
- premium_rate['id'],
- dfp.DfpClassType(premium_rate['premiumFeature']),
- premium_rate['rateCardId']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/premium_rate_service/get_premium_rates_for_a_rate_card.py b/examples/dfp/v201502/premium_rate_service/get_premium_rates_for_a_rate_card.py
deleted file mode 100755
index e21f2572..00000000
--- a/examples/dfp/v201502/premium_rate_service/get_premium_rates_for_a_rate_card.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all premium rates belonging to a specific rate card.
-
-To create premium rates, run create_premium_rates.py.
-
-Tags: PremiumRateService.getPremiumRatesByStatement
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE'
-
-
-def main(client, rate_card_id):
- # Initialize appropriate service.
- premium_rate_service = client.GetService('PremiumRateService',
- version='v201502')
-
- # Create statement object to select a single proposal by an ID.
- values = [{
- 'key': 'rateCardId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': rate_card_id
- }
- }]
- query = 'WHERE rateCardId = :rateCardId ORDER BY id ASC'
- statement = dfp.FilterStatement(query, values)
-
- # Get premium rates by statement.
- while True:
- response = premium_rate_service.getPremiumRatesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for premium_rate in response['results']:
- print ('Premium rate with ID \'%s\' of type \'%s\' assigned to '
- ' rate card with ID \'%s\' was found.\n' % (
- premium_rate['id'],
- dfp.DfpClassType(premium_rate['premiumFeature']),
- premium_rate['rateCardId']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, RATE_CARD_ID)
diff --git a/examples/dfp/v201502/premium_rate_service/update_premium_rates.py b/examples/dfp/v201502/premium_rate_service/update_premium_rates.py
deleted file mode 100755
index e2cc88d3..00000000
--- a/examples/dfp/v201502/premium_rate_service/update_premium_rates.py
+++ /dev/null
@@ -1,94 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates a premium rate to add a flat fee to an existing feature.
-
-To determine which premium rates exist, run get_all_premium_rates.py.
-
-Tags: PremiumRateService.getPremiumRatesByStatement
-Tags: PremiumRateService.updatePremiumRates
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-PREMIUM_RATE_ID = 'INSERT_PREMIUM_RATE_ID_HERE'
-
-
-def main(client, premium_rate_id):
- # Initialize appropriate service.
- premium_rate_service = client.GetService('PremiumRateService',
- version='v201502')
-
- # Create statement object to select a single proposal by an ID.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': premium_rate_id
- }
- }]
- query = 'WHERE id = :id ORDER BY id ASC'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get the premium rate.
- response = premium_rate_service.getPremiumRatesByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- updated_premium_rates = []
- for premium_rate in response['results']:
- # Create a flat fee based premium rate value with a 10% increase.
- new_flat_fee_rate = {
- 'premiumFeature': premium_rate['premiumFeature'],
- 'rateType': 'CPM',
- 'adjustmentSize': 10000,
- 'adjustmentType': 'PERCENTAGE'
- }
-
- # Update the premium rate's premiumRateValues to include a flat fee
- # premium rate.
-
- existing_premium_rate_value = (
- [] if 'premiumRateValues' not in premium_rate else
- premium_rate['premiumRateValues'])
- existing_premium_rate_value.append(new_flat_fee_rate)
- premium_rate['premiumRateValues'] = existing_premium_rate_value
-
- updated_premium_rates.append(premium_rate)
-
- # Update products remotely.
- premium_rates = premium_rate_service.updatePremiumRates(
- updated_premium_rates)
-
- # Display results.
- if premium_rates:
- for premium_rate in premium_rates:
- print ('Premium rate with ID \'%s\', associated with rate card id'
- ' \'%s\' was updated.' % (premium_rate['id'],
- premium_rate['rateCardId']))
- else:
- print 'No premium rates were updated.'
- else:
- print 'No premium rates found to update.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PREMIUM_RATE_ID)
diff --git a/examples/dfp/v201502/product_service/__init__.py b/examples/dfp/v201502/product_service/__init__.py
deleted file mode 100755
index a426ca48..00000000
--- a/examples/dfp/v201502/product_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201502/product_service/get_all_products.py b/examples/dfp/v201502/product_service/get_all_products.py
deleted file mode 100755
index 37c64506..00000000
--- a/examples/dfp/v201502/product_service/get_all_products.py
+++ /dev/null
@@ -1,55 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all products.
-
-Products are created automatically from product templates.
-
-Tags: ProductService.getProductsByStatement
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- product_service = client.GetService('ProductService', version='v201502')
-
- # Create a filter statement.
- statement = dfp.FilterStatement('ORDER BY id ASC')
-
- # Get products by statement.
- while True:
- response = product_service.getProductsByStatement(statement.ToStatement())
- if 'results' in response:
- # Display results.
- for product in response['results']:
- print ('Product with id \'%s\' and name \'%s\' was found.' % (
- product['id'], product['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/product_service/get_products_for_product_template.py b/examples/dfp/v201502/product_service/get_products_for_product_template.py
deleted file mode 100755
index e21bb3f8..00000000
--- a/examples/dfp/v201502/product_service/get_products_for_product_template.py
+++ /dev/null
@@ -1,64 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all products created from a product template.
-
-Tags: ProductService.getProductsByStatement
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE'
-
-
-def main(client, product_template_id):
- # Initialize appropriate service.
- product_service = client.GetService('ProductService', version='v201502')
-
- # Create a filter statement to select only products created from a single
- # a product template.
- values = [{
- 'key': 'productTemplateId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': product_template_id
- }
- }]
- query = 'WHERE productTemplateId = :productTemplateId ORDER BY id ASC'
- statement = dfp.FilterStatement(query, values)
-
- # Get products by statement.
- while True:
- response = product_service.getProductsByStatement(statement.ToStatement())
- if 'results' in response:
- # Display results.
- for product in response['results']:
- print ('Product with id \'%s\' and name \'%s\' was found.' % (
- product['id'], product['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PRODUCT_TEMPLATE_ID)
diff --git a/examples/dfp/v201502/product_service/update_products.py b/examples/dfp/v201502/product_service/update_products.py
deleted file mode 100755
index a4f38527..00000000
--- a/examples/dfp/v201502/product_service/update_products.py
+++ /dev/null
@@ -1,75 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates a product's notes.
-
-To determine which products exist, run get_all_products.py.
-
-Tags: ProductService.getProductsByStatement
-Tags: ProductService.updateProducts
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE'
-
-
-def main(client, product_id):
- # Initialize appropriate service.
- product_service = client.GetService('ProductService', version='v201502')
-
- # Create statement object to select a single product by an ID.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': product_id
- }
- }]
- query = 'WHERE id = :id'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get products by statement.
- response = product_service.getProductsByStatement(statement.ToStatement())
-
- if 'results' in response:
- # Update each local product object by changing its notes.
- updated_products = []
- for product in response['results']:
- product['notes'] = 'Product needs further review before activation.'
- updated_products.append(product)
-
- # Update products remotely.
- products = product_service.updateProducts(updated_products)
-
- # Display results.
- if products:
- for product in products:
- print ('Product with id \'%s\', name \'%s\', and '
- 'notes \'%s\' was updated.'
- % (product['id'], product['name'], product['notes']))
- else:
- print 'No products were updated.'
- else:
- print 'No products found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PRODUCT_ID)
diff --git a/examples/dfp/v201502/product_template_service/__init__.py b/examples/dfp/v201502/product_template_service/__init__.py
deleted file mode 100755
index a426ca48..00000000
--- a/examples/dfp/v201502/product_template_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201502/product_template_service/activate_product_templates.py b/examples/dfp/v201502/product_template_service/activate_product_templates.py
deleted file mode 100755
index a79cc2a9..00000000
--- a/examples/dfp/v201502/product_template_service/activate_product_templates.py
+++ /dev/null
@@ -1,82 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example activates a product template.
-
-To determine which product templates exist, run get_all_product_templates.py.
-
-Tags: ProductTemplateService.getProductTemplatesByStatement
-Tags: ProductTemplateService.performProductTemplateAction
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the id of the product template to activate.
-PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE'
-
-
-def main(client, product_template_id):
- # Initialize appropriate service.
- product_template_service = client.GetService(
- 'ProductTemplateService', version='v201502')
-
- # Create query.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': product_template_id
- }
- }]
- query = 'WHERE id = :id'
- statement = dfp.FilterStatement(query, values, 1)
-
- product_templates_activated = 0
-
- # Get product_templates by statement.
- while True:
- response = product_template_service.getProductTemplatesByStatement(
- statement.ToStatement())
- if 'results' in response:
- for product_template in response['results']:
- print ('Product template with id \'%s\' and name \'%s\' will be '
- 'activated.' % (product_template['id'],
- product_template['name']))
-
- # Perform action.
- result = product_template_service.performProductTemplateAction(
- {'xsi_type': 'ActivateProductTemplates'}, statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- product_templates_activated += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Display results.
- if product_templates_activated > 0:
- print ('Number of product templates '
- 'activated: %s' % product_templates_activated)
- else:
- print 'No product templates were activated.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PRODUCT_TEMPLATE_ID)
diff --git a/examples/dfp/v201502/product_template_service/create_product_templates.py b/examples/dfp/v201502/product_template_service/create_product_templates.py
deleted file mode 100755
index 5d761752..00000000
--- a/examples/dfp/v201502/product_template_service/create_product_templates.py
+++ /dev/null
@@ -1,108 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates a product template.
-
-To determine which product templates exist, run get_all_product_templates.py.
-
-Tags: ProductTemplateService.createProductTemplates
-Tags: NetworkService.getCurrentNetwork
-"""
-
-__author__ = 'Nicholas Chen'
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- product_template_service = client.GetService(
- 'ProductTemplateService', version='v201502')
- network_service = client.GetService(
- 'NetworkService', version='v201502')
-
- # Create a product template.
- product_template = {
- 'name': ('Product template #%d' % uuid.uuid4()),
- 'description': ('This product template creates standard proposal line '
- 'items targeting Chrome browsers with product '
- 'segmentation on ad units and geo targeting.'),
- 'nameMacro': (' - - '
- ' - '),
- 'productType': 'DFP',
- 'rateType': 'CPM',
- 'roadblockingType': 'ONE_OR_MORE',
- 'creativePlaceholders': [
- {
- 'size': {
- 'width': '728',
- 'height': '90'
- }
- },
- {
- 'size': {
- 'width': '300',
- 'height': '250'
- }
- }
- ],
- 'lineItemType': 'STANDARD',
- 'targeting': {
- # Set browser targeting to Chrome.
- 'browserTargeting': [
- {
- 'browsers': [
- {
- 'id': '500072'
- }
- ]
- }
- ]
- },
- 'productSegmentation': {
- 'geoSegment': {
- 'targetedLocations': [
- {'id': '2840',
- 'displayName': 'US'},
- {'id': '2344',
- 'displayName': 'Hong Kong'}
- ]
- },
- 'adUnitSegments': [{
- 'adUnitId': (network_service.getCurrentNetwork()[
- 'effectiveRootAdUnitId']),
- 'includeDescendants': 'true'
- }]
- }
- }
-
- # Create product templates on the server.
- product_templates = product_template_service.createProductTemplates(
- [product_template])
-
- if product_templates:
- for product_template in product_templates:
- print ('A product template with ID \'%s\' and name \'%s\' was '
- 'created.' % (product_template['id'], product_template['name']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/product_template_service/get_all_product_templates.py b/examples/dfp/v201502/product_template_service/get_all_product_templates.py
deleted file mode 100755
index 4e7f1e99..00000000
--- a/examples/dfp/v201502/product_template_service/get_all_product_templates.py
+++ /dev/null
@@ -1,57 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all product templates.
-
-To create product templates, run create_product_template_templates.py.
-
-Tags: ProductTemplateService.getProductTemplatesByStatement
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- product_template_service = client.GetService(
- 'ProductTemplateService', version='v201502')
-
- # Create a filter statement.
- statement = dfp.FilterStatement('ORDER BY id ASC')
-
- # Get product templates by statement.
- while True:
- response = product_template_service.getProductTemplatesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for product_template in response['results']:
- print ('Product template with id \'%s\' and name \'%s\' was found.' % (
- product_template['id'], product_template['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/product_template_service/get_sponsorship_product_templates.py b/examples/dfp/v201502/product_template_service/get_sponsorship_product_templates.py
deleted file mode 100755
index 25011c46..00000000
--- a/examples/dfp/v201502/product_template_service/get_sponsorship_product_templates.py
+++ /dev/null
@@ -1,63 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all sponsorship product templates.
-
-Tags: ProductTemplateService.getProductTemplatesByStatement
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- product_template_service = client.GetService(
- 'ProductTemplateService', version='v201502')
-
- # Create a statement to select all sponsorship product templates.
- values = [{
- 'key': 'lineItemType',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'SPONSORSHIP'
- }
- }]
- query = 'WHERE lineItemType = :lineItemType ORDER BY id ASC'
- statement = dfp.FilterStatement(query, values)
-
- # Get product templates by statement.
- while True:
- response = product_template_service.getProductTemplatesByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for product_template in response['results']:
- print ('Product template with id \'%s\' and name \'%s\' was found.' % (
- product_template['id'], product_template['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/product_template_service/update_product_templates.py b/examples/dfp/v201502/product_template_service/update_product_templates.py
deleted file mode 100755
index 00f10b12..00000000
--- a/examples/dfp/v201502/product_template_service/update_product_templates.py
+++ /dev/null
@@ -1,101 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates a product template's GeoTargeting.
-
-To determine which product templates exist, run get_all_product_templates.py.
-
-Tags: ProductTemplateService.getProductTemplatesByStatement
-Tags: ProductTemplateService.updateProductTemplates
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE'
-
-
-def main(client, product_template_id):
- # Initialize appropriate service.
- product_template_service = client.GetService(
- 'ProductTemplateService', version='v201502')
-
- # Create a statement to select a single product template by ID.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': product_template_id
- }
- }]
- query = 'WHERE id = :id ORDER BY id ASC'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get product templates by statement.
- response = product_template_service.getProductTemplatesByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- # Update each local product template object by appending a new geo-target.
- for product_template in response['results']:
- # Create geo-targeting for Canada to append.
- location = {
- 'id': '2124',
- 'displayName': 'Canada'
- }
-
- try:
- targeting = product_template['targeting']
-
- if 'geoTargeting' in targeting:
- geo_targeting = targeting['geoTargeting']
-
- if 'targetedLocations' in geo_targeting:
- geo_targeting['targetedLocations'].append(location)
- else:
- geo_targeting['targetedLocations'] = [location]
- else:
- targeting['geoTargeting'] = {
- 'targetedLocations': [location]
- }
- except KeyError:
- product_template['targeting'] = {
- 'geoTargeting': {
- 'targetedLocations': [location]
- }
- }
-
- # Update products remotely.
- product_templates = product_template_service.updateProductTemplates(
- [product_template])
-
- # Display results.
- if product_templates:
- for product_template in product_templates:
- print ('Product template with id \'%s\' and name \'%s\' was '
- 'updated.' % (product_template['id'], product_template['name']))
- else:
- print 'No product templates were updated.'
- else:
- print 'No product templates found to update.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PRODUCT_TEMPLATE_ID)
diff --git a/examples/dfp/v201502/proposal_line_item_service/__init__.py b/examples/dfp/v201502/proposal_line_item_service/__init__.py
deleted file mode 100755
index a426ca48..00000000
--- a/examples/dfp/v201502/proposal_line_item_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201502/proposal_line_item_service/archive_proposal_line_items.py b/examples/dfp/v201502/proposal_line_item_service/archive_proposal_line_items.py
deleted file mode 100755
index 1b586c2d..00000000
--- a/examples/dfp/v201502/proposal_line_item_service/archive_proposal_line_items.py
+++ /dev/null
@@ -1,82 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example archives a proposal line item.
-
-To determine which proposal line items exist, run
-get_all_proposal_line_items.py.
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the id of the proposal line item to archive.
-PROPOSAL_LINE_ITEM_ID = 'INSERT_PROPOSAL_LINE_ITEM_ID_HERE'
-
-
-def main(client, proposal_line_item_id):
- # Initialize appropriate service.
- proposal_line_item_service = client.GetService(
- 'ProposalLineItemService', version='v201502')
-
- # Create query.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': proposal_line_item_id
- }
- }]
- query = 'WHERE id = :id'
- statement = dfp.FilterStatement(query, values, 1)
-
- proposal_line_items_archived = 0
-
- # Get proposal line items by statement.
- while True:
- response = proposal_line_item_service.getProposalLineItemsByStatement(
- statement.ToStatement())
- if 'results' in response:
- for proposal_line_item in response['results']:
- print ('Proposal line item with id \'%s\', '
- 'belonging to proposal id \'%s\', and '
- 'name \'%s\' will be archived.' %
- (proposal_line_item['id'], proposal_line_item['proposalId'],
- proposal_line_item['name']))
-
- # Perform action.
- result = proposal_line_item_service.performProposalLineItemAction(
- {'xsi_type': 'ArchiveProposalLineItems'}, statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- proposal_line_items_archived += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Display results.
- if proposal_line_items_archived > 0:
- print ('Number of proposal line items '
- 'archived: %s' % proposal_line_items_archived)
- else:
- print 'No proposal line items were archived.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PROPOSAL_LINE_ITEM_ID)
diff --git a/examples/dfp/v201502/proposal_line_item_service/create_proposal_line_items.py b/examples/dfp/v201502/proposal_line_item_service/create_proposal_line_items.py
deleted file mode 100755
index 1449ce52..00000000
--- a/examples/dfp/v201502/proposal_line_item_service/create_proposal_line_items.py
+++ /dev/null
@@ -1,120 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates a new run-of-network proposal line item.
-
-To determine which proposal line items exist, run
-get_all_proposal_line_items.py. To determine which proposals exist, run
-get_all_proposals.py.
-"""
-
-__author__ = 'Nicholas Chen'
-
-from datetime import date
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set proposal that the created proposal line item will belong to.
-PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE'
-
-# Set the ID of the product that the proposal line items should be created from.
-PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE'
-
-# Set the ID of the rate card the proposal line items should be priced from.
-RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE'
-
-
-def main(client, proposal_id, product_id, rate_card_id):
- # Initialize appropriate service.
- proposal_line_item_service = client.GetService(
- 'ProposalLineItemService', version='v201502')
- network_service = client.GetService('NetworkService', version='v201502')
-
- # Get the root ad unit to target.
- root_ad_unit_id = (
- network_service.getCurrentNetwork()['effectiveRootAdUnitId'])
-
- # Create a single proposal line item.
- proposal_line_item = {
- 'name': 'Proposal line item #%s' % uuid.uuid4(),
- 'rateCardId': rate_card_id,
- 'productId': product_id,
- 'proposalId': proposal_id,
- 'targeting': {
- 'inventoryTargeting': {
- 'targetedAdUnits': {
- 'adUnitId': root_ad_unit_id
- }
- }
- },
- 'startDateTime': {
- 'date': {
- 'year': str(date.today().year),
- 'month': str(date.today().month),
- 'day': str(date.today().day)
- },
- 'hour': '23',
- 'minute': '59',
- 'second': '59'
- },
- 'endDateTime': {
- 'date': {
- 'year': str(date.today().year + 1),
- 'month': '9',
- 'day': '30'
- },
- 'hour': '0',
- 'minute': '0',
- 'second': '0'
- },
- 'deliveryRateType': 'EVENLY',
- 'creativeRotationType': 'OPTIMIZED',
- 'billingCap': 'CAPPED_CUMULATIVE',
- 'billingSource': 'THIRD_PARTY_VOLUME',
- 'goal': {
- 'units': '1000',
- 'unitType': 'IMPRESSIONS',
- },
- 'cost': {
- 'currencyCode': 'USD',
- 'microAmount': '2000000'
- },
- 'costPerUnit': {
- 'currencyCode': 'USD',
- 'microAmount': '2000000'
- },
- 'rateType': 'CPM',
- }
-
- # Add proposal line items.
- proposal_line_items = proposal_line_item_service.createProposalLineItems(
- [proposal_line_item])
-
- # Display results.
- for proposal_line_item in proposal_line_items:
- print ('Proposal line item with id \'%s\', belonging to proposal id \'%s\''
- ', and named \'%s\' was created.' %
- (proposal_line_item['id'], proposal_line_item['proposalId'],
- proposal_line_item['name']))
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PROPOSAL_ID, PRODUCT_ID, RATE_CARD_ID)
-
diff --git a/examples/dfp/v201502/proposal_line_item_service/get_all_proposal_line_items.py b/examples/dfp/v201502/proposal_line_item_service/get_all_proposal_line_items.py
deleted file mode 100755
index a1e8ae70..00000000
--- a/examples/dfp/v201502/proposal_line_item_service/get_all_proposal_line_items.py
+++ /dev/null
@@ -1,58 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all proposal line items.
-
-To create proposal line items, run create_proposal_line_items.py.
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- proposal_line_item_service = client.GetService(
- 'ProposalLineItemService', version='v201502')
-
- # Create a filter statement.
- statement = dfp.FilterStatement('ORDER BY id ASC')
-
- # Get proposal line items by statement.
- while True:
- response = proposal_line_item_service.getProposalLineItemsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for idx, proposal_line_item in enumerate(response['results'],
- start=statement.offset):
- print ('%s) Proposal line item with id \'%s\', belonging to proposal id'
- ' \'%s\', and named \'%s\' was found.' %
- (idx, proposal_line_item['id'], proposal_line_item['proposalId'],
- proposal_line_item['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/dfp/v201502/proposal_line_item_service/get_proposal_line_items_for_proposal.py
deleted file mode 100755
index 5206b61c..00000000
--- a/examples/dfp/v201502/proposal_line_item_service/get_proposal_line_items_for_proposal.py
+++ /dev/null
@@ -1,71 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all proposal line items that belong to a proposal.
-
-To create proposal line items, run create_proposal_line_items.py."""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set the id of the proposal to get proposal line items from.
-PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE'
-
-
-def main(client, proposal_id):
- # Initialize appropriate service.
- proposal_line_item_service = client.GetService(
- 'ProposalLineItemService', version='v201502')
-
- # Create statement object to only select proposal line items belonging to a
- # given proposal.
- values = [{
- 'key': 'proposalId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': proposal_id
- }
- }]
- query = 'WHERE proposalId = :proposalId ORDER BY id ASC'
- statement = dfp.FilterStatement(query, values)
-
- while True:
- # Get proposal line items by statement.
- response = proposal_line_item_service.getProposalLineItemsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- # Display results.
- for idx, proposal_line_item in enumerate(response['results'],
- start=statement.offset):
- print ('%s) Line item with id \'%s\', belonging to proposal id \'%s\', '
- 'and named \'%s\' was found.' % (
- idx, proposal_line_item['id'],
- proposal_line_item['proposalId'],
- proposal_line_item['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PROPOSAL_ID)
diff --git a/examples/dfp/v201502/proposal_line_item_service/update_proposal_line_items.py b/examples/dfp/v201502/proposal_line_item_service/update_proposal_line_items.py
deleted file mode 100755
index 7bfbab25..00000000
--- a/examples/dfp/v201502/proposal_line_item_service/update_proposal_line_items.py
+++ /dev/null
@@ -1,78 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates a proposal line item's notes.
-
-To determine which proposal line items exist,
-run get_all_proposal_line_items.py.
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-# Set id of the proposal line item to update.
-PROPOSAL_LINE_ITEM_ID = 'INSERT_PROPOSAL_LINE_ITEM_ID_HERE'
-
-
-def main(client, proposal_line_item_id):
- # Initialize appropriate service.
- proposal_line_item_service = client.GetService(
- 'ProposalLineItemService', version='v201502')
-
- # Create statement to select a proposal line item.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': proposal_line_item_id
- }
- }]
-
- query = 'WHERE id = :id'
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get proposal line items by statement.
- response = proposal_line_item_service.getProposalLineItemsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- # Update each the proposal line item's notes field.
- proposal_line_item = response['results'][0]
- proposal_line_item['notes'] = 'Proposal line item ready for submission.'
-
- # Update proposal line items remotely.
- proposal_line_items = proposal_line_item_service.updateProposalLineItems(
- [proposal_line_item])
-
- # Display results.
- if proposal_line_items:
- for proposal_line_item in proposal_line_items:
- print ('Line item with id \'%s\', belonging to proposal id \'%s\' and,'
- ' named \'%s\' was updated.' % (
- proposal_line_item['id'], proposal_line_item['proposalId'],
- proposal_line_item['name']))
- else:
- print 'No proposal line items were updated.'
- else:
- print 'No proposal line items found to update.'
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PROPOSAL_LINE_ITEM_ID)
diff --git a/examples/dfp/v201502/proposal_service/__init__.py b/examples/dfp/v201502/proposal_service/__init__.py
deleted file mode 100755
index a426ca48..00000000
--- a/examples/dfp/v201502/proposal_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201502/proposal_service/create_proposals.py b/examples/dfp/v201502/proposal_service/create_proposals.py
deleted file mode 100755
index dab9f002..00000000
--- a/examples/dfp/v201502/proposal_service/create_proposals.py
+++ /dev/null
@@ -1,77 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new proposals.
-
-To determine which proposals exist, run get_all_proposals.py."""
-
-__author__ = 'Nicholas Chen'
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE'
-PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE'
-SECONDARY_SALESPERSON_ID = 'INSERT_SECONDARY_SALESPERSON_ID_HERE'
-PRIMARY_TRAFFICKER_ID = 'INSERT_PRIMARY_TRAFFICKER_ID_HERE'
-
-
-def main(client, advertiser_id, primary_salesperson_id,
- secondary_salesperson_id, primary_trafficker_id):
- # Initialize appropriate services.
- proposal_service = client.GetService('ProposalService', version='v201502')
- network_service = client.GetService('NetworkService', version='v201502')
-
- # Create proposal objects.
- proposal = {
- 'name': 'Proposal #%s' % uuid.uuid4(),
- 'advertiser': {
- 'companyId': advertiser_id,
- 'type': 'ADVERTISER'
- },
- 'primarySalesperson': {
- 'userId': primary_salesperson_id,
- 'split': '75000'
- },
- 'secondarySalespeople': [{
- 'userId': secondary_salesperson_id,
- 'split': '25000'
- }],
- 'primaryTraffickerId': primary_trafficker_id,
- 'probabilityOfClose': '100000',
- 'budget': {
- 'microAmount': '100000000',
- 'currencyCode': network_service.getCurrentNetwork()['currencyCode']
- },
- 'billingCap': 'CAPPED_CUMULATIVE',
- 'billingSource': 'DFP_VOLUME'
- }
-
- # Add proposals.
- proposals = proposal_service.createProposals([proposals])
-
- # Display results.
- for proposal in proposals:
- print ('Proposal with id \'%s\' and name \'%s\' was created.'
- % (proposal['id'], proposal['name']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ADVERTISER_ID, PRIMARY_SALESPERSON_ID,
- SECONDARY_SALESPERSON_ID, PRIMARY_TRAFFICKER_ID)
diff --git a/examples/dfp/v201502/proposal_service/get_all_proposals.py b/examples/dfp/v201502/proposal_service/get_all_proposals.py
deleted file mode 100755
index 6bbf66ef..00000000
--- a/examples/dfp/v201502/proposal_service/get_all_proposals.py
+++ /dev/null
@@ -1,53 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all proposals.
-
-To create proposals, run create_proposals.py.
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- proposal_service = client.GetService('ProposalService', version='v201502')
-
- # Create a filter statement.
- statement = dfp.FilterStatement('ORDER BY id ASC')
-
- # Get proposals by statement.
- while True:
- response = proposal_service.getProposalsByStatement(statement.ToStatement())
- if 'results' in response:
- # Display results.
- for proposal in response['results']:
- print ('Proposal with id \'%s\' and name \'%s\' was found.' % (
- proposal['id'], proposal['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/proposal_service/get_proposals_by_statement.py b/examples/dfp/v201502/proposal_service/get_proposals_by_statement.py
deleted file mode 100755
index c203af87..00000000
--- a/examples/dfp/v201502/proposal_service/get_proposals_by_statement.py
+++ /dev/null
@@ -1,61 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all proposals that are currently 'PENDING_APPROVAL.'
-
-To create proposals, run create_proposals.py."""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- proposal_service = client.GetService('ProposalService', version='v201502')
-
- # Create statement object to select a single proposal by an ID.
- values = [{
- 'key': 'status',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'PENDING_APPROVAL'
- }
- }]
- query = 'WHERE status = :status ORDER BY id ASC'
-
- statement = dfp.FilterStatement(query, values)
-
- # Get proposals by statement.
- while True:
- response = proposal_service.getProposalsByStatement(statement.ToStatement())
- if 'results' in response:
- # Display results.
- for proposal in response['results']:
- print ('Proposal with id \'%s\' name \'%s\' was found.'
- % (proposal['id'], proposal['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/proposal_service/submit_proposals_for_approval.py b/examples/dfp/v201502/proposal_service/submit_proposals_for_approval.py
deleted file mode 100755
index d24f8938..00000000
--- a/examples/dfp/v201502/proposal_service/submit_proposals_for_approval.py
+++ /dev/null
@@ -1,73 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example approves a single proposal.
-
-To determine which proposals exist, run get_all_proposals.py."""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE'
-
-def main(client, proposal_id):
- # Initialize appropriate service.
- proposal_service = client.GetService('ProposalService', version='v201502')
-
- # Create query.
- values = [{
- 'key': 'proposalId',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': proposal_id
- }
- }]
- query = 'WHERE id = :proposalId'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
- proposals_approved = 0
-
- # Get proposals by statement.
- while True:
- response = proposal_service.getProposalsByStatement(statement.ToStatement())
- if 'results' in response:
- # Display results.
- for proposal in response['results']:
- print ('Proposal with id \'%s\', name \'%s\', and status \'%s\' will be'
- ' approved.' % (proposal['id'], proposal['name'],
- proposal['status']))
- # Perform action.
- result = proposal_service.performProposalAction(
- {'xsi_type': 'SubmitProposalsForApproval'}, statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- proposals_approved += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Display results.
- if proposals_approved > 0:
- print '\nNumber of proposals approved: %s' % proposals_approved
- else:
- print '\nNo proposals were approved.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PROPOSAL_ID)
diff --git a/examples/dfp/v201502/proposal_service/update_proposals.py b/examples/dfp/v201502/proposal_service/update_proposals.py
deleted file mode 100755
index 2394038c..00000000
--- a/examples/dfp/v201502/proposal_service/update_proposals.py
+++ /dev/null
@@ -1,72 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates the notes of a single proposal specified by ID.
-
-To determine which proposals exist, run get_all_proposals.py."""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE'
-
-
-def main(client, proposal_id):
- # Initialize appropriate service.
- proposal_service = client.GetService('ProposalService', version='v201502')
-
- # Create statement object to select a single proposal by an ID.
- values = [{
- 'key': 'proposalId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': proposal_id
- }
- }]
- query = 'WHERE id = :proposalId'
-
- statement = dfp.FilterStatement(query, values, 1)
-
- # Get proposals by statement.
- response = proposal_service.getProposalsByStatement(statement.ToStatement())
-
- if 'results' in response:
- # Update each local proposal object by changing its notes.
- updated_proposals = []
- for proposal in response['results']:
- proposal['notes'] = 'Proposal needs further review before approval.'
- updated_proposals.append(proposal)
-
- # Update proposals remotely.
- proposals = proposal_service.updateProposals(updated_proposals)
-
- # Display results.
- if proposals:
- for proposal in proposals:
- print ('Proposal with id \'%s\', name \'%s\', and '
- 'notes \'%s\' was updated.'
- % (proposal['id'], proposal['name'], proposal['notes']))
- else:
- print 'No proposals were updated.'
- else:
- print 'No proposals found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PROPOSAL_ID)
diff --git a/examples/dfp/v201502/publisher_query_language_service/__init__.py b/examples/dfp/v201502/publisher_query_language_service/__init__.py
deleted file mode 100755
index a426ca48..00000000
--- a/examples/dfp/v201502/publisher_query_language_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201502/publisher_query_language_service/fetch_match_tables.py b/examples/dfp/v201502/publisher_query_language_service/fetch_match_tables.py
deleted file mode 100755
index fd848da3..00000000
--- a/examples/dfp/v201502/publisher_query_language_service/fetch_match_tables.py
+++ /dev/null
@@ -1,57 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example fetches data from PQL tables and creates match table files."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import tempfile
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize a report downloader.
- report_downloader = client.GetDataDownloader(version='v201502')
-
- line_items_file = tempfile.NamedTemporaryFile(
- prefix='line_items_', suffix='.csv', mode='w', delete=False)
- ad_units_file = tempfile.NamedTemporaryFile(
- prefix='ad_units_', suffix='.csv', mode='w', delete=False)
-
- line_items_pql_query = ('SELECT Name, Id, Status FROM Line_Item ORDER BY Id '
- 'ASC')
- ad_units_pql_query = 'SELECT Name, Id FROM Ad_Unit ORDER BY Id ASC'
-
- # Downloads the response from PQL select statement to the specified file
- report_downloader.DownloadPqlResultToCsv(
- line_items_pql_query, line_items_file)
- report_downloader.DownloadPqlResultToCsv(
- ad_units_pql_query, ad_units_file)
-
- line_items_file.close()
- ad_units_file.close()
-
- print ('Saved line items to... %s' % line_items_file.name)
- print ('Saved ad units to... %s' % ad_units_file.name)
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/publisher_query_language_service/get_geo_targets.py b/examples/dfp/v201502/publisher_query_language_service/get_geo_targets.py
deleted file mode 100755
index e4679714..00000000
--- a/examples/dfp/v201502/publisher_query_language_service/get_geo_targets.py
+++ /dev/null
@@ -1,65 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets geographic criteria from the Geo_Target table.
-
-The types available to filter on include 'City', 'Country', 'Region', 'State',
-'Postal_Code', and 'DMA_Region' (i.e. Metro).
-
-A full list of available geo target types can be found at
-https://developers.google.com/doubleclick-publishers/docs/reference/v201502/PublisherQueryLanguageService
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import tempfile
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize a report downloader.
- report_downloader = client.GetDataDownloader(version='v201502')
-
- output_file = tempfile.NamedTemporaryFile(
- prefix='geo_target_type_', suffix='.csv', mode='w', delete=False)
-
- # Create bind value to select geo-targets of type 'City'.
- values = [{
- 'key': 'type',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'City'
- }
- }]
-
- pql_query = ('SELECT Name, Id FROM Geo_Target '
- 'WHERE targetable = true AND Type = :type')
-
- # Downloads the response from PQL select statement to the specified file
- report_downloader.DownloadPqlResultToCsv(
- pql_query, output_file, values)
- output_file.close()
-
- print ('Saved geo targets to... %s' % output_file.name)
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/publisher_query_language_service/get_line_items_named_like.py b/examples/dfp/v201502/publisher_query_language_service/get_line_items_named_like.py
deleted file mode 100755
index 37980e87..00000000
--- a/examples/dfp/v201502/publisher_query_language_service/get_line_items_named_like.py
+++ /dev/null
@@ -1,58 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all line items with names starting with 'line item'."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import tempfile
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize a report downloader.
- report_downloader = client.GetDataDownloader(version='v201502')
-
- output_file = tempfile.NamedTemporaryFile(
- prefix='line_items_named_like_', suffix='.csv', mode='w', delete=False)
-
- # Create bind value to select line items with names starting with 'line item'.
- values = [{
- 'key': 'name',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'line item%'
- }
- }]
-
- pql_query = ('SELECT Name, Id, Status FROM Line_Item '
- 'WHERE Name LIKE :name')
-
- # Downloads the response from PQL select statement to the specified file
- report_downloader.DownloadPqlResultToCsv(
- pql_query, output_file, values)
- output_file.close()
-
- print ('Saved line items to... %s' % output_file.name)
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/rate_card_service/__init__.py b/examples/dfp/v201502/rate_card_service/__init__.py
deleted file mode 100755
index a426ca48..00000000
--- a/examples/dfp/v201502/rate_card_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201502/rate_card_service/get_all_rate_cards.py b/examples/dfp/v201502/rate_card_service/get_all_rate_cards.py
deleted file mode 100755
index a541c1db..00000000
--- a/examples/dfp/v201502/rate_card_service/get_all_rate_cards.py
+++ /dev/null
@@ -1,55 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all rate cards.
-
-Tags: RateCardService.getRateCardsByStatement
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- rate_card_service = client.GetService('RateCardService', version='v201502')
-
- # Create a filter statement.
- statement = dfp.FilterStatement('ORDER BY id ASC')
-
- # Get rate cards by statement.
- while True:
- response = rate_card_service.getRateCardsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for rate_card in response['results']:
- print ('Rate card with id \'%s,\' name \'%s,\' and currency \'%s\' '
- 'was found.' % (rate_card['id'], rate_card['name'],
- rate_card['currencyCode']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/rate_card_service/get_rate_cards_priced_with_currency.py b/examples/dfp/v201502/rate_card_service/get_rate_cards_priced_with_currency.py
deleted file mode 100755
index 4f69f5e7..00000000
--- a/examples/dfp/v201502/rate_card_service/get_rate_cards_priced_with_currency.py
+++ /dev/null
@@ -1,64 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all rate cards that have a currency in US dollars.
-
-Tags: RateCardService.getRateCardsByStatement
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- rate_card_service = client.GetService('RateCardService', version='v201502')
-
- # Create a statement to get all rate cards using USD as currency.
- values = [{
- 'key': 'currencyCode',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'USD'
- }
- }]
- query = 'WHERE currencyCode = :currencyCode'
-
- statement = dfp.FilterStatement(query, values)
-
- # Get rate cards by statement.
- while True:
- response = rate_card_service.getRateCardsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for rate_card in response['results']:
- print ('Rate card with id \'%s,\' name \'%s,\' and currency \'%s\' '
- 'was found.' % (rate_card['id'], rate_card['name'],
- rate_card['currencyCode']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/report_service/__init__.py b/examples/dfp/v201502/report_service/__init__.py
deleted file mode 100755
index a426ca48..00000000
--- a/examples/dfp/v201502/report_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201502/report_service/run_delivery_report.py b/examples/dfp/v201502/report_service/run_delivery_report.py
deleted file mode 100755
index 205d5dc0..00000000
--- a/examples/dfp/v201502/report_service/run_delivery_report.py
+++ /dev/null
@@ -1,85 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example runs a report similar to the "Orders report" on the DFP
-website with additional attributes and can filter to include just one order.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-import tempfile
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-from googleads import errors
-
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-
-
-def main(client, order_id):
- # Create statement object to filter for an order.
- values = [{
- 'key': 'id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': order_id
- }
- }]
- filter_statement = {'query': 'WHERE ORDER_ID = :id',
- 'values': values}
-
- # Create report job.
- report_job = {
- 'reportQuery': {
- 'dimensions': ['ORDER_ID', 'ORDER_NAME'],
- 'dimensionAttributes': ['ORDER_TRAFFICKER', 'ORDER_START_DATE_TIME',
- 'ORDER_END_DATE_TIME'],
- 'statement': filter_statement,
- 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS',
- 'AD_SERVER_CTR', 'AD_SERVER_CPM_AND_CPC_REVENUE',
- 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'],
- 'dateRangeType': 'LAST_MONTH'
- }
- }
-
- # Initialize a DataDownloader.
- report_downloader = client.GetDataDownloader(version='v201502')
-
- try:
- # Run the report and wait for it to finish.
- report_job_id = report_downloader.WaitForReport(report_job)
- except errors.DfpReportError, e:
- print 'Failed to generate report. Error was: %s' % e
-
- # Change to your preferred export format.
- export_format = 'CSV_DUMP'
-
- report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
-
- # Download report data.
- report_downloader.DownloadReportToFile(
- report_job_id, export_format, report_file)
-
- report_file.close()
-
- # Display results.
- print 'Report job with id \'%s\' downloaded to:\n%s' % (
- report_job_id, report_file.name)
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID)
diff --git a/examples/dfp/v201502/report_service/run_inventory_report.py b/examples/dfp/v201502/report_service/run_inventory_report.py
deleted file mode 100755
index ed743e81..00000000
--- a/examples/dfp/v201502/report_service/run_inventory_report.py
+++ /dev/null
@@ -1,90 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example runs a report equal to the "Whole network report" on the
-DFP website.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-import tempfile
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-from googleads import errors
-
-
-def main(client):
- # Initialize appropriate service.
- network_service = client.GetService('NetworkService', version='v201502')
- # Initialize a DataDownloader.
- report_downloader = client.GetDataDownloader(version='v201502')
-
- # Get root ad unit id for network.
- root_ad_unit_id = (
- network_service.getCurrentNetwork()['effectiveRootAdUnitId'])
-
- # Set filter statement and bind value for reportQuery.
- values = [{
- 'key': 'parent_ad_unit_id',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': root_ad_unit_id
- }
- }]
- filter_statement = {'query': 'WHERE PARENT_AD_UNIT_ID = :parent_ad_unit_id',
- 'values': values}
-
- # Create report job.
- report_job = {
- 'reportQuery': {
- 'dimensions': ['DATE', 'AD_UNIT_NAME'],
- 'adUnitView': 'HIERARCHICAL',
- 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS',
- 'DYNAMIC_ALLOCATION_INVENTORY_LEVEL_IMPRESSIONS',
- 'DYNAMIC_ALLOCATION_INVENTORY_LEVEL_CLICKS',
- 'TOTAL_INVENTORY_LEVEL_IMPRESSIONS',
- 'TOTAL_INVENTORY_LEVEL_CPM_AND_CPC_REVENUE'],
- 'dateRangeType': 'LAST_WEEK',
- 'statement': filter_statement
- }
- }
-
- try:
- # Run the report and wait for it to finish.
- report_job_id = report_downloader.WaitForReport(report_job)
- except errors.DfpReportError, e:
- print 'Failed to generate report. Error was: %s' % e
-
- # Change to your preferred export format.
- export_format = 'CSV_DUMP'
-
- report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
-
- # Download report data.
- report_downloader.DownloadReportToFile(
- report_job_id, export_format, report_file)
-
- report_file.close()
-
- # Display results.
- print 'Report job with id \'%s\' downloaded to:\n%s' % (
- report_job_id, report_file.name)
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/report_service/run_reach_report.py b/examples/dfp/v201502/report_service/run_reach_report.py
deleted file mode 100755
index 1d26baa3..00000000
--- a/examples/dfp/v201502/report_service/run_reach_report.py
+++ /dev/null
@@ -1,66 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example runs a reach report."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-import tempfile
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-from googleads import errors
-
-
-def main(client):
- # Initialize a DataDownloader.
- report_downloader = client.GetDataDownloader(version='v201502')
-
- # Create report job.
- report_job = {
- 'reportQuery': {
- 'dimensions': ['LINE_ITEM_ID', 'LINE_ITEM_NAME'],
- 'columns': ['REACH_FREQUENCY', 'REACH_AVERAGE_REVENUE', 'REACH'],
- 'dateRangeType': 'REACH_LIFETIME'
- }
- }
-
- try:
- # Run the report and wait for it to finish.
- report_job_id = report_downloader.WaitForReport(report_job)
- except errors.DfpReportError, e:
- print 'Failed to generate report. Error was: %s' % e
-
- # Change to your preferred export format.
- export_format = 'CSV_DUMP'
-
- report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
-
- # Download report data.
- report_downloader.DownloadReportToFile(
- report_job_id, export_format, report_file)
-
- report_file.close()
-
- # Display results.
- print 'Report job with id \'%s\' downloaded to:\n%s' % (
- report_job_id, report_file.name)
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/report_service/run_report_with_custom_fields.py b/examples/dfp/v201502/report_service/run_report_with_custom_fields.py
deleted file mode 100755
index 21da37d1..00000000
--- a/examples/dfp/v201502/report_service/run_report_with_custom_fields.py
+++ /dev/null
@@ -1,107 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example runs a report that with custom fields found in the line
-items of an order.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-import tempfile
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-from googleads import errors
-
-# Set the ID of the order to get line items from.
-ORDER_ID = 'INSERT_ORDER_ID_HERE'
-
-
-def main(client, order_id):
- # Initialize appropriate service.
- line_item_service = client.GetService('LineItemService', version='v201502')
- # Initialize a DataDownloader.
- report_downloader = client.GetDataDownloader(version='v201502')
-
- # Filter for line items of a given order.
- values = [{
- 'key': 'orderId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': order_id
- }
- }]
- query = 'WHERE orderId = :orderId'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Collect all line item custom field IDs for an order.
- custom_field_ids = set()
-
- # Get users by statement.
- while True:
- response = line_item_service.getLineItemsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Get custom field IDs from the line items of an order.
- for line_item in response['results']:
- if 'customFieldValues' in line_item:
- for custom_field_value in line_item['customFieldValues']:
- custom_field_ids.add(custom_field_value['customFieldId'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Create statement object to filter for an order.
- filter_statement = {'query': query, 'values': values}
-
- # Create report job.
- report_job = {
- 'reportQuery': {
- 'dimensions': ['LINE_ITEM_ID', 'LINE_ITEM_NAME'],
- 'statement': filter_statement,
- 'columns': ['AD_SERVER_IMPRESSIONS'],
- 'dateRangeType': 'LAST_MONTH',
- 'customFieldIds': list(custom_field_ids)
- }
- }
-
- try:
- # Run the report and wait for it to finish.
- report_job_id = report_downloader.WaitForReport(report_job)
- except errors.DfpReportError, e:
- print 'Failed to generate report. Error was: %s' % e
-
- # Change to your preferred export format.
- export_format = 'CSV_DUMP'
-
- report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
-
- # Download report data.
- report_downloader.DownloadReportToFile(
- report_job_id, export_format, report_file)
-
- report_file.close()
-
- # Display results.
- print 'Report job with id \'%s\' downloaded to:\n%s' % (
- report_job_id, report_file.name)
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, ORDER_ID)
diff --git a/examples/dfp/v201502/report_service/run_sales_report.py b/examples/dfp/v201502/report_service/run_sales_report.py
deleted file mode 100755
index 4146cb51..00000000
--- a/examples/dfp/v201502/report_service/run_sales_report.py
+++ /dev/null
@@ -1,67 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example runs a report equal to the "Sales by salespersons report."
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-import tempfile
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-from googleads import errors
-
-
-def main(client):
- # Initialize a DataDownloader.
- report_downloader = client.GetDataDownloader(version='v201502')
-
- # Create report job.
- report_job = {
- 'reportQuery': {
- 'dimensions': ['SALESPERSON_ID', 'SALESPERSON_NAME'],
- 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CPM_AND_CPC_REVENUE',
- 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'],
- 'dateRangeType': 'LAST_MONTH'
- }
- }
-
- try:
- # Run the report and wait for it to finish.
- report_job_id = report_downloader.WaitForReport(report_job)
- except errors.DfpReportError, e:
- print 'Failed to generate report. Error was: %s' % e
-
- # Change to your preferred export format.
- export_format = 'CSV_DUMP'
-
- report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
-
- # Download report data.
- report_downloader.DownloadReportToFile(
- report_job_id, export_format, report_file)
-
- report_file.close()
-
- # Display results.
- print 'Report job with id \'%s\' downloaded to:\n%s' % (
- report_job_id, report_file.name)
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/suggested_ad_unit_service/__init__.py b/examples/dfp/v201502/suggested_ad_unit_service/__init__.py
deleted file mode 100755
index a426ca48..00000000
--- a/examples/dfp/v201502/suggested_ad_unit_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201502/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/dfp/v201502/suggested_ad_unit_service/approve_all_suggested_ad_units.py
deleted file mode 100755
index b73964cc..00000000
--- a/examples/dfp/v201502/suggested_ad_unit_service/approve_all_suggested_ad_units.py
+++ /dev/null
@@ -1,80 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example approves all suggested ad units with 50 or more requests.
-
-This feature is only available to DFP premium solution networks.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-THRESHOLD_NUMBER_OF_REQUESTS = '50'
-
-
-def main(client):
- # Initialize appropriate service.
- suggested_ad_unit_service = client.GetService(
- 'SuggestedAdUnitService', version='v201502')
-
- values = [{
- 'key': 'numRequests',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': THRESHOLD_NUMBER_OF_REQUESTS
- }
- }]
-
- query = 'WHERE numRequests > :numRequests'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
- num_approved_suggested_ad_units = 0
-
- # Get suggested ad units by statement.
- while True:
- response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Print suggested ad units that will be approved.
- for suggested_ad_unit in response['results']:
- print ('Suggested ad unit with id \'%s\', and number of requests \'%s\''
- ' will be approved.' % (suggested_ad_unit['id'],
- suggested_ad_unit['numRequests']))
-
- # Approve suggested ad units.
- result = suggested_ad_unit_service.performSuggestedAdUnitAction(
- {'xsi_type': 'ApproveSuggestedAdUnit'},
- statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- num_approved_suggested_ad_units += int(result['numChanges'])
- else:
- break
-
- if num_approved_suggested_ad_units > 0:
- print ('Number of suggested ad units approved: %s' %
- num_approved_suggested_ad_units)
- else:
- print 'No suggested ad units were approved.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
-
diff --git a/examples/dfp/v201502/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/dfp/v201502/suggested_ad_unit_service/get_all_suggested_ad_units.py
deleted file mode 100755
index 46ae8e49..00000000
--- a/examples/dfp/v201502/suggested_ad_unit_service/get_all_suggested_ad_units.py
+++ /dev/null
@@ -1,56 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all suggested ad units.
-
-To approve suggested ad units, run approve_suggested_ad_units.py. This feature
-is only available to DFP premium solution networks.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- suggested_ad_unit_service = client.GetService(
- 'SuggestedAdUnitService', version='v201502')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get suggested ad units by statement.
- while True:
- response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for suggested_ad_unit in response['results']:
- print ('Ad unit with id \'%s\' and number of requests \'%s\' was found.'
- % (suggested_ad_unit['id'], suggested_ad_unit['numRequests']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py b/examples/dfp/v201502/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py
deleted file mode 100755
index b6bf16df..00000000
--- a/examples/dfp/v201502/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py
+++ /dev/null
@@ -1,65 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets suggested ad units that have more than 50 requests.
-
-This feature is only available to DFP premium solution networks.
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- suggested_ad_unit_service = client.GetService(
- 'SuggestedAdUnitService', version='v201502')
-
- values = [{
- 'key': 'numRequests',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': '50'
- }
- }]
-
- query = 'WHERE numRequests > :numRequests'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Get suggested ad units by statement.
- while True:
- response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for suggested_ad_unit in response['results']:
- print ('Ad unit with id \'%s\' and number of requests \'%s\' was found.'
- % (suggested_ad_unit['id'], suggested_ad_unit['numRequests']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/team_service/__init__.py b/examples/dfp/v201502/team_service/__init__.py
deleted file mode 100755
index a426ca48..00000000
--- a/examples/dfp/v201502/team_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201502/team_service/create_teams.py b/examples/dfp/v201502/team_service/create_teams.py
deleted file mode 100755
index 53f6e12a..00000000
--- a/examples/dfp/v201502/team_service/create_teams.py
+++ /dev/null
@@ -1,64 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example creates new teams.
-
-To determine which teams exist, run get_all_teams.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: TeamService.createTeams
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-import uuid
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- team_service = client.GetService('TeamService', version='v201502')
-
- # Create team objects.
- teams = []
- for i in xrange(5):
- team = {
- 'name': 'Team %s' % uuid.uuid4(),
- 'hasAllCompanies': 'false',
- 'hasAllInventory': 'false',
- 'teamAccessType': 'READ_WRITE'
- }
- teams.append(team)
-
- # Add Teams.
- teams = team_service.createTeams(teams)
-
- # Display results.
- for team in teams:
- print ('Team with ID \'%s\' and name \'%s\' was created.'
- % (team['id'], team['name']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/team_service/get_all_teams.py b/examples/dfp/v201502/team_service/get_all_teams.py
deleted file mode 100755
index 2ca82f3f..00000000
--- a/examples/dfp/v201502/team_service/get_all_teams.py
+++ /dev/null
@@ -1,60 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all teams.
-
-To create teams, run create_teams.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: TeamService.getTeamsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- team_service = client.GetService('TeamService', version='v201502')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get users by statement.
- while True:
- response = team_service.getTeamsByStatement(statement.ToStatement())
- if 'results' in response:
- # Display results.
- for team in response['results']:
- print ('Team with ID \'%s\' and name \'%s\' was found.'
- % (team['id'], team['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/team_service/get_teams_by_statement.py b/examples/dfp/v201502/team_service/get_teams_by_statement.py
deleted file mode 100755
index db9c9e60..00000000
--- a/examples/dfp/v201502/team_service/get_teams_by_statement.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets a single team by ID.
-
-To create teams, run create_teams.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: TeamService.getTeamsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-TEAM_ID = 'INSERT_TEAM_ID_HERE'
-
-
-def main(client, team_id):
- # Initialize appropriate service.
- team_service = client.GetService('TeamService', version='v201502')
-
- # Create a filter statement to select a single team by ID.
- values = [{
- 'key': 'teamId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': team_id
- }
- }]
- query = 'WHERE id = :teamId'
- statement = dfp.FilterStatement(query, values)
-
- while True:
- # Get teams by statement.
- response = team_service.getTeamsByStatement(statement.ToStatement())
- if 'results' in response:
- # Display results.
- for team in response['results']:
- print ('Team with id \'%s\' and name \'%s\' was found.'
- % (team['id'], team['name']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, TEAM_ID)
diff --git a/examples/dfp/v201502/team_service/update_teams.py b/examples/dfp/v201502/team_service/update_teams.py
deleted file mode 100755
index a38c104a..00000000
--- a/examples/dfp/v201502/team_service/update_teams.py
+++ /dev/null
@@ -1,84 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates teams by adding an ad unit to a team.
-
-To determine which teams exist, run get_all_teams.py. To determine which ad
-units exist, run get_all_ad_units.py
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: TeamService.getTeamsByStatement, TeamService.updateTeams
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE'
-TEAM_ID = 'INSERT_TEAM_ID_HERE'
-
-
-def main(client, ad_unit_id, team_id):
- # Initialize appropriate service.
- team_service = client.GetService('TeamService', version='v201502')
-
- # Create a filter statement to select a single team by ID.
- values = [{
- 'key': 'teamId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': team_id
- }
- }]
- query = 'WHERE id = :teamId'
- statement = dfp.FilterStatement(query, values)
-
- # Get teams by statement.
- response = team_service.getTeamsByStatement(statement.ToStatement())
-
- if 'results' in response:
- updated_teams = []
- # Update each local team object by adding the ad unit to it.
- for team in response['results']:
- ad_unit_ids = []
- if 'adUnitIds' in team:
- ad_unit_ids = team['adUnitIds']
- # Don't add the ad unit if the team has all inventory already.
- if not team['hasAllInventory']:
- ad_unit_ids.append(ad_unit_id)
- team['adUnitIds'] = ad_unit_ids
- updated_teams.append(team)
-
- # Update teams on the server.
- teams = team_service.updateTeams(updated_teams)
-
- # Display results.
- for team in teams:
- print ('Team with id \'%s\' and name \'%s\' was updated.'
- % (team['id'], team['name']))
- else:
- print 'No teams found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, AD_UNIT_ID, TEAM_ID)
diff --git a/examples/dfp/v201502/user_service/__init__.py b/examples/dfp/v201502/user_service/__init__.py
deleted file mode 100755
index a426ca48..00000000
--- a/examples/dfp/v201502/user_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201502/user_service/create_users.py b/examples/dfp/v201502/user_service/create_users.py
deleted file mode 100755
index 055270a9..00000000
--- a/examples/dfp/v201502/user_service/create_users.py
+++ /dev/null
@@ -1,59 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example creates new users.
-
-To determine which users exist, run get_all_users.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-NEW_USER_EMAIL_ADDRESS = 'INSERT_EMAIL_ADDRESS_HERE'
-NEW_USER_NAME = 'INSERT_NAME_HERE'
-
-
-def main(client, email, name):
- # Initialize appropriate service.
- user_service = client.GetService('UserService', version='v201502')
-
- # Create user objects.
- users = [
- {
- 'email': email,
- 'name': name,
- 'preferredLocale': 'en_US'
- }
- ]
- for user in users:
- # Set the system defined ID of the trafficker role.
- # To determine what other roles exist, run get_all_roles.py.
- user['roleId'] = '-7'
-
- # Add users.
- users = user_service.createUsers(users)
-
- # Display results.
- for user in users:
- print ('User with id \'%s\', email \'%s\', and role \'%s\' was created.'
- % (user['id'], user['email'], user['roleName']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, NEW_USER_EMAIL_ADDRESS, NEW_USER_NAME)
diff --git a/examples/dfp/v201502/user_service/deactivate_users.py b/examples/dfp/v201502/user_service/deactivate_users.py
deleted file mode 100755
index a0bbbd96..00000000
--- a/examples/dfp/v201502/user_service/deactivate_users.py
+++ /dev/null
@@ -1,73 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example deactivates a user.
-
-Deactivated users can no longer make requests to the API. The user making the
-request cannot deactivate itself. To determine which users exist, run
-get_all_users.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-USER_ID = 'INSERT_USER_ID_TO_DEACTIVATE_HERE'
-
-
-def main(client, user_id):
- # Initialize appropriate service.
- user_service = client.GetService('UserService', version='v201502')
-
- # Create query.
- values = [{
- 'key': 'userId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': user_id
- }
- }]
- query = 'WHERE id = :userId'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Get users by statement.
- response = user_service.getUsersByStatement(statement.ToStatement())
- users = response['results'] if 'results' in response else []
-
- for user in users:
- print ('User with id \'%s\', email \'%s\', and status \'%s\' will be '
- 'deactivated.'
- % (user['id'], user['email'],
- {'true': 'ACTIVE', 'false': 'INACTIVE'}[user['isActive']]))
- print 'Number of users to be deactivated: %s' % len(users)
-
- # Perform action.
- result = user_service.performUserAction({'xsi_type': 'DeactivateUsers'},
- statement.ToStatement())
-
- # Display results.
- if result and int(result['numChanges']) > 0:
- print 'Number of users deactivated: %s' % result['numChanges']
- else:
- print 'No users were deactivated.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, USER_ID)
diff --git a/examples/dfp/v201502/user_service/get_all_roles.py b/examples/dfp/v201502/user_service/get_all_roles.py
deleted file mode 100755
index d9bced06..00000000
--- a/examples/dfp/v201502/user_service/get_all_roles.py
+++ /dev/null
@@ -1,46 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all roles.
-
-This sample can be used to determine which role id is needed when getting and
-creating users."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- user_service = client.GetService('UserService', version='v201502')
-
- # Get all roles.
- roles = user_service.getAllRoles()
-
- # Display results.
- for role in roles:
- print ('Role with id \'%s\' and name \'%s\' was found.'
- % (role['id'], role['name']))
-
- print '\nNumber of results found: %s' % len(roles)
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/user_service/get_all_users.py b/examples/dfp/v201502/user_service/get_all_users.py
deleted file mode 100755
index 012601e8..00000000
--- a/examples/dfp/v201502/user_service/get_all_users.py
+++ /dev/null
@@ -1,50 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets all users. To create users, run create_users.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- user_service = client.GetService('UserService', version='v201502')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get users by statement.
- while True:
- response = user_service.getUsersByStatement(statement.ToStatement())
- if 'results' in response:
- # Display results.
- for user in response['results']:
- print ('User with id \'%s\', email \'%s\', and role \'%s\' was found.'
- % (user['id'], user['email'], user['roleName']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/user_service/get_current_user.py b/examples/dfp/v201502/user_service/get_current_user.py
deleted file mode 100755
index a5739c0e..00000000
--- a/examples/dfp/v201502/user_service/get_current_user.py
+++ /dev/null
@@ -1,40 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets the current user."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- user_service = client.GetService('UserService', version='v201502')
-
- # Get current user.
- user = user_service.getCurrentUser()
-
- # Display results.
- print ('User with id \'%s\', email \'%s\', and role \'%s\' was found.'
- % (user['id'], user['email'], user['roleName']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/user_service/get_users_by_statement.py b/examples/dfp/v201502/user_service/get_users_by_statement.py
deleted file mode 100755
index 48461c51..00000000
--- a/examples/dfp/v201502/user_service/get_users_by_statement.py
+++ /dev/null
@@ -1,59 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example gets a user by its id.
-
-To create users, run create_user.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-USER_ID = 'INSERT_USER_ID_TO_FIND_HERE'
-
-
-def main(client, user_id):
- # Initialize appropriate service.
- user_service = client.GetService('UserService', version='v201502')
-
- # Create query.
- values = [{
- 'key': 'userId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': user_id
- }
- }]
- query = 'WHERE id = :userId'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Get users by statement.
- response = user_service.getUsersByStatement(statement.ToStatement())
- users = response['results'] if 'results' in response else []
-
- for user in users:
- # Display results.
- print ('User with id \'%s\', email \'%s\', and role \'%s\' was found.'
- % (user['id'], user['email'], user['roleName']))
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, USER_ID)
diff --git a/examples/dfp/v201502/user_service/update_users.py b/examples/dfp/v201502/user_service/update_users.py
deleted file mode 100755
index 08317efc..00000000
--- a/examples/dfp/v201502/user_service/update_users.py
+++ /dev/null
@@ -1,66 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This code example updates a user by adding " Sr." to the end of their name.
-
-To determine which users exist, run get_all_users.py."""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-USER_ID = 'INSERT_USER_ID_TO_UPDATE_HERE'
-
-
-def main(client, user_id):
- # Initialize appropriate service.
- user_service = client.GetService('UserService', version='v201502')
-
- # Create query.
- values = [{
- 'key': 'userId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': user_id
- }
- }]
- query = 'WHERE id = :userId'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Get users by statement.
- response = user_service.getUsersByStatement(statement.ToStatement())
-
- if 'results' in response:
- users = response['results']
- for user in users:
- user['name'] += ' Sr.'
-
- # Update users on server.
- users = user_service.updateUsers(users)
- for user in users:
- print ('User with id \'%s\' and name \'%s\' was updated.'
- % (user['id'], user['name']))
- else:
- print 'No users found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, USER_ID)
diff --git a/examples/dfp/v201502/user_team_association_service/__init__.py b/examples/dfp/v201502/user_team_association_service/__init__.py
deleted file mode 100755
index a426ca48..00000000
--- a/examples/dfp/v201502/user_team_association_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201502/user_team_association_service/create_user_team_associations.py b/examples/dfp/v201502/user_team_association_service/create_user_team_associations.py
deleted file mode 100755
index 724e2345..00000000
--- a/examples/dfp/v201502/user_team_association_service/create_user_team_associations.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example adds a user to a team by creating an association between them.
-
-To determine which teams exists, run get_all_teams.py. To determine which
-users exist, run get_all_users.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: UserTeamAssociationService.createUserTeamAssociations
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-TEAM_ID = 'INSERT_TEAM_ID_HERE'
-USER_IDS = ['INSERT_USER_IDS_TO_ASSOCIATE_TO_TEAM_HERE']
-
-
-def main(client, team_id, user_ids):
- # Initialize appropriate service.
- user_team_association_service = client.GetService(
- 'UserTeamAssociationService', version='v201502')
-
- user_team_associations = []
- for user_id in user_ids:
- user_team_associations.append(
- {
- 'teamId': team_id,
- 'userId': user_id
- })
-
- # Create the user team association on the server.
- user_team_associations = (
- user_team_association_service.createUserTeamAssociations(
- user_team_associations))
-
- # Display results.
- if user_team_associations:
- for user_team_association in user_team_associations:
- print ('A user team association between user with ID \'%s\' and team with'
- ' ID \'%s\'was created.' % (user_team_association['userId'],
- user_team_association['teamId']))
- else:
- print 'No user team associations created.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, TEAM_ID, USER_IDS)
diff --git a/examples/dfp/v201502/user_team_association_service/delete_user_team_associations.py b/examples/dfp/v201502/user_team_association_service/delete_user_team_associations.py
deleted file mode 100755
index ee27770b..00000000
--- a/examples/dfp/v201502/user_team_association_service/delete_user_team_associations.py
+++ /dev/null
@@ -1,83 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example removes the user from all its teams.
-
-To determine which users exist, run get_all_users.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: UserTeamAssociationService.performUserTeamAssociationAction
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-USER_ID = 'INSERT_USER_ID_HERE'
-
-
-def main(client, user_id):
- # Initialize appropriate service.
- user_team_association_service = client.GetService(
- 'UserTeamAssociationService', version='v201502')
-
- # Create filter text to select user team associations by the user ID.
- values = [{
- 'key': 'userId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': user_id
- }
- }]
- query = 'WHERE userId = :userId'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Get user team associations by statement.
- response = user_team_association_service.getUserTeamAssociationsByStatement(
- statement.ToStatement())
- user_team_associations = response['results'] if 'results' in response else []
-
- for user_team_association in user_team_associations:
- print ('User team association between user with ID \'%s\' and team with '
- 'ID \'%s\' will be deleted.' % (user_team_association['userId'],
- user_team_association['teamId']))
- print ('Number of teams that the user will be removed from: %s' %
- len(user_team_associations))
-
- # Perform action.
- result = user_team_association_service.performUserTeamAssociationAction(
- {'xsi_type': 'DeleteUserTeamAssociations'},
- {'query': query, 'values': values})
-
- # Display results.
- if result and int(result['numChanges']) > 0:
- print ('Number of teams that the user was removed from: %s'
- % result['numChanges'])
- else:
- print 'No user team associations were deleted.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, USER_ID)
diff --git a/examples/dfp/v201502/user_team_association_service/get_all_user_team_associations.py b/examples/dfp/v201502/user_team_association_service/get_all_user_team_associations.py
deleted file mode 100755
index e2b9c816..00000000
--- a/examples/dfp/v201502/user_team_association_service/get_all_user_team_associations.py
+++ /dev/null
@@ -1,64 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all user team associations.
-
-To create user team associations, run create_user_team_assocations.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: UserTeamAssociationService.getUserTeamAssociationsByStatement
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- user_team_association_service = client.GetService(
- 'UserTeamAssociationService', version='v201502')
-
- # Create a filter statement.
- statement = dfp.FilterStatement()
-
- # Get user team associations by statement.
- while True:
- response = user_team_association_service.getUserTeamAssociationsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for user_team_association in response['results']:
- print ('User team association between user with ID \'%s\' and team with'
- ' ID \'%s\' was found.' % (user_team_association['userId'],
- user_team_association['teamId']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/user_team_association_service/get_user_team_associations_for_user.py b/examples/dfp/v201502/user_team_association_service/get_user_team_associations_for_user.py
deleted file mode 100755
index ed2c7015..00000000
--- a/examples/dfp/v201502/user_team_association_service/get_user_team_associations_for_user.py
+++ /dev/null
@@ -1,75 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets all user team associations for a single user.
-
-To determine which users exist, run get_all_users.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: UserTeamAssociationService.getUserTeamAssociation
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-USER_ID = 'INSERT_USER_ID_HERE'
-
-
-def main(client, user_id):
- # Initialize appropriate service.
- user_team_association_service = client.GetService(
- 'UserTeamAssociationService', version='v201502')
-
- # Create query.
- values = [{
- 'key': 'userId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': user_id
- }
- }]
- query = 'WHERE userId = :userId'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Get user team associations by statement.
- while True:
- response = user_team_association_service.getUserTeamAssociationsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for user_team_association in response['results']:
- print ('User team association between user with ID \'%s\' and team with'
- ' ID \'%s\' was found.' % (user_team_association['userId'],
- user_team_association['teamId']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, USER_ID)
diff --git a/examples/dfp/v201502/user_team_association_service/update_user_team_associations.py b/examples/dfp/v201502/user_team_association_service/update_user_team_associations.py
deleted file mode 100755
index d2b3f380..00000000
--- a/examples/dfp/v201502/user_team_association_service/update_user_team_associations.py
+++ /dev/null
@@ -1,89 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example updates user team associations.
-
-It updates a user team association by setting the overridden access type to read
-only for all teams that the user belongs to. To determine which users exists,
-run get_all_users.py.
-
-The LoadFromStorage method is pulling credentials and properties from a
-"googleads.yaml" file. By default, it looks for this file in your home
-directory. For more information, see the "Caching authentication information"
-section of our README.
-
-Tags: UserTeamAssociationService.getUserTeamAssociationsByStatement
-Tags: UserTeamAssociationService.updateUserTeamAssociations
-"""
-
-__author__ = ('Nicholas Chen',
- 'Joseph DiLallo')
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-USER_ID = 'INSERT_USER_ID_TO_UPDATE_HERE'
-
-
-def main(client, user_id):
- # Initialize appropriate service.
- user_team_association_service = client.GetService(
- 'UserTeamAssociationService', version='v201502')
-
- # Create filter text to select user team associations by the user ID.
- values = [{
- 'key': 'userId',
- 'value': {
- 'xsi_type': 'NumberValue',
- 'value': user_id
- }
- }]
- query = 'WHERE userId = :userId'
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
-
- # Get user team associations by statement.
- response = user_team_association_service.getUserTeamAssociationsByStatement(
- statement.ToStatement())
-
- if 'results' in response:
- updated_user_team_associations = []
- # Update each local user team association to read only access.
- for user_team_association in response['results']:
- user_team_association['overriddenTeamAccessType'] = 'READ_ONLY'
- updated_user_team_associations.append(user_team_association)
-
- # Update user team associations on the server.
- user_team_associations = (
- user_team_association_service.updateUserTeamAssociations(
- updated_user_team_associations))
-
- # Display results.
- if user_team_associations:
- for user_team_association in user_team_associations:
- print ('User team association between user with ID \'%s\' and team with'
- ' ID \'%s\' was updated.' % (user_team_association['userId'],
- user_team_association['teamId']))
- else:
- print 'No user team associations were updated.'
- else:
- print 'No user team associations found to update.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, USER_ID)
diff --git a/examples/dfp/v201502/workflow_request_service/__init__.py b/examples/dfp/v201502/workflow_request_service/__init__.py
deleted file mode 100755
index a426ca48..00000000
--- a/examples/dfp/v201502/workflow_request_service/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/examples/dfp/v201502/workflow_request_service/approve_workflow_approval_requests.py b/examples/dfp/v201502/workflow_request_service/approve_workflow_approval_requests.py
deleted file mode 100755
index 99d68931..00000000
--- a/examples/dfp/v201502/workflow_request_service/approve_workflow_approval_requests.py
+++ /dev/null
@@ -1,99 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example approves all workflow approval requests belonging to a proposal.
-
-To determine which workflow approval requests exist, run
-get_all_workflow_approval_requests.py.
-
-Tags: WorkflowRequestService.getWorkflowRequestsByStatement
-Tags: WorkflowRequestService.performWorkflowRequestAction
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE'
-
-
-def main(client, proposal_id):
- # Initialize appropriate service.
- workflow_request_service = client.GetService('WorkflowRequestService',
- version='v201502')
-
- # Create query.
- values = [
- {
- 'key': 'entityId',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': proposal_id
- }
- },
- {
- 'key': 'entityType',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'PROPOSAL'
- }
- },
- {
- 'key': 'type',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'WORKFLOW_APPROVAL_REQUEST'
- }
- }
- ]
- query = ('WHERE entityId = :entityId and entityType = :entityType '
- 'and type = :type')
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
- workflow_approval_requests_approved = 0
-
- # Get workflow approval requests by statement.
- while True:
- response = workflow_request_service.getWorkflowRequestsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for workflow_approval_request in response['results']:
- print ('Workflow approval request with id \'%s\' will be'
- ' approved.' % workflow_approval_request['id'])
- # Perform action.
- result = workflow_request_service.performWorkflowRequestAction(
- {'xsi_type': 'ApproveWorkflowApprovalRequests'},
- statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- workflow_approval_requests_approved += int(result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Display results.
- if workflow_approval_requests_approved > 0:
- print ('\nNumber of workflow approval requests approved: %s' %
- workflow_approval_requests_approved)
- else:
- print '\nNo workflow approval requests were approved.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PROPOSAL_ID)
diff --git a/examples/dfp/v201502/workflow_request_service/get_workflow_approval_requests_by_statement.py b/examples/dfp/v201502/workflow_request_service/get_workflow_approval_requests_by_statement.py
deleted file mode 100755
index 09da9783..00000000
--- a/examples/dfp/v201502/workflow_request_service/get_workflow_approval_requests_by_statement.py
+++ /dev/null
@@ -1,69 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets workflow approval requests.
-
-Workflow approval requests must be approved or rejected for a workflow to
-finish.
-
-Tags: WorkflowRequestService.getWorkflowRequestsByStatement
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- workflow_request_service = client.GetService('WorkflowRequestService',
- version='v201502')
-
- # Create statement object to select all workflow approval requests.
- values = [{
- 'key': 'type',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'WORKFLOW_APPROVAL_REQUEST'
- }
- }]
- query = 'WHERE type = :type'
-
- statement = dfp.FilterStatement(query, values)
-
- # Get proposals by statement.
- while True:
- response = workflow_request_service.getWorkflowRequestsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for workflow_request in response['results']:
- print ('Workflow approval request with id \'%s\' for %s with id \'%s\' '
- 'was found.' % (workflow_request['id'],
- workflow_request['entityType'],
- workflow_request['entityId']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/workflow_request_service/get_workflow_external_condition_requests_by_statement.py b/examples/dfp/v201502/workflow_request_service/get_workflow_external_condition_requests_by_statement.py
deleted file mode 100755
index 3c839d83..00000000
--- a/examples/dfp/v201502/workflow_request_service/get_workflow_external_condition_requests_by_statement.py
+++ /dev/null
@@ -1,69 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This example gets workflow external condition requests.
-
-Workflow external condition requests must be triggered or skipped for a workflow
-to finish.
-
-Tags: WorkflowRequestService.getWorkflowRequestsByStatement
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-
-def main(client):
- # Initialize appropriate service.
- workflow_request_service = client.GetService('WorkflowRequestService',
- version='v201502')
-
- # Create statement object to select a single proposal by an ID.
- values = [{
- 'key': 'type',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'WORKFLOW_EXTERNAL_CONDITION_REQUEST'
- }
- }]
- query = 'WHERE type = :type'
-
- statement = dfp.FilterStatement(query, values)
-
- # Get proposals by statement.
- while True:
- response = workflow_request_service.getWorkflowRequestsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for workflow_request in response['results']:
- print ('Workflow external condition request with id \'%s\' for %s '
- 'with id \'%s\' was found.' % (workflow_request['id'],
- workflow_request['entityType'],
- workflow_request['entityId']))
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- print '\nNumber of results found: %s' % response['totalResultSetSize']
-
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client)
diff --git a/examples/dfp/v201502/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/dfp/v201502/workflow_request_service/trigger_workflow_external_condition_requests.py
deleted file mode 100755
index 0f4881af..00000000
--- a/examples/dfp/v201502/workflow_request_service/trigger_workflow_external_condition_requests.py
+++ /dev/null
@@ -1,103 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""This triggers all workflow external condition requests for a proposal.
-
-Workflow external condition requests must be triggered or skipped for a workflow
-to finish. To determine which proposals exist, run get_all_proposals.py.
-
-Tags: WorkflowRequestService.getWorkflowRequestsByStatement
-Tags: WorkflowRequestService.performWorkflowRequestAction
-"""
-
-__author__ = 'Nicholas Chen'
-
-# Import appropriate modules from the client library.
-from googleads import dfp
-
-PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE'
-
-
-def main(client, proposal_id):
- # Initialize appropriate service.
- workflow_request_service = client.GetService('WorkflowRequestService',
- version='v201502')
-
- # Create query.
- values = [
- {
- 'key': 'entityId',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': proposal_id
- }
- },
- {
- 'key': 'entityType',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'PROPOSAL'
- }
- },
- {
- 'key': 'type',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'WORKFLOW_EXTERNAL_CONDITION_REQUEST'
- }
- }
- ]
- query = ('WHERE entityId = :entityId and entityType = :entityType '
- 'and type = :type')
-
- # Create a filter statement.
- statement = dfp.FilterStatement(query, values)
- workflow_external_condition_requests_triggered = 0
-
- # Get workflow external condition requests by statement.
- while True:
- response = workflow_request_service.getWorkflowRequestsByStatement(
- statement.ToStatement())
- if 'results' in response:
- # Display results.
- for workflow_request in response['results']:
- print ('Workflow external condition request with id \'%s\' for %s '
- 'with id \'%s\' will be triggered.' %
- (workflow_request['id'],
- workflow_request['entityType'],
- workflow_request['entityId']))
- # Perform action.
- result = workflow_request_service.performWorkflowRequestAction(
- {'xsi_type': 'TriggerWorkflowExternalConditionRequests'},
- statement.ToStatement())
- if result and int(result['numChanges']) > 0:
- workflow_external_condition_requests_triggered += int(
- result['numChanges'])
- statement.offset += dfp.SUGGESTED_PAGE_LIMIT
- else:
- break
-
- # Display results.
- if workflow_external_condition_requests_triggered > 0:
- print ('\nNumber of workflow external condition requests triggered: %s' %
- workflow_external_condition_requests_triggered)
- else:
- print '\nNo workflow external condition requests were triggered.'
-
-if __name__ == '__main__':
- # Initialize client object.
- dfp_client = dfp.DfpClient.LoadFromStorage()
- main(dfp_client, PROPOSAL_ID)
diff --git a/googleads.yaml b/googleads.yaml
index f2362f43..582baf6f 100644
--- a/googleads.yaml
+++ b/googleads.yaml
@@ -1,34 +1,124 @@
+# AdWordsClient configurations
adwords:
+ #############################################################################
+ # Required Fields #
+ #############################################################################
developer_token: INSERT_DEVELOPER_TOKEN_HERE
- user_agent: INSERT_USER_AGENT_HERE
+ #############################################################################
+ # Optional Fields #
+ #############################################################################
+ # client_customer_id: INSERT_CLIENT_CUSTOMER_ID_HERE
+ # user_agent: INSERT_USER_AGENT_HERE
+ # partial_failure: True
+ # validate_only: True
+ #############################################################################
+ # OAuth2 Configuration #
+ # Below you may provide credentials for either the installed application or #
+ # service account flows. Remove or comment the lines for the flow you're #
+ # not using. #
+ #############################################################################
+ # The following values configure the client for the installed application
+ # flow.
client_id: INSERT_OAUTH_2_CLIENT_ID_HERE
client_secret: INSERT_CLIENT_SECRET_HERE
refresh_token: INSERT_REFRESH_TOKEN_HERE
-# The following values are optional:
-# client_customer_id: INSERT_CLIENT_CUSTOMER_ID_HERE
-# partial_failure: True
-# validate_only: True
+ # The following values configure the client for the service account flow.
+ # path_to_private_key_file: INSERT_PATH_TO_JSON_KEY_FILE_HERE
+ # delegated_account: INSERT_DOMAIN_WIDE_DELEGATION_ACCOUNT
+ #############################################################################
+ # ReportDownloader Headers #
+ # Below you may specify boolean values for optional headers that will be #
+ # applied to all requests made by the ReportDownloader utility by default. #
+ #############################################################################
+ # report_downloader_headers:
+ # skip_report_header: False
+ # skip_column_header: False
+ # skip_report_summary: False
+ # use_raw_enum_values: False
-dfp:
- application_name: INSERT_APPLICATION_NAME_HERE
- client_id: INSERT_OAUTH_2_CLIENT_ID_HERE
- client_secret: INSERT_CLIENT_SECRET_HERE
- refresh_token: INSERT_REFRESH_TOKEN_HERE
-# The following values are optional:
-# network_code: INSERT_NETWORK_CODE_HERE
-dfa:
- username: INSERT_DFA_USERNAME_HERE
+# AdManagerClient configurations
+ad_manager:
+ #############################################################################
+ # Required Fields #
+ #############################################################################
application_name: INSERT_APPLICATION_NAME_HERE
- client_id: INSERT_OAUTH_2_CLIENT_ID_HERE
- client_secret: INSERT_CLIENT_SECRET_HERE
- refresh_token: INSERT_REFRESH_TOKEN_HERE
-# The following values are optional:
+ #############################################################################
+ # Optional Fields #
+ #############################################################################
+ # The network_code is required for all services except NetworkService:
+ # network_code: INSERT_NETWORK_CODE_HERE
+ # delegated_account: INSERT_DOMAIN_WIDE_DELEGATION_ACCOUNT
+ #############################################################################
+ # OAuth2 Configuration #
+ # Below you may provide credentials for either the installed application or #
+ # service account (recommended) flows. Remove or comment the lines for the #
+ # flow you're not using. #
+ #############################################################################
+ # The following values configure the client for the service account flow.
+ path_to_private_key_file: INSERT_PATH_TO_JSON_KEY_FILE_HERE
+ # delegated_account: INSERT_DOMAIN_WIDE_DELEGATION_ACCOUNT
+ # The following values configure the client for the installed application
+ # flow.
+ # client_id: INSERT_OAUTH_2_CLIENT_ID_HERE
+ # client_secret: INSERT_CLIENT_SECRET_HERE
+ # refresh_token: INSERT_REFRESH_TOKEN_HERE
+
-# The following are optional settings for using a proxy.
-# proxy_info:
-# host: INSERT_HOST_HERE
-# port: INSERT_PROXY_PORT_HERE
-# The following values are optional:
-# disable_ssl_certificate_validation: False
-# ca_certs: INSERT_PATH_HERE
+# Common configurations:
+###############################################################################
+# Compression (optional) #
+# Below you may specify whether to accept and automatically decompress gzip #
+# encoded SOAP requests. By default, gzip compression is not enabled. #
+###############################################################################
+# enable_compression: False
+###############################################################################
+# Logging configuration (optional) #
+# Below you may specify the logging configuration. This will be provided as #
+# an input to logging.config.dictConfig. #
+###############################################################################
+# logging:
+ # version: 1
+ # disable_existing_loggers: False
+ # formatters:
+ # default_fmt:
+ # format: ext://googleads.util.LOGGER_FORMAT
+ # handlers:
+ # default_handler:
+ # class: logging.StreamHandler
+ # formatter: default_fmt
+ # level: INFO
+ # loggers:
+ ## Configure root logger
+ # "":
+ # handlers: [default_handler]
+ # level: INFO
+###############################################################################
+# Proxy configurations (optional) #
+# Below you may specify an HTTP or HTTPS Proxy to be used when making API #
+# requests. Note: You must specify the scheme used for the proxy endpoint. #
+# #
+# For additional information on configuring these values, see: #
+# http://docs.python-requests.org/en/master/user/advanced/#proxies #
+###############################################################################
+# proxy_config:
+ # http: INSERT_HTTP_PROXY_URI_HERE
+ # https: INSERT_HTTPS_PROXY_URI_HERE
+ # If specified, the given cafile will only be used if certificate validation
+ # is not disabled.
+ # cafile: INSERT_PATH_HERE
+ # disable_certificate_validation: False
+################################################################################
+# Utilities Included (optional) #
+# Below you may specify whether the library will include utilities used in the #
+# user agent. By default, the library will include utilities used in the user #
+# agent. #
+################################################################################
+# include_utilities_in_user_agent: True
+################################################################################
+# Custom HTTP headers (optional) #
+# Specify one or more custom headers to pass along with all requests to #
+# the API. #
+################################################################################
+# custom_http_headers:
+# X-My-Header: 'content'
diff --git a/googleads/__init__.py b/googleads/__init__.py
index e0beb1d9..78b5fa78 100644
--- a/googleads/__init__.py
+++ b/googleads/__init__.py
@@ -14,6 +14,5 @@
"""A client library for Google's SOAP Ads APIs."""
-from adwords import AdWordsClient
-from dfa import DfaClient
-from dfp import DfpClient
+from .ad_manager import AdManagerClient
+from .adwords import AdWordsClient
diff --git a/googleads/ad_manager.py b/googleads/ad_manager.py
new file mode 100644
index 00000000..50a1dcba
--- /dev/null
+++ b/googleads/ad_manager.py
@@ -0,0 +1,1003 @@
+# Copyright 2013 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Client library for the Ad Manager API."""
+
+
+import csv
+import datetime
+import logging
+import numbers
+import os
+import sys
+import time
+from urllib.request import build_opener
+
+import pytz
+import googleads.common
+import googleads.errors
+
+# The default application name.
+DEFAULT_APPLICATION_NAME = 'INSERT_APPLICATION_NAME_HERE'
+# The endpoint server for Ad Manager.
+DEFAULT_ENDPOINT = 'https://ads.google.com'
+# The suggested page limit per page fetched from the API.
+SUGGESTED_PAGE_LIMIT = 500
+# The chunk size used for report downloads.
+_CHUNK_SIZE = 16 * 1024
+
+
+_data_downloader_logger = logging.getLogger(
+ '%s.%s' % (__name__, 'data_downloader'))
+
+
+# A giant dictionary of Ad Manager versions and the services they support.
+_SERVICE_MAP = {
+ 'v202111': (
+ 'ActivityGroupService', 'ActivityService', 'AdExclusionRuleService',
+ 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService',
+ 'CdnConfigurationService', 'CmsMetadataService', 'CompanyService',
+ 'ContactService', 'ContentBundleService', 'ContentService',
+ 'CreativeReviewService', 'CreativeService', 'CreativeSetService',
+ 'CreativeTemplateService', 'CreativeWrapperService',
+ 'CustomFieldService', 'CustomTargetingService',
+ 'DaiAuthenticationKeyService', 'DaiEncodingProfileService',
+ 'ForecastService', 'InventoryService', 'LabelService',
+ 'LineItemCreativeAssociationService', 'LineItemService',
+ 'LineItemTemplateService', 'LiveStreamEventService',
+ 'MobileApplicationService', 'NativeStyleService', 'NetworkService',
+ 'OrderService', 'PlacementService', 'ProposalLineItemService',
+ 'ProposalService', 'PublisherQueryLanguageService', 'ReportService',
+ 'SiteService', 'StreamActivityMonitorService',
+ 'SuggestedAdUnitService', 'TeamService', 'TargetingPresetService',
+ 'UserService', 'UserTeamAssociationService'),
+ 'v202202': (
+ 'ActivityGroupService', 'ActivityService', 'AdjustmentService',
+ 'AdRuleService', 'AudienceSegmentService', 'CdnConfigurationService',
+ 'CmsMetadataService', 'CompanyService', 'ContactService',
+ 'ContentBundleService', 'ContentService', 'CreativeReviewService',
+ 'CreativeService', 'CreativeSetService', 'CreativeTemplateService',
+ 'CreativeWrapperService', 'CustomFieldService',
+ 'CustomTargetingService', 'DaiAuthenticationKeyService',
+ 'DaiEncodingProfileService', 'ForecastService', 'InventoryService',
+ 'LabelService', 'LineItemCreativeAssociationService',
+ 'LineItemService', 'LineItemTemplateService',
+ 'LiveStreamEventService', 'MobileApplicationService',
+ 'NativeStyleService', 'NetworkService', 'OrderService',
+ 'PlacementService', 'ProposalLineItemService', 'ProposalService',
+ 'PublisherQueryLanguageService', 'ReportService', 'SiteService',
+ 'StreamActivityMonitorService', 'SuggestedAdUnitService',
+ 'TeamService', 'TargetingPresetService', 'UserService',
+ 'UserTeamAssociationService', 'YieldGroupService'),
+ 'v202205': (
+ 'ActivityGroupService', 'ActivityService', 'AdjustmentService',
+ 'AdRuleService', 'AudienceSegmentService', 'CdnConfigurationService',
+ 'CmsMetadataService', 'CompanyService', 'ContactService',
+ 'ContentBundleService', 'ContentService', 'CreativeReviewService',
+ 'CreativeService', 'CreativeSetService', 'CreativeTemplateService',
+ 'CreativeWrapperService', 'CustomFieldService',
+ 'CustomTargetingService', 'DaiAuthenticationKeyService',
+ 'DaiEncodingProfileService', 'ForecastService', 'InventoryService',
+ 'LabelService', 'LineItemCreativeAssociationService',
+ 'LineItemService', 'LineItemTemplateService',
+ 'LiveStreamEventService', 'MobileApplicationService',
+ 'NativeStyleService', 'NetworkService', 'OrderService',
+ 'PlacementService', 'ProposalLineItemService', 'ProposalService',
+ 'PublisherQueryLanguageService', 'ReportService', 'SiteService',
+ 'StreamActivityMonitorService', 'SuggestedAdUnitService',
+ 'TeamService', 'TargetingPresetService', 'UserService',
+ 'UserTeamAssociationService', 'YieldGroupService'),
+ 'v202208': (
+ 'ActivityGroupService', 'ActivityService', 'AdjustmentService',
+ 'AdRuleService', 'AudienceSegmentService', 'CdnConfigurationService',
+ 'CmsMetadataService', 'CompanyService', 'ContactService',
+ 'ContentBundleService', 'ContentService', 'CreativeReviewService',
+ 'CreativeService', 'CreativeSetService', 'CreativeTemplateService',
+ 'CreativeWrapperService', 'CustomFieldService',
+ 'CustomTargetingService', 'DaiAuthenticationKeyService',
+ 'DaiEncodingProfileService', 'ForecastService', 'InventoryService',
+ 'LabelService', 'LineItemCreativeAssociationService',
+ 'LineItemService', 'LineItemTemplateService',
+ 'LiveStreamEventService', 'MobileApplicationService',
+ 'NativeStyleService', 'NetworkService', 'OrderService',
+ 'PlacementService', 'ProposalLineItemService', 'ProposalService',
+ 'PublisherQueryLanguageService', 'ReportService', 'SiteService',
+ 'StreamActivityMonitorService', 'SuggestedAdUnitService',
+ 'TeamService', 'TargetingPresetService', 'UserService',
+ 'UserTeamAssociationService', 'YieldGroupService'),
+}
+
+
+class AdManagerClient(googleads.common.CommonClient):
+ """A central location to set headers and create web service clients.
+
+ Attributes:
+ oauth2_client: A googleads.oauth2.GoogleOAuth2Client used to authorize your
+ requests.
+ application_name: An arbitrary string which will be used to identify your
+ application
+ network_code: A string identifying the network code of the network you are
+ accessing. All requests other than some NetworkService calls require
+ this header to be set.
+ """
+
+ # The key in the storage yaml which contains Ad Manager data.
+ _YAML_KEY = 'ad_manager'
+ # A list of values which must be provided to use Ad Manager.
+ _REQUIRED_INIT_VALUES = ('application_name',)
+ # A list of values which may optionally be provided when using Ad Manager.
+ _OPTIONAL_INIT_VALUES = (
+ 'network_code', googleads.common.ENABLE_COMPRESSION_KEY)
+ # The format of SOAP service WSDLs. A server, version, and service name need
+ # to be formatted in.
+ _SOAP_SERVICE_FORMAT = '%s/apis/ads/publisher/%s/%s?wsdl'
+
+ @classmethod
+ def LoadFromString(cls, yaml_doc):
+ """Creates a AdManagerClient with information stored in a yaml string.
+
+ Args:
+ yaml_doc: The yaml string containing the cached Ad Manager data.
+
+ Returns:
+ A AdManagerClient initialized with the values cached in the yaml string.
+
+ Raises:
+ A GoogleAdsValueError if the given yaml string does not contain the
+ information necessary to instantiate a client object - either a
+ required key was missing or an OAuth2 key was missing.
+ """
+ return cls(**googleads.common.LoadFromString(
+ yaml_doc, cls._YAML_KEY, cls._REQUIRED_INIT_VALUES,
+ cls._OPTIONAL_INIT_VALUES))
+
+ @classmethod
+ def LoadFromStorage(cls, path=None):
+ """Creates a AdManagerClient with information stored in a yaml file.
+
+ Args:
+ [optional]
+ path: str The path to the file containing cached Ad Manager data.
+
+ Returns:
+ A AdManagerClient initialized with the values cached in the file.
+
+ Raises:
+ A GoogleAdsValueError if the given yaml file does not contain the
+ information necessary to instantiate a client object - either a
+ required key was missing or an OAuth2 key was missing.
+ """
+ if path is None:
+ path = os.path.join(os.path.expanduser('~'), 'googleads.yaml')
+
+ return cls(**googleads.common.LoadFromStorage(
+ path, cls._YAML_KEY, cls._REQUIRED_INIT_VALUES,
+ cls._OPTIONAL_INIT_VALUES))
+
+ def __init__(self, oauth2_client, application_name, network_code=None,
+ cache=None, proxy_config=None, timeout=3600,
+ custom_http_headers=None,
+ enable_compression=False):
+ """Initializes a AdManagerClient.
+
+ For more information on these arguments, see our SOAP headers guide:
+ https://developers.google.com/ad-manager/docs/soap_xml
+
+ Args:
+ oauth2_client: A googleads.oauth2.GoogleOAuth2Client used to authorize
+ your requests.
+ application_name: An arbitrary string which will be used to identify your
+ application
+ [optional]
+ network_code: A string identifying the network code of the network you are
+ accessing. All requests other than getAllNetworks require this header
+ to be set.
+ cache: A subclass of zeep.cache.Base. If not set,
+ this will default to a basic file cache. To disable caching for Zeep,
+ pass googleads.common.ZeepServiceProxy.NO_CACHE.
+ proxy_config: A googleads.common.ProxyConfig instance or None if a proxy
+ isn't being used.
+ timeout: An integer timeout in MS for connections made to Ad Manager.
+ custom_http_headers: A dictionary with HTTP headers to add to outgoing
+ requests.
+ enable_compression: A boolean indicating if you want to enable compression
+ of the SOAP response. If True, the SOAP response will use gzip
+ compression, and will be decompressed for you automatically.
+ """
+ super(AdManagerClient, self).__init__()
+
+ if not application_name or (DEFAULT_APPLICATION_NAME in application_name):
+ raise googleads.errors.GoogleAdsValueError(
+ 'Application name must be set and not contain the default [%s]' %
+ DEFAULT_APPLICATION_NAME)
+
+ self.oauth2_client = oauth2_client
+ self.application_name = application_name
+ self.network_code = network_code
+ self.cache = cache
+ self.custom_http_headers = custom_http_headers
+ self._header_handler = _AdManagerHeaderHandler(
+ self, enable_compression, custom_http_headers)
+ self.proxy_config = (proxy_config if proxy_config
+ else googleads.common.ProxyConfig())
+
+ if enable_compression:
+ self.application_name = '%s (gzip)' % self.application_name
+
+ self.timeout = timeout
+
+ 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 string identifying the Ad Manager version to connect to. This
+ defaults to what is currently the latest version. This will be
+ updated in future releases to point to what is then the
+ latest version.
+ server: A string identifying the webserver hosting the Ad Manager API.
+
+ Returns:
+ A googleads.common.GoogleSoapService instance which has the headers
+ and proxy configured for use.
+
+ Raises:
+ A GoogleAdsValueError if the service or version provided do not exist.
+ """
+ if not server:
+ server = DEFAULT_ENDPOINT
+
+ server = server[:-1] if server[-1] == '/' else server
+
+ try:
+ service = googleads.common.GetServiceClassForLibrary()(
+ self._SOAP_SERVICE_FORMAT % (server, version, service_name),
+ self._header_handler,
+ _AdManagerPacker,
+ self.proxy_config,
+ self.timeout,
+ version,
+ cache=self.cache)
+
+ return service
+ except googleads.errors.GoogleAdsSoapTransportError:
+ if version in _SERVICE_MAP:
+ if service_name in _SERVICE_MAP[version]:
+ raise
+ else:
+ raise googleads.errors.GoogleAdsValueError(
+ 'Unrecognized service for the Ad Manager API. Service given: %s '
+ 'Supported services: %s'
+ % (service_name, _SERVICE_MAP[version]))
+ else:
+ raise googleads.errors.GoogleAdsValueError(
+ 'Unrecognized version of the Ad Manager API. Version given: %s '
+ 'Supported versions: %s' % (version, _SERVICE_MAP.keys()))
+
+ 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:
+ [optional]
+ version: A string identifying the Ad Manager version to connect to.
+ This defaults to what is currently the latest version. This will be
+ updated in future releases to point to what is then the
+ latest version.
+ server: A string identifying the webserver hosting the Ad Manager API.
+
+ Returns:
+ A DataDownloader tied to this AdManagerClient, ready to download reports.
+ """
+ if not server:
+ server = DEFAULT_ENDPOINT
+
+ return DataDownloader(self, version, server)
+
+
+class _AdManagerHeaderHandler(googleads.common.HeaderHandler):
+ """Handler which sets the headers for an Ad Manager SOAP call."""
+
+ # The library signature for Ad Manager, to be appended to all
+ # application_names.
+ _PRODUCT_SIG = 'DfpApi-Python'
+ # The name of the WSDL-defined SOAP Header class used in all requests.
+ _SOAP_HEADER_CLASS = 'ns0:SoapRequestHeader'
+
+ def __init__(
+ self, ad_manager_client, enable_compression, custom_http_headers=None):
+ """Initializes an AdManagerHeaderHandler.
+
+ Args:
+ ad_manager_client: The AdManagerClient whose data will be used to fill
+ in the headers. We retain a reference to this object so that the
+ header handler picks up changes to the client.
+ enable_compression: A boolean indicating if you want to enable compression
+ of the SOAP response. If True, the SOAP response will use gzip
+ compression, and will be decompressed for you automatically.
+ custom_http_headers: A dictionary of custom HTTP headers to send with all
+ requests.
+ """
+ self._ad_manager_client = ad_manager_client
+ self.enable_compression = enable_compression
+ self.custom_http_headers = custom_http_headers or {}
+
+ 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_HEADER_CLASS)
+ header.networkCode = self._ad_manager_client.network_code
+ header.applicationName = ''.join([
+ self._ad_manager_client.application_name,
+ googleads.common.GenerateLibSig(self._PRODUCT_SIG)])
+ return header
+
+ def GetHTTPHeaders(self):
+ """Returns the HTTP headers required for request authorization.
+
+ Returns:
+ A dictionary containing the required headers.
+ """
+ http_headers = self._ad_manager_client.oauth2_client.CreateHttpHeader()
+ if self.enable_compression:
+ http_headers['accept-encoding'] = 'gzip'
+
+ http_headers.update(self.custom_http_headers)
+
+ return http_headers
+
+
+class _AdManagerPacker(googleads.common.SoapPacker):
+ """A utility applying customized packing logic for Ad Manager."""
+
+ @classmethod
+ 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 Manager-specific logic for SOAP,
+ if applicable. Otherwise, returns the given object unmodified.
+ """
+ if isinstance(obj, (datetime.datetime, datetime.date)):
+ return cls.AdManagerDateTimePacker(obj, version)
+ return obj
+
+ @classmethod
+ 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 Manager SOAP.
+ """
+
+ if isinstance(value, datetime.datetime):
+ if value.tzinfo is None:
+ raise googleads.errors.GoogleAdsValueError(
+ 'Datetime %s is not timezone aware.' % value
+ )
+ return {
+ 'date': cls.AdManagerDateTimePacker(value.date(), version),
+ 'hour': value.hour,
+ 'minute': value.minute,
+ 'second': value.second,
+ 'timeZoneId': value.tzinfo.zone,
+ }
+ elif isinstance(value, datetime.date):
+ return {'year': value.year, 'month': value.month, 'day': value.day}
+
+
+@googleads.common.RegisterUtility('StatementBuilder')
+class StatementBuilder(object):
+ """Provides the ability to programmatically construct PQL queries."""
+
+ class _OrderByPair(object):
+ """Stores and serializes a pair of column/ascending values."""
+
+ def __init__(self, column, ascending):
+ """Initializes a pair of column/ascending values.
+
+ Args:
+ column: a string specifying the column name.
+ ascending: a boolean specifying sort order ascending or descending.
+ """
+ self.column = column
+ self.ascending = ascending
+
+ def __repr__(self):
+ """The string representation of this class is valid PQL."""
+ return '%s %s' % (self.column, 'ASC' if self.ascending else 'DESC')
+
+ _SELECT_PART = 'SELECT %s FROM %s'
+ _WHERE_PART = 'WHERE %s'
+ _ORDER_BY_PART = 'ORDER BY %s'
+ _LIMIT_PART = 'LIMIT %s'
+ _OFFSET_PART = 'OFFSET %s'
+
+ def __init__(self, select_columns=None, from_table=None, where=None,
+ order_by=None, order_ascending=True,
+ limit=SUGGESTED_PAGE_LIMIT, offset=0,
+ version=sorted(_SERVICE_MAP.keys())[-1]):
+ """Initializes StatementBuilder.
+
+ Args:
+ select_columns: a comma separated string of column names.
+ from_table: a string specifying the table to select from.
+ where: a string with the where clause.
+ order_by: a string with the order by clause.
+ order_ascending: a boolean specifying sort order ascending or descending.
+ limit: an integer with the limit clause.
+ offset: an integer with the offset clause.
+ version: A string identifying the Ad Manager version this statement is
+ compatible with. This defaults to what is currently the latest
+ version. This will be updated in future releases to point to what is
+ then the latest version.
+ """
+ self._select = select_columns
+ self._from_ = from_table
+ self._where = where
+ self.limit = limit
+ self.offset = offset
+ self._version = version
+ if order_by:
+ self._order_by = self._OrderByPair(column=order_by,
+ ascending=order_ascending)
+ else:
+ self._order_by = None
+ self._values = {} # Use a dict to prevent duplicates
+
+ def ToStatement(self):
+ """Builds a PQL string from the current state.
+
+ Returns:
+ A string representation of the PQL statement.
+ """
+
+ if self._select and not self._from_:
+ raise googleads.errors.GoogleAdsError('FROM clause required with SELECT.')
+
+ if self._from_ and not self._select:
+ raise googleads.errors.GoogleAdsError('SELECT clause required with FROM.')
+
+ query = []
+
+ if self._select:
+ query.append(self._SELECT_PART % (self._select, self._from_))
+
+ if self._where:
+ query.append(self._WHERE_PART % self._where)
+
+ if self._order_by:
+ query.append(self._ORDER_BY_PART % self._order_by)
+
+ if self.limit:
+ query.append(self._LIMIT_PART % self.limit)
+
+ if self.offset is not None:
+ query.append(self._OFFSET_PART % self.offset)
+
+ return {'query': ' '.join(query),
+ 'values': (PQLHelper.GetQueryValuesFromDict(
+ self._values, self._version) if self._values else None)}
+
+ def Select(self, columns):
+ """Adds a SELECT clause.
+
+ Args:
+ columns: A comma separated string specifying the columns.
+
+ Returns:
+ A reference to the StatementBuilder.
+ """
+ self._select = columns
+ return self
+
+ def From(self, table):
+ """Adds a FROM clause.
+
+ Args:
+ table: A string specifying the table.
+
+ Returns:
+ A reference to the StatementBuilder
+ """
+ self._from_ = table
+ return self
+
+ def Where(self, clause):
+ """Adds a WHERE clause.
+
+ Args:
+ clause: A string specifying the where clause.
+
+ Returns:
+ A reference to the StatementBuilder.
+ """
+ self._where = clause
+ return self
+
+ def Limit(self, limit=SUGGESTED_PAGE_LIMIT):
+ """Adds a LIMIT clause.
+
+ Args:
+ limit: An integer specifying the limit value.
+
+ Returns:
+ A reference to the StatementBuilder.
+ """
+ self.limit = limit
+ return self
+
+ def Offset(self, value):
+ """Adds an OFFSET clause.
+
+ Args:
+ value: An integer specifying the offset value.
+
+ Returns:
+ A reference to the StatementBuilder.
+ """
+ self.offset = value
+ return self
+
+ def OrderBy(self, column, ascending=True):
+ """Adds an ORDER BY clause.
+
+ Args:
+ column: A string specifying the column to order by.
+ ascending: A bool to indicate ascending vs descending.
+
+ Returns:
+ A reference to the StatementBuilder
+ """
+ self._order_by = self._OrderByPair(column=column,
+ ascending=ascending)
+ return self
+
+ def WithBindVariable(self, key, value):
+ """Binds a value to a variable in the statement.
+
+ Args:
+ key: A string identifying the variable.
+ value: A object of an acceptable type specifying the value.
+
+ Returns:
+ A reference to the StatementBuilder.
+ """
+
+ # Make this call to throw the exception here if there is a problem
+ PQLHelper.GetValueRepresentation(value, self._version)
+
+ self._values[key] = value
+ return self
+
+
+class PQLHelper(object):
+ """Utility class for PQL."""
+
+ @classmethod
+ 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. This defaults to what is currently the latest
+ version. This will be updated in future releases to point to what is
+ then the latest version.
+
+ Returns:
+ A list of variables formatted for PQL statements which are compatible with
+ a particular API version.
+ """
+ return [{
+ 'key': key,
+ 'value': cls.GetValueRepresentation(value, version)
+ } for key, value in d.items()]
+
+ @classmethod
+ 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. This defaults to what is currently the latest
+ version. This will be updated in future releases to point to what is
+ then the latest version.
+
+ Returns:
+ The value formatted for PQL statements which are compatible with a
+ particular API version.
+ """
+ if isinstance(value, str):
+ return {'value': value, 'xsi_type': 'TextValue'}
+ elif isinstance(value, bool):
+ return {'value': value, 'xsi_type': 'BooleanValue'}
+ elif isinstance(value, numbers.Number):
+ return {'value': value, 'xsi_type': 'NumberValue'}
+ # It's important that datetime is checked for before date
+ # because isinstance(datetime.datetime.now(), datetime.date) is True
+ elif isinstance(value, datetime.datetime):
+ if value.tzinfo is None:
+ raise googleads.errors.GoogleAdsValueError(
+ 'Datetime %s is not timezone aware.' % value
+ )
+
+ return {
+ 'xsi_type': 'DateTimeValue',
+ 'value': {
+ 'date': {
+ 'year': value.year,
+ 'month': value.month,
+ 'day': value.day,
+ },
+ 'hour': value.hour,
+ 'minute': value.minute,
+ 'second': value.second,
+ 'timeZoneId': value.tzinfo.zone,
+ }
+ }
+ elif isinstance(value, datetime.date):
+ return {
+ 'xsi_type': 'DateValue',
+ 'value': {
+ 'year': value.year,
+ 'month': value.month,
+ 'day': value.day,
+ }
+ }
+ elif isinstance(value, list):
+ if value and not all(isinstance(x, type(value[0])) for x in value):
+ raise googleads.errors.GoogleAdsValueError('Cannot pass more than one '
+ 'type in a set.')
+
+ return {
+ 'xsi_type': 'SetValue',
+ 'values': [cls.GetValueRepresentation(v, version) for v in value]
+ }
+ else:
+ raise googleads.errors.GoogleAdsValueError(
+ 'Can\'t represent unknown type: %s.' % type(value))
+
+
+@googleads.common.RegisterUtility('FilterStatement')
+class FilterStatement(object):
+ """A statement object for PQL and get*ByStatement queries.
+
+ The FilterStatement object allows for user control of limit/offset. It
+ automatically limits queries to the suggested page limit if not explicitly
+ set.
+ """
+
+ def __init__(self, where_clause='', values=None, limit=SUGGESTED_PAGE_LIMIT,
+ offset=0):
+ self.where_clause = where_clause
+ self.values = values
+ self.limit = limit
+ self.offset = offset
+
+ def ToStatement(self):
+ """Returns this statement object in the format Ad Manager requires."""
+ return {'query': ('%s LIMIT %d OFFSET %d' %
+ (self.where_clause, self.limit, self.offset)),
+ 'values': self.values}
+
+
+class DataDownloader(object):
+ """A utility that can be used to download reports and PQL result sets."""
+
+ def __init__(self, ad_manager_client, version=sorted(_SERVICE_MAP.keys())[-1],
+ server=None):
+ """Initializes a DataDownloader.
+
+ Args:
+ ad_manager_client: The AdManagerClient whose attributes will be used to
+ authorize your report download and PQL query requests.
+ [optional]
+ version: A string identifying the Ad Manager version to connect to.
+ This defaults to what is currently the latest version. This will be
+ updated in future releases to point to what is then the
+ latest version.
+ server: A string identifying the webserver hosting the Ad Manager API.
+ """
+ if not server:
+ server = DEFAULT_ENDPOINT
+
+ if server[-1] == '/':
+ server = server[:-1]
+
+ self._ad_manager_client = ad_manager_client
+ self._version = version
+ self._server = server
+ self._report_service = None
+ self._pql_service = None
+ self.proxy_config = self._ad_manager_client.proxy_config
+ handlers = self.proxy_config.GetHandlers()
+ self.url_opener = build_opener(*handlers)
+
+ if self._ad_manager_client.custom_http_headers:
+ self.url_opener.addheaders.extend(
+ self._ad_manager_client.custom_http_headers.items())
+
+ 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
+
+ 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
+
+ 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.
+
+ Raises:
+ An AdManagerReportError if the report job fails to complete.
+ """
+ service = self._GetReportService()
+ report_job_id = service.runReportJob(report_job)['id']
+
+ status = service.getReportJobStatus(report_job_id)
+
+ while status != 'COMPLETED' and status != 'FAILED':
+ _data_downloader_logger.debug('Report job status: %s', status)
+ time.sleep(30)
+ status = service.getReportJobStatus(report_job_id)
+
+ if status == 'FAILED':
+ raise googleads.errors.AdManagerReportError(report_job_id)
+ else:
+ _data_downloader_logger.debug('Report has completed successfully')
+ return report_job_id
+
+ 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 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 write to.
+ include_report_properties: Whether or not to include the report
+ properties (e.g. network, user, date generated...)
+ in the generated report.
+ include_totals_row: Whether or not to include the totals row.
+ use_gzip_compression: Whether or not to use gzip compression.
+ """
+ service = self._GetReportService()
+
+ if include_totals_row is None: # True unless CSV export if not specified
+ include_totals_row = True if export_format != 'CSV_DUMP' else False
+ opts = {
+ 'exportFormat': export_format,
+ 'includeReportProperties': include_report_properties,
+ 'includeTotalsRow': include_totals_row,
+ 'useGzipCompression': use_gzip_compression
+ }
+ report_url = service.getReportDownloadUrlWithOptions(report_job_id, opts)
+ _data_downloader_logger.info('Request Summary: Report job ID: %s, %s',
+ report_job_id, opts)
+
+ response = self.url_opener.open(report_url)
+
+ _data_downloader_logger.debug(
+ 'Incoming response: %s %s REDACTED REPORT DATA', response.code,
+ response.msg)
+
+ while True:
+ chunk = response.read(_CHUNK_SIZE)
+ if not chunk: break
+ outfile.write(chunk)
+
+ 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 SOAP values to bind
+ to the pql_query.
+
+ Returns:
+ a list of lists with the first being the header row and each subsequent
+ list being a row of results.
+ """
+ results = []
+ self._PageThroughPqlSet(pql_query, results.append, values)
+ return results
+
+ 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.
+ [optional]
+ values: A dict of python objects or a list of raw SOAP values to bind
+ to the pql_query.
+ """
+ pql_writer = csv.writer(file_handle, delimiter=',',
+ quotechar='"', quoting=csv.QUOTE_ALL)
+ self._PageThroughPqlSet(pql_query, pql_writer.writerow, values)
+
+ 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.
+ """
+ if 'value' in pql_value:
+ field = pql_value['value']
+ elif 'values' in pql_value:
+ field = pql_value['values']
+ else:
+ field = None
+
+ if field:
+ if isinstance(field, list):
+ if all(AdManagerClassType(single_field) == AdManagerClassType(field[0])
+ for single_field in field):
+ return ','.join([
+ '"%s"' % str(self._ConvertValueForCsv(single_field))
+ for single_field in field])
+ else:
+ raise googleads.errors.GoogleAdsValueError(
+ 'The set value returned contains unsupported mix value types')
+
+ class_type = AdManagerClassType(pql_value)
+
+ if class_type == 'TextValue':
+ s = field.replace('"', '""')
+
+ # Encode UTF-8 characters for Python 2 only.
+ if sys.version_info.major < 3:
+ s = s.encode('UTF8')
+ return s
+ elif class_type == 'NumberValue':
+ return float(field) if '.' in field else int(field)
+ elif class_type == 'DateTimeValue':
+ return self._ConvertDateTimeToOffset(field)
+ elif class_type == 'DateValue':
+ return datetime.date(int(field['year']),
+ int(field['month']),
+ int(field['day'])).isoformat()
+ else:
+ return field
+ else:
+ return '-'
+
+ 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 output the results (csv or in
+ memory)
+ values: A dict of python objects or a list of raw SOAP values to bind
+ to the pql_query.
+ """
+ if isinstance(values, dict):
+ values = PQLHelper.GetQueryValuesFromDict(values, self._version)
+
+ pql_service = self._GetPqlService()
+ current_offset = 0
+
+ while True:
+ query_w_limit_offset = '%s LIMIT %d OFFSET %d' % (pql_query,
+ SUGGESTED_PAGE_LIMIT,
+ current_offset)
+ response = pql_service.select({'query': query_w_limit_offset,
+ 'values': values})
+
+ if 'rows' in response:
+ # Write the header row only on first pull
+ if current_offset == 0:
+ header = response['columnTypes']
+ output_function([label['labelName'] for label in header])
+
+ entities = response['rows']
+ result_set_size = len(entities)
+
+ for entity in entities:
+ output_function([self._ConvertValueForCsv(value) for value
+ in entity['values']])
+
+ current_offset += result_set_size
+ if result_set_size != SUGGESTED_PAGE_LIMIT:
+ break
+ else:
+ break
+
+ 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 of the date time value uniform to
+ ReportService.
+ """
+ date_time_obj = datetime.datetime(int(date_time_value['date']['year']),
+ int(date_time_value['date']['month']),
+ int(date_time_value['date']['day']),
+ int(date_time_value['hour']),
+ int(date_time_value['minute']),
+ int(date_time_value['second']))
+ date_time_str = pytz.timezone(
+ date_time_value['timeZoneId']).localize(date_time_obj).isoformat()
+
+ if date_time_str[-5:] == '00:00':
+ return date_time_str[:-6] + 'Z'
+ else:
+ return date_time_str
+
+
+def AdManagerClassType(value):
+ """Returns the class type for an object.
+
+ Args:
+ value: generic object to return type for.
+
+ Returns:
+ str: A string representation of the value response type.
+ """
+ return value.__class__.__name__
diff --git a/googleads/adwords.py b/googleads/adwords.py
index 859f7719..415bdec4 100644
--- a/googleads/adwords.py
+++ b/googleads/adwords.py
@@ -14,112 +14,36 @@
"""Client library for the AdWords API."""
-__author__ = 'Joseph DiLallo'
-
-import io
+import abc
+import codecs
+from collections import namedtuple
+import datetime
+import logging
import os
-import StringIO
+import re
import sys
-import urllib
-import urllib2
+import io
+from urllib.request import Request, build_opener
+from urllib.parse import urlencode
+from urllib.error import HTTPError
from xml.etree import ElementTree
-import suds.client
-import suds.mx.literal
-import suds.xsd.doctor
-
import googleads.common
import googleads.errors
+import xmltodict
+import yaml
+
+
+_report_logger = logging.getLogger('%s.%s' % (__name__, 'report_downloader'))
+_batch_job_logger = logging.getLogger('%s.%s'
+ % (__name__, 'batch_job_helper'))
# The chunk size used for report downloads.
-CHUNK_SIZE = 16 * 1024
+_CHUNK_SIZE = 16 * 1024
# A giant dictionary of AdWords versions, the services they support, and which
# namespace those services are in.
_SERVICE_MAP = {
- 'v201406': {
- 'AdGroupAdService': 'cm',
- 'AdGroupBidModifierService': 'cm',
- 'AdGroupCriterionService': 'cm',
- 'AdGroupFeedService': 'cm',
- 'AdGroupService': 'cm',
- 'AdParamService': 'cm',
- 'AdwordsUserListService': 'rm',
- 'AlertService': 'mcm',
- 'BiddingStrategyService': 'cm',
- 'BudgetOrderService': 'billing',
- 'BudgetService': 'cm',
- 'CampaignAdExtensionService': 'cm',
- 'CampaignCriterionService': 'cm',
- 'CampaignFeedService': 'cm',
- 'CampaignService': 'cm',
- 'CampaignSharedSetService': 'cm',
- 'ConstantDataService': 'cm',
- 'ConversionTrackerService': 'cm',
- 'CustomerFeedService': 'cm',
- 'CustomerService': 'mcm',
- 'CustomerSyncService': 'ch',
- 'DataService': 'cm',
- 'ExperimentService': 'cm',
- 'FeedItemService': 'cm',
- 'FeedMappingService': 'cm',
- 'FeedService': 'cm',
- 'GeoLocationService': 'cm',
- 'LabelService': 'cm',
- 'LocationCriterionService': 'cm',
- 'ManagedCustomerService': 'mcm',
- 'MediaService': 'cm',
- 'MutateJobService': 'cm',
- 'OfflineConversionFeedService': 'cm',
- 'ReportDefinitionService': 'cm',
- 'SharedCriterionService': 'cm',
- 'SharedSetService': 'cm',
- 'TargetingIdeaService': 'o',
- 'TrafficEstimatorService': 'o',
- },
- 'v201409': {
- 'AdCustomizerFeedService': 'cm',
- 'AdGroupAdService': 'cm',
- 'AdGroupBidModifierService': 'cm',
- 'AdGroupCriterionService': 'cm',
- 'AdGroupExtensionSettingService': 'cm',
- 'AdGroupFeedService': 'cm',
- 'AdGroupService': 'cm',
- 'AdParamService': 'cm',
- 'AdwordsUserListService': 'rm',
- 'BiddingStrategyService': 'cm',
- 'BudgetOrderService': 'billing',
- 'BudgetService': 'cm',
- 'CampaignAdExtensionService': 'cm',
- 'CampaignCriterionService': 'cm',
- 'CampaignExtensionSettingService': 'cm',
- 'CampaignFeedService': 'cm',
- 'CampaignService': 'cm',
- 'CampaignSharedSetService': 'cm',
- 'ConstantDataService': 'cm',
- 'ConversionTrackerService': 'cm',
- 'CustomerExtensionSettingService': 'cm',
- 'CustomerFeedService': 'cm',
- 'CustomerService': 'mcm',
- 'CustomerSyncService': 'ch',
- 'DataService': 'cm',
- 'ExperimentService': 'cm',
- 'FeedItemService': 'cm',
- 'FeedMappingService': 'cm',
- 'FeedService': 'cm',
- 'GeoLocationService': 'cm',
- 'LabelService': 'cm',
- 'LocationCriterionService': 'cm',
- 'ManagedCustomerService': 'mcm',
- 'MediaService': 'cm',
- 'MutateJobService': 'cm',
- 'OfflineConversionFeedService': 'cm',
- 'ReportDefinitionService': 'cm',
- 'SharedCriterionService': 'cm',
- 'SharedSetService': 'cm',
- 'TargetingIdeaService': 'o',
- 'TrafficEstimatorService': 'o',
- },
- 'v201502': {
+ 'v201809': {
'AccountLabelService': 'mcm',
'AdCustomizerFeedService': 'cm',
'AdGroupAdService': 'cm',
@@ -129,46 +53,69 @@
'AdGroupFeedService': 'cm',
'AdGroupService': 'cm',
'AdParamService': 'cm',
+ 'AdService': 'cm',
'AdwordsUserListService': 'rm',
+ 'AssetService': 'cm',
+ 'BatchJobService': 'cm',
'BiddingStrategyService': 'cm',
'BudgetOrderService': 'billing',
'BudgetService': 'cm',
+ 'CampaignBidModifierService': 'cm',
'CampaignCriterionService': 'cm',
'CampaignExtensionSettingService': 'cm',
'CampaignFeedService': 'cm',
+ 'CampaignGroupPerformanceTargetService': 'cm',
+ 'CampaignGroupService': 'cm',
'CampaignService': 'cm',
'CampaignSharedSetService': 'cm',
'ConstantDataService': 'cm',
'ConversionTrackerService': 'cm',
+ 'CustomAffinityService': 'rm',
'CustomerExtensionSettingService': 'cm',
'CustomerFeedService': 'cm',
+ 'CustomerNegativeCriterionService': 'cm',
'CustomerService': 'mcm',
'CustomerSyncService': 'ch',
'DataService': 'cm',
- 'ExperimentService': 'cm',
+ 'DraftAsyncErrorService': 'cm',
+ 'DraftService': 'cm',
'FeedItemService': 'cm',
+ 'FeedItemTargetService': 'cm',
'FeedMappingService': 'cm',
'FeedService': 'cm',
- 'GeoLocationService': 'cm',
'LabelService': 'cm',
'LocationCriterionService': 'cm',
'ManagedCustomerService': 'mcm',
'MediaService': 'cm',
- 'MutateJobService': 'cm',
+ 'OfflineCallConversionFeedService': 'cm',
+ 'OfflineConversionAdjustmentFeedService': 'cm',
'OfflineConversionFeedService': 'cm',
+ 'OfflineDataUploadService': 'rm',
'ReportDefinitionService': 'cm',
'SharedCriterionService': 'cm',
'SharedSetService': 'cm',
'TargetingIdeaService': 'o',
'TrafficEstimatorService': 'o',
+ 'TrialAsyncErrorService': 'cm',
+ 'TrialService': 'cm'
}
}
+# Supported kwargs for params sent in the report header.
+_REPORT_HEADER_KWARGS = {'client_customer_id': 'clientCustomerId',
+ 'include_zero_impressions': 'includeZeroImpressions',
+ 'skip_report_header': 'skipReportHeader',
+ 'skip_column_header': 'skipColumnHeader',
+ 'skip_report_summary': 'skipReportSummary',
+ 'use_raw_enum_values': 'useRawEnumValues'}
+
# The endpoint used by default when making AdWords API requests.
_DEFAULT_ENDPOINT = 'https://adwords.google.com'
+# The user-agent used by default when making AdWords API requests.
+_DEFAULT_USER_AGENT = 'unknown'
-class AdWordsClient(object):
+class AdWordsClient(googleads.common.CommonClient):
"""A central location to set headers and create web service clients.
Attributes:
@@ -186,22 +133,42 @@ class AdWordsClient(object):
succeed, to result in a complete failure with no changes made or a
partial failure with some changes made. Only certain services respect
this header.
- https_proxy: A string identifying the URL of a proxy that all HTTPS requests
- should be routed through. Modifying this value will not affect any SOAP
- service clients you've already created.
"""
# The key in the storage yaml which contains AdWords data.
_YAML_KEY = 'adwords'
- # A list of values which must be provided to use AdWords.
- _REQUIRED_INIT_VALUES = ('user_agent', 'developer_token')
- # A list of values which may optionally be provided when using AdWords.
- _OPTIONAL_INIT_VALUES = ('validate_only', 'partial_failure',
- 'client_customer_id')
+ # A tuple containing values which must be provided to use AdWords.
+ _REQUIRED_INIT_VALUES = ('developer_token',)
+ # A tuple containing values which may optionally be provided when using
+ # AdWords.
+ _OPTIONAL_INIT_VALUES = (
+ 'validate_only', 'partial_failure', 'client_customer_id', 'user_agent',
+ 'report_downloader_headers',
+ googleads.common.ENABLE_COMPRESSION_KEY)
+
# The format of SOAP service WSDLs. A server, namespace, version, and service
# name need to be formatted in.
_SOAP_SERVICE_FORMAT = '%s/api/adwords/%s/%s/%s?wsdl'
+ @classmethod
+ def LoadFromString(cls, yaml_doc):
+ """Creates an AdWordsClient with information stored in a yaml string.
+
+ Args:
+ yaml_doc: The yaml string containing the cached AdWords data.
+
+ Returns:
+ An AdWordsClient initialized with the values cached in the string.
+
+ Raises:
+ A GoogleAdsValueError if the given yaml string does not contain the
+ information necessary to instantiate a client object - either a
+ required key was missing or an OAuth2 key was missing.
+ """
+ return cls(**googleads.common.LoadFromString(
+ yaml_doc, cls._YAML_KEY, cls._REQUIRED_INIT_VALUES,
+ cls._OPTIONAL_INIT_VALUES))
+
@classmethod
def LoadFromStorage(cls, path=None):
"""Creates an AdWordsClient with information stored in a yaml file.
@@ -216,7 +183,7 @@ def LoadFromStorage(cls, path=None):
Raises:
A GoogleAdsValueError if the given yaml file does not contain the
information necessary to instantiate a client object - either a
- required key was missing or an OAuth 2.0 key was missing.
+ required key was missing or an OAuth2 key was missing.
"""
if path is None:
path = os.path.join(os.path.expanduser('~'), 'googleads.yaml')
@@ -225,10 +192,8 @@ def LoadFromStorage(cls, path=None):
path, cls._YAML_KEY, cls._REQUIRED_INIT_VALUES,
cls._OPTIONAL_INIT_VALUES))
- def __init__(
- self, developer_token, oauth2_client, user_agent,
- client_customer_id=None, validate_only=False, partial_failure=False,
- https_proxy=None, cache=None):
+ def __init__(self, developer_token, oauth2_client,
+ user_agent=_DEFAULT_USER_AGENT, timeout=3600, **kwargs):
"""Initializes an AdWordsClient.
For more information on these arguments, see our SOAP headers guide:
@@ -238,13 +203,17 @@ def __init__(
developer_token: A string containing your AdWords API developer token.
oauth2_client: A googleads.oauth2.GoogleOAuth2Client used to authorize
your requests.
- user_agent: An arbitrary string which will be used to identify your
- application
- [optional]
+ user_agent: An arbitrary string containing only ASCII characters that will
+ be used to identify your application. If not set, this will default to
+ the string value "unknown".
+ timeout: An integer time in MS to time out connections to AdWords.
+ **kwargs: Optional keyword arguments.
+
+ Keyword Arguments:
client_customer_id: A string identifying which AdWords customer you want
to act as. You do not have to provide this if you are using a client
- account. You probably want to provide this if you're using an MCC
- account.
+ account. You probably want to provide this if you're using an AdWords
+ manager account.
validate_only: A boolean indicating if you want your request to be
validated but not actually executed.
partial_failure: A boolean indicating if you want your mutate calls
@@ -252,21 +221,51 @@ def __init__(
succeed, to result in a complete failure with no changes made or a
partial failure with some changes made. Only certain services respect
this header.
- https_proxy: A string identifying the proxy that all HTTPS requests
- should be routed through.
- cache: A subclass of suds.cache.Cache; defaults to None.
+ cache: A subclass of zeep.cache.Base. If not set, this will default to a
+ basic file cache. To disable caching for Zeep, pass
+ googleads.common.ZeepServiceProxy.NO_CACHE.
+ proxy_config: A googleads.common.ProxyConfig instance or None if a proxy
+ isn't being used.
+ report_downloader_headers: A dict containing optional headers to be used
+ by default when making requests with the ReportDownloader.
+ enable_compression: A boolean indicating if you want to enable compression
+ of the SOAP response. If True, the SOAP response will use gzip
+ compression, and will be decompressed for you automatically.
+
+ Raises:
+ GoogleAdsValueError: If the provided user_agent contains non-ASCII
+ characters.
"""
+ super(AdWordsClient, self).__init__()
+
self.developer_token = developer_token
self.oauth2_client = oauth2_client
+ self.client_customer_id = kwargs.get('client_customer_id')
self.user_agent = user_agent
- self.client_customer_id = client_customer_id
- self.validate_only = validate_only
- self.partial_failure = partial_failure
- self.https_proxy = https_proxy
- self.cache = cache
-
- def GetService(self, service_name, version=sorted(_SERVICE_MAP.keys())[-1],
- server=_DEFAULT_ENDPOINT):
+ self.custom_http_headers = kwargs.get('custom_http_headers')
+ # Verify that the provided user_agent contains only ASCII characters. A
+ # UnicodeEncodeError will be raised if it contains a non-ASCII character.
+ try:
+ self.user_agent.encode('ascii')
+ except UnicodeEncodeError:
+ raise googleads.errors.GoogleAdsValueError(
+ 'Invalid user_agent value, must contain only ASCII characters.')
+ self.validate_only = kwargs.get('validate_only', False)
+ self.partial_failure = kwargs.get('partial_failure', False)
+ self.cache = kwargs.get('cache')
+ proxy_config = kwargs.get('proxy_config')
+ self.proxy_config = (proxy_config if proxy_config else
+ googleads.common.ProxyConfig())
+ self.report_download_headers = kwargs.get('report_download_headers', {})
+ self.enable_compression = kwargs.get(
+ googleads.common.ENABLE_COMPRESSION_KEY, False)
+
+ if self.enable_compression:
+ self.user_agent = '%s (gzip)' % self.user_agent
+
+ self.timeout = timeout
+
+ def GetService(self, service_name, version=None, server=None):
"""Creates a service client for the given service.
Args:
@@ -279,44 +278,76 @@ def GetService(self, service_name, version=sorted(_SERVICE_MAP.keys())[-1],
server: A string identifying the webserver hosting the AdWords API.
Returns:
- A suds.client.ServiceSelector which has the headers and proxy configured
- for use.
+ A googleads.common.GoogleSoapService instance which has the headers
+ and proxy configured for use.
Raises:
A GoogleAdsValueError if the service or version provided do not exist.
"""
- if server[-1] == '/': server = server[:-1]
+ if not server:
+ server = _DEFAULT_ENDPOINT
+ server = server.rstrip('/')
+
+ if not version:
+ version = sorted(_SERVICE_MAP.keys())[-1]
+
try:
- proxy_option = None
- if self.https_proxy:
- proxy_option = {
- 'https': self.https_proxy
- }
-
- client = suds.client.Client(
- self._SOAP_SERVICE_FORMAT %
- (server, _SERVICE_MAP[version][service_name], version, service_name),
- proxy=proxy_option, cache=self.cache, timeout=3600)
+ version_service_mapping = _SERVICE_MAP[version][service_name]
except KeyError:
+ msg_fmt = 'Unrecognized %s for the AdWords API. Given: %s Supported: %s'
+
if version in _SERVICE_MAP:
raise googleads.errors.GoogleAdsValueError(
- 'Unrecognized service for the AdWords API. Service given: %s '
- 'Supported services: %s'
- % (service_name, _SERVICE_MAP[version].keys()))
+ msg_fmt % ('service', service_name, _SERVICE_MAP[version].keys()))
else:
raise googleads.errors.GoogleAdsValueError(
- 'Unrecognized version of the AdWords API. Version given: %s '
- 'Supported versions: %s' % (version, _SERVICE_MAP.keys()))
+ msg_fmt % ('version', version, _SERVICE_MAP.keys()))
+
+ service = googleads.common.GetServiceClassForLibrary()(
+ self._SOAP_SERVICE_FORMAT % (
+ server, version_service_mapping, version, service_name),
+ _AdWordsHeaderHandler(
+ self, version, self.enable_compression, self.custom_http_headers),
+ _AdWordsPacker,
+ self.proxy_config,
+ self.timeout,
+ version,
+ cache=self.cache)
+
+ return service
+
+ def GetBatchJobHelper(self, version=sorted(_SERVICE_MAP.keys())[-1],
+ server=None):
+ """Returns a BatchJobHelper to work with the BatchJobService.
+
+ This is a convenience method. It is functionally identical to calling
+ BatchJobHelper(adwords_client, version).
+
+ Args:
+ [optional]
+ version: A string identifying the AdWords version to connect to. This
+ defaults to what is currently the latest version. This will be updated
+ in future releases to point to what is then the latest version.
+ server: A string identifying the webserver hosting the AdWords API.
+
+ Returns:
+ An initialized BatchJobHelper tied to this client.
+ """
+ if not server:
+ server = _DEFAULT_ENDPOINT
- return googleads.common.SudsServiceProxy(
- client, _AdWordsHeaderHandler(self, version))
+ request_builder = BatchJobHelper.GetRequestBuilder(
+ self, version=version, server=server)
+ response_parser = BatchJobHelper.GetResponseParser()
+
+ return BatchJobHelper(request_builder, response_parser)
def GetReportDownloader(self, version=sorted(_SERVICE_MAP.keys())[-1],
- server=_DEFAULT_ENDPOINT):
+ server=None):
"""Creates a downloader for AdWords reports.
This is a convenience method. It is functionally identical to calling
- ReportDownloader(adwords_client, version, server)
+ ReportDownloader(adwords_client, version, server).
Args:
[optional]
@@ -328,13 +359,16 @@ def GetReportDownloader(self, version=sorted(_SERVICE_MAP.keys())[-1],
Returns:
A ReportDownloader tied to this AdWordsClient, ready to download reports.
"""
+ if not server:
+ server = _DEFAULT_ENDPOINT
+
return ReportDownloader(self, version, server)
def SetClientCustomerId(self, client_customer_id):
"""Change the client customer id used by the AdWordsClient instance.
Args:
- client_customer_id: str New Client Customer Id to use.
+ client_customer_id: str New Client Customer ID to use.
"""
self.client_customer_id = client_customer_id
@@ -343,15 +377,16 @@ class _AdWordsHeaderHandler(googleads.common.HeaderHandler):
"""Handler which generates the headers for AdWords requests."""
# The library signature for AdWords, to be appended to all user agents.
- _LIB_SIG = googleads.common.GenerateLibSig('AwApi-Python')
+ _PRODUCT_SIG = 'AwApi-Python'
# The name of the WSDL-defined SOAP Header class used in all SOAP requests.
# The namespace needs the version of AdWords being used to be templated in.
- _SOAP_HEADER_CLASS = ('{https://adwords.google.com/api/adwords/cm/%s}'
- 'SoapHeader')
+ _SOAP_HEADER_CLASS = (
+ '{https://adwords.google.com/api/adwords/cm/%s}SoapHeader')
# The content type of report download requests
_CONTENT_TYPE = 'application/x-www-form-urlencoded'
- def __init__(self, adwords_client, version):
+ def __init__(self, adwords_client, version,
+ enable_compression, custom_http_headers=None):
"""Initializes an AdWordsHeaderHandler.
Args:
@@ -360,56 +395,762 @@ def __init__(self, adwords_client, version):
handler picks up changes to the client.
version: A string identifying which version of AdWords this header handler
will be used for.
+ enable_compression: A boolean indicating if you want to enable compression
+ of the SOAP response. If True, the SOAP response will use gzip
+ compression, and will be decompressed for you automatically.
+ custom_http_headers: A dictionary of custom HTTP headers to send with all
+ requests.
"""
self._adwords_client = adwords_client
self._version = version
+ self.enable_compression = enable_compression
+ self.custom_http_headers = custom_http_headers or {}
+
+ 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.
- def SetHeaders(self, suds_client):
- """Sets the SOAP and HTTP headers on the given suds client."""
- header = suds_client.factory.create(self._SOAP_HEADER_CLASS % self._version)
+ Returns:
+ A SOAP object containing the headers.
+ """
+ header = create_method(self._SOAP_HEADER_CLASS % self._version)
header.clientCustomerId = self._adwords_client.client_customer_id
header.developerToken = self._adwords_client.developer_token
- header.userAgent = ''.join([self._adwords_client.user_agent, self._LIB_SIG])
+ header.userAgent = ''.join([
+ self._adwords_client.user_agent,
+ googleads.common.GenerateLibSig(self._PRODUCT_SIG)])
header.validateOnly = self._adwords_client.validate_only
header.partialFailure = self._adwords_client.partial_failure
+ return header
+
+ def GetHTTPHeaders(self):
+ """Returns the HTTP headers required for request authorization.
+
+ Returns:
+ A dictionary containing the required headers.
+ """
+ http_headers = self._adwords_client.oauth2_client.CreateHttpHeader()
+ if self.enable_compression:
+ http_headers['accept-encoding'] = 'gzip'
- suds_client.set_options(
- soapheaders=header,
- headers=self._adwords_client.oauth2_client.CreateHttpHeader())
+ http_headers.update(self.custom_http_headers)
- def GetReportDownloadHeaders(self, skip_report_header=None,
- skip_report_summary=None):
+ return http_headers
+
+ def GetReportDownloadHeaders(self, **kwargs):
"""Returns a dictionary of headers for a report download request.
+ Note that the given keyword arguments will override any settings configured
+ from the googleads.yaml file.
+
Args:
+ **kwargs: Optional keyword arguments.
+
+ Keyword Arguments:
+ client_customer_id: A string containing a client_customer_id intended to
+ override the default value set by the AdWordsClient.
+ include_zero_impressions: A boolean indicating whether the report should
+ show rows with zero impressions.
skip_report_header: A boolean indicating whether to include a header row
containing the report name and date range. If false or not specified,
report output will include the header row.
+ skip_column_header: A boolean indicating whether to include column names
+ in reports. If false or not specified, report output will include the
+ column names.
skip_report_summary: A boolean indicating whether to include a summary row
containing the report totals. If false or not specified, report output
will include the summary row.
+ use_raw_enum_values: A boolean indicating whether to return enum field
+ values as enums instead of display values.
Returns:
A dictionary containing the headers configured for downloading a report.
+
+ Raises:
+ GoogleAdsValueError: If one or more of the report header keyword arguments
+ is invalid.
"""
headers = self._adwords_client.oauth2_client.CreateHttpHeader()
headers.update({
'Content-type': self._CONTENT_TYPE,
'developerToken': str(self._adwords_client.developer_token),
- 'clientCustomerId': str(self._adwords_client.client_customer_id),
- 'User-Agent': ''.join([self._adwords_client.user_agent, self._LIB_SIG,
- ',gzip'])
+ 'clientCustomerId': str(kwargs.get(
+ 'client_customer_id', self._adwords_client.client_customer_id)),
+ 'User-Agent': ''.join([
+ self._adwords_client.user_agent,
+ googleads.common.GenerateLibSig(self._PRODUCT_SIG),
+ ',gzip'])
})
+ headers.update(self.custom_http_headers)
- if skip_report_header:
- headers.update({'skipReportHeader': str(skip_report_header)})
+ updated_kwargs = dict(self._adwords_client.report_download_headers)
+ updated_kwargs.update(kwargs)
- if skip_report_summary:
- headers.update({'skipReportSummary': str(skip_report_summary)})
+ for kw in updated_kwargs:
+ try:
+ headers[_REPORT_HEADER_KWARGS[kw]] = str(updated_kwargs[kw])
+ except KeyError:
+ raise googleads.errors.GoogleAdsValueError(
+ 'The provided keyword "%s" is invalid. Accepted keywords are: %s'
+ % (kw, _REPORT_HEADER_KWARGS.keys()))
return headers
+class _AdWordsPacker(googleads.common.SoapPacker):
+ """A utility applying customized packing logic for AdWords."""
+
+ @classmethod
+ def Pack(cls, obj, version):
+ """Pack the given object using AdWords-specific logic.
+
+ Args:
+ obj: an object to be packed for SOAP using AdWords-specific logic, if
+ applicable.
+ version: the version of the current API, e.g. 'v201809'
+
+ Returns:
+ The given object packed with AdWords-specific logic for SOAP, if
+ applicable. Otherwise, returns the given object unmodified.
+ """
+ if isinstance(obj, ServiceQuery):
+ return str(obj)
+ return obj
+
+
+@googleads.common.RegisterUtility('BatchJobHelper')
+class BatchJobHelper(object):
+ """A utility that simplifies working with the BatchJobService."""
+
+ class AbstractResponseParser(object):
+ """Interface for parsing responses from the BatchJobService."""
+
+ __metaclass__ = abc.ABCMeta
+
+ @abc.abstractmethod
+ def ParseResponse(self, batch_job_response):
+ """Parses a Batch Job Service response..
+
+ Args:
+ batch_job_response: a str containing the response from the
+ BatchJobService.
+ """
+
+ class _XMLToDictResponseParser(AbstractResponseParser):
+ """Parses responses from the BatchJobService, returning as a dictionary."""
+
+ def ParseResponse(self, batch_job_response):
+ """Parses a Batch Job Service response.
+
+ Args:
+ batch_job_response: a str containing the response from the
+ BatchJobService.
+
+ Returns:
+ An OrderedDict containing the Batch Job Service response.
+ """
+ return xmltodict.parse(batch_job_response)
+
+ class AbstractUploadRequestBuilder(object):
+ """Interface for building requests used to upload batch job operations."""
+
+ __metaclass__ = abc.ABCMeta
+
+ @abc.abstractmethod
+ def BuildUploadRequest(self, upload_url, operations, **kwargs):
+ """Builds the BatchJob upload request.
+
+ Args:
+ upload_url: a string url that the given operations will be uploaded to.
+ operations: a list where each element is a list containing operations
+ for a single AdWords Service.
+ **kwargs: optional keyword arguments.
+
+ Returns:
+ A urllib.request.Request instance with the correct method, headers, and
+ padding (if required) for the batch job upload.
+ """
+
+ @abc.abstractmethod
+ def GetVersion(self):
+ """Retrieves the version of AdWords used to build requests.
+
+ Returns:
+ A str indicating the version of AdWords for which requests are being
+ built.
+ """
+
+ @abc.abstractmethod
+ def GetServer(self):
+ """Retrieves the endpoint used to access the AdWords API.
+
+ Returns:
+ A str indicating the version of AdWords endpoint being used.
+ """
+
+ class _UploadRequestBuilder(AbstractUploadRequestBuilder):
+ """Builds requests used to upload operations for Batch Jobs."""
+ # Used to remove namespace from xsi:type Element attributes.
+ _ATTRIB_NAMESPACE_SUB = re.compile('ns[0-1]:')
+ # Components of the upload request.
+ _UPLOAD_PREFIX_TEMPLATE = """
+"""
+ _UPLOAD_SUFFIX = ''
+ # Incremental uploads must have a content-length that is a multiple of this.
+ _BATCH_JOB_INCREMENT = 262144
+ _OPERATION = namedtuple('Operation',
+ ['operation_type', 'service', 'method'])
+ _OPERATION_MAP = {
+ 'AdGroupAdOperation': _OPERATION('AdGroupAdOperation',
+ 'AdGroupAdService', 'mutate'),
+ 'AdGroupAdLabelOperation': _OPERATION(
+ 'AdGroupAdLabelOperation', 'AdGroupAdService', 'mutateLabel'),
+ 'AdGroupBidModifierOperation': _OPERATION(
+ 'AdGroupBidModifierOperation', 'AdGroupBidModifierService',
+ 'mutate'),
+ 'AdGroupCriterionOperation': _OPERATION(
+ 'AdGroupCriterionOperation', 'AdGroupCriterionService', 'mutate'),
+ 'AdGroupCriterionLabelOperation': _OPERATION(
+ 'AdGroupCriterionLabelOperation', 'AdGroupCriterionService',
+ 'mutateLabel'),
+ 'AdGroupExtensionSettingOperation': _OPERATION(
+ 'AdGroupExtensionSettingOperation',
+ 'AdGroupExtensionSettingService', 'mutate'),
+ 'AdGroupOperation': _OPERATION('AdGroupOperation', 'AdGroupService',
+ 'mutate'),
+ 'AdGroupLabelOperation': _OPERATION('AdGroupLabelOperation',
+ 'AdGroupService', 'mutateLabel'),
+ 'BudgetOperation': _OPERATION('BudgetOperation', 'BudgetService',
+ 'mutate'),
+ 'CampaignCriterionOperation': _OPERATION(
+ 'CampaignCriterionOperation', 'CampaignCriterionService', 'mutate'),
+ 'CampaignExtensionSettingOperation': _OPERATION(
+ 'CampaignExtensionSettingOperation',
+ 'CampaignExtensionSettingService', 'mutate'),
+ 'CampaignOperation': _OPERATION('CampaignOperation',
+ 'CampaignService', 'mutate'),
+ 'CampaignLabelOperation': _OPERATION('CampaignLabelOperation',
+ 'CampaignService', 'mutateLabel'),
+ 'CampaignSharedSetOperation': _OPERATION(
+ 'CampaignSharedSetOperation', 'CampaignSharedSetService',
+ 'mutate'),
+ 'CustomerExtensionSettingOperation': _OPERATION(
+ 'CustomerExtensionSettingOperation',
+ 'CustomerExtensionSettingService', 'mutate'),
+ 'FeedItemOperation': _OPERATION('FeedItemOperation', 'FeedItemService',
+ 'mutate'),
+ 'FeedItemTargetOperation': _OPERATION(
+ 'FeedItemTargetOperation', 'FeedItemTargetService', 'mutate'),
+ 'SharedCriterionOperation': _OPERATION(
+ 'SharedCriterionOperation', 'SharedCriterionService', 'mutate'),
+ 'SharedSetOperation': _OPERATION('SharedSetOperation',
+ 'SharedSetService', 'mutate')
+ }
+ XSI_TYPE_STRING = '{http://www.w3.org/2001/XMLSchema-instance}type'
+
+ def __init__(self, client, **kwargs):
+ """Initializes an _UploadRequestBuilder.
+
+ Arguments:
+ client: an AdWordsClient instance.
+ **kwargs: Keyword arguments.
+
+ Keyword Arguments:
+ version: a string identifying the AdWords version to connect to.
+ server: a string identifying the webserver hosting the AdWords API.
+ """
+ self.client = client
+ self._version = kwargs.get('version', sorted(_SERVICE_MAP.keys())[-1])
+ self.server = kwargs.get('server', _DEFAULT_ENDPOINT)
+ self._adwords_endpoint = ('%s/api/adwords/cm/%s' %
+ (self.server, self._version))
+ self._adwords_namespace = ('{%s}' % self._adwords_endpoint)
+ # Used to remove the AdWords namespace from Element tags.
+ self._tag_namespace_sub = re.compile(self._adwords_namespace)
+
+ def BuildUploadRequest(self, upload_url, operations, **kwargs):
+ """Builds the BatchJob upload request.
+
+ Args:
+ upload_url: a string url that the given operations will be uploaded to.
+ operations: a list where each element is a list containing operations
+ for a single AdWords Service.
+ **kwargs: optional keyword arguments.
+
+ Keyword Arguments:
+ current_content_length: an integer indicating the current total content
+ length of an incremental upload request. If this keyword argument is
+ provided, this request will be handled as an incremental upload.
+ is_last: a boolean indicating whether this is the final request in an
+ incremental upload.
+
+ Returns:
+ A urllib.request.Request instance with the correct method, headers, and
+ padding (if required) for the batch job upload.
+ """
+ current_content_length = kwargs.get('current_content_length', 0)
+ is_last = kwargs.get('is_last')
+ # Generate an unpadded request body
+ request_body = self._BuildUploadRequestBody(
+ operations,
+ has_prefix=current_content_length == 0,
+ has_suffix=is_last)
+ req = Request(upload_url)
+ req.add_header('Content-Type', 'application/xml')
+ # Determine length of this message and the required padding.
+ new_content_length = current_content_length
+ request_length = len(request_body.encode('utf-8'))
+ padding_length = self._GetPaddingLength(request_length)
+ padded_request_length = request_length + padding_length
+ new_content_length += padded_request_length
+ request_body += ' ' * padding_length
+ req.get_method = lambda: 'PUT' # Modify this into a PUT request.
+ req.data = request_body.encode('utf-8')
+ req.add_header('Content-Length', padded_request_length)
+ req.add_header('Content-Range', 'bytes %s-%s/%s' % (
+ current_content_length,
+ new_content_length - 1,
+ new_content_length if is_last else '*'
+ ))
+
+ return req
+
+ def GetVersion(self):
+ """Retrieves the version of AdWords used to build requests.
+
+ Returns:
+ A str indicating the version of AdWords for which requests are being
+ built.
+ """
+ return self._version
+
+ def GetServer(self):
+ """Retrieves the endpoint used to access the AdWords API.
+
+ Returns:
+ A str indicating the version of AdWords endpoint being used.
+ """
+ return self.server
+
+ def _BuildUploadRequestBody(self, operations, has_prefix=True,
+ has_suffix=True):
+ """Builds an unpadded body containing operations for a BatchJob upload.
+
+ Args:
+ operations: a list where each element is a list containing operations
+ for a single AdWords Service.
+ has_prefix: a boolean indicating whether the prefix should be included
+ in the request body.
+ has_suffix: a boolean indicating whether the suffic should be included
+ in the request body.
+
+ Returns:
+ A string containing the unpadded batch job upload request body.
+ """
+ operations_xml = ''.join([
+ self._GenerateOperationsXML(operations_list)
+ for operations_list in operations])
+ request_body = '%s%s%s' % ((self._UPLOAD_PREFIX_TEMPLATE %
+ self._adwords_endpoint) if has_prefix else '',
+ operations_xml,
+ self._UPLOAD_SUFFIX if has_suffix else '')
+ return request_body
+
+ def _ExtractOperations(self, full_soap_xml):
+ """Extracts operations from API Request XML for use with BatchJobService.
+
+ Args:
+ full_soap_xml: The full XML for the desired operation.
+
+ Returns:
+ A string containing only the operations portion of the full XML request,
+ formatted for use with the BatchJobService. If no operations are found,
+ returns an empty string.
+
+ Raises:
+ GoogleAdsValueErrorr: If no Operation.Type element is found in the
+ operations. This ordinarily happens if no xsi_type is specified for the
+ operations.
+ """
+ # Extract method element (e.g. mutate, mutateLabel, etc...) from XML, this
+ # contains the operations.
+ method = self._GetRawOperationsFromXML(full_soap_xml)
+ # Ensure operations are formatted correctly for BatchJobService.
+ for operations in method:
+ self._FormatForBatchJobService(operations)
+ # Extract the operation type, ensure xsi:type is set for BatchJobService.
+ operation_type = operations.find('Operation.Type')
+ if operation_type is None:
+ raise googleads.errors.GoogleAdsValueError('No xsi_type specified '
+ 'for the operations.')
+ operations.attrib[self.XSI_TYPE_STRING] = operation_type.text
+ operations_xml = ''.join([ElementTree.tostring(operation).decode('utf-8')
+ for operation in method])
+ return operations_xml
+
+ def _FormatForBatchJobService(self, element):
+ """Formats contents of all operations for use with the BatchJobService.
+
+ This will recursively remove unnecessary namespaces that would prevent the
+ operations from executing via the BatchJobService. It will also remove namespaces
+ appended to the xsi:type in some cases that also cause issues for the BatchJobService.
+
+ Args:
+ element: a starting Element to be modified to the correct format.
+ """
+ # Remove any unnecessary AdWords namespace from the tag.
+ element.tag = self._tag_namespace_sub.sub('', element.tag)
+ xsi_type = element.attrib.get(
+ '{http://www.w3.org/2001/XMLSchema-instance}type')
+ # If an xsi_type attribute exists, ensure that the namespace is removed
+ # from the type.
+ if xsi_type:
+ element.attrib['{http://www.w3.org/2001/XMLSchema-instance}type'] = (
+ self._ATTRIB_NAMESPACE_SUB.sub('', xsi_type))
+ for child in element:
+ self._FormatForBatchJobService(child)
+
+ def _GenerateOperationsXML(self, operations):
+ """Generates XML for the given list of operations.
+
+ Args:
+ operations: a list of operations for single AdWords Service.
+
+ Returns:
+ A str containing the XML for only the operations, formatted to work with
+ the BatchJobService.
+
+ Raises:
+ GoogleAdsValueError: if no xsi_type is specified for the operations.
+ """
+ # Verify that all operations included specify an xsi_type.
+ if operations:
+ if any('xsi_type' not in operation for operation in operations):
+ raise googleads.errors.AdWordsBatchJobServiceInvalidOperationError(
+ 'Operations have no xsi_type specified.')
+ return self._ExtractOperations(self._GenerateRawRequestXML(operations))
+ else:
+ return ''
+
+ def _GenerateRawRequestXML(self, operations):
+ """Generates the raw XML for the operations sent to the given service.
+
+ Args:
+ operations: a list containing operations that could be run by the given
+ service.
+
+ Returns:
+ An element containing the raw XML of the request to the given service
+ that would execute the given operations
+
+ Raises:
+ KeyError: If the given operation type is not supported.
+ """
+ operation = self._OPERATION_MAP[operations[0]['xsi_type']]
+ service = self.client.GetService(operation.service, self._version)
+ return service.GetRequestXML(operation.method, operations)
+
+ def _GetPaddingLength(self, length):
+ """Retrieve the padding to be used in an incremental upload.
+
+ Args:
+ length: an integer containing the length of the operations XML to be
+ uploaded as part of a batch job.
+ Returns:
+ An integer indicating the required padding to be applied in an
+ incremental batch job upload request.
+ """
+ padding = self._BATCH_JOB_INCREMENT - (length % self._BATCH_JOB_INCREMENT)
+ return 0 if padding == self._BATCH_JOB_INCREMENT else padding
+
+ def _GetRawOperationsFromXML(self, raw_request_xml):
+ """Retrieve the raw set of operations from the request XML.
+
+ Args:
+ raw_request_xml: The full XML for the desired operation.
+
+ Returns:
+ An unmodified Element containing the operations from the raw request
+ xml.
+
+ Raises:
+ AttributeError: if the provided XML isn't from AdWords.
+ """
+ return raw_request_xml.find(
+ '{http://schemas.xmlsoap.org/soap/envelope/}Body').find('.//')
+
+ def __init__(self, request_builder, response_parser):
+ """Initializes the BatchJobHelper.
+
+ For general use, consider using AdWordsClient's GetBatchJobHelper method to
+ receive an initialized BatchJobHelper using the default request builder and
+ response parser.
+
+ Args:
+ request_builder: an AbstractUploadRequestBuilder instance.
+ response_parser: an AbstractResponseParser instance.
+ """
+ self._temporary_id = 0 # Used for temporary IDs in BatchJobService.
+ self._request_builder = request_builder
+ self._response_parser = response_parser
+
+ def GetId(self):
+ """Produces a distinct sequential ID for the BatchJobService.
+
+ Returns:
+ A negative number that will be the temporary ID for an API resource.
+ """
+ self._temporary_id -= 1
+ return self._temporary_id
+
+ def GetIncrementalUploadHelper(self, upload_url, current_content_length=0):
+ return IncrementalUploadHelper(
+ self._request_builder, upload_url, current_content_length)
+
+ @classmethod
+ def GetRequestBuilder(cls, *args, **kwargs):
+ """Get a new AbstractUploadRequestBuilder instance."""
+ return cls._UploadRequestBuilder(*args, **kwargs)
+
+ @classmethod
+ def GetResponseParser(cls, *args, **kwargs):
+ """Get a new AbstractResponseParser instance."""
+ return cls._XMLToDictResponseParser(*args, **kwargs)
+
+ def ParseResponse(self, batch_job_response):
+ """Parses a Batch Job Service response and returns it as a zeep object.
+
+ Note: Unlike zeep objects generated via an API call with zeep, type
+ information will be lost. All values are strings.
+
+ Args:
+ batch_job_response: a str containing the response from the
+ BatchJobService.
+
+ Returns:
+ A zeep object response generated from the provided batch_job_response.
+ """
+ return self._response_parser.ParseResponse(batch_job_response)
+
+ def UploadOperations(self, upload_url, *operations):
+ """Uploads all operations to the given uploadUrl in a single request.
+
+ Note: Each list of operations is expected to contain operations of the same
+ type, similar to how one would normally send operations in an AdWords API
+ Service request.
+
+ Args:
+ upload_url: a string url that the given operations will be uploaded to.
+ *operations: one or more lists of operations as would be sent to the
+ AdWords API for the associated service.
+ """
+ uploader = IncrementalUploadHelper(self._request_builder, upload_url)
+ uploader.UploadOperations(operations, is_last=True)
+
+
+class IncrementalUploadHelper(object):
+ """A utility for uploading operations for a BatchJob incrementally."""
+
+ @classmethod
+ def Load(cls, file_input, client=None):
+ """Loads an IncrementalUploadHelper from the given file-like object.
+
+ Args:
+ file_input: a file-like object containing a serialized
+ IncrementalUploadHelper.
+ client: an AdWordsClient instance. If not specified, an AdWordsClient will
+ be instantiated using the default configuration file.
+
+ Returns:
+ An IncrementalUploadHelper instance initialized using the contents of the
+ serialized input file.
+
+ Raises:
+ GoogleAdsError: If there is an error reading the input file containing the
+ serialized IncrementalUploadHelper.
+ GoogleAdsValueError: If the contents of the input file can't be parsed to
+ produce an IncrementalUploadHelper.
+ """
+ if client is None:
+ client = AdWordsClient.LoadFromStorage()
+
+ try:
+ data = yaml.safe_load(file_input)
+ except yaml.YAMLError as e:
+ raise googleads.errors.GoogleAdsError(
+ 'Error loading IncrementalUploadHelper from file: %s' % str(e))
+
+ try:
+ request_builder = BatchJobHelper.GetRequestBuilder(
+ client, version=data['version'], server=data['server']
+ )
+
+ return cls(request_builder, data['upload_url'],
+ current_content_length=data['current_content_length'],
+ is_last=data['is_last'])
+ except KeyError as e:
+ raise googleads.errors.GoogleAdsValueError(
+ 'Can\'t parse IncrementalUploadHelper from file. Required field '
+ '"%s" is missing.' % e.message)
+
+ def __init__(self, request_builder, upload_url, current_content_length=0,
+ is_last=False):
+ """Initializes the IncrementalUpload.
+
+ Args:
+ request_builder: an AbstractUploadRequestBuilder instance.
+ upload_url: a string url provided by the BatchJobService.
+ current_content_length: an integer identifying the current content length
+ of data uploaded to the Batch Job.
+ is_last: a boolean indicating whether this is the final increment.
+ Raises:
+ GoogleAdsValueError: if the content length is lower than 0.
+ """
+ self._request_builder = request_builder
+ if current_content_length < 0:
+ raise googleads.errors.GoogleAdsValueError(
+ 'Current content length %s is < 0.' % current_content_length)
+ self._current_content_length = current_content_length
+ self._is_last = is_last
+ self._url_opener = build_opener(
+ *self._request_builder.client.proxy_config.GetHandlers())
+ if self._request_builder.client.custom_http_headers:
+ self._url_opener.addheaders.extend(
+ self._request_builder.client.custom_http_headers.items())
+
+ self._upload_url = self._InitializeURL(upload_url, current_content_length)
+
+ def _InitializeURL(self, upload_url, current_content_length):
+ """Ensures that the URL used to upload operations is properly initialized.
+
+ Args:
+ upload_url: a string url.
+ current_content_length: an integer identifying the current content length
+ of data uploaded to the Batch Job.
+
+ Returns:
+ An initialized string URL, or the provided string URL if the URL has
+ already been initialized.
+ """
+ # If initialization is not necessary, return the provided upload_url.
+ if current_content_length != 0:
+ return upload_url
+
+ headers = {
+ 'Content-Type': 'application/xml',
+ 'Content-Length': 0,
+ 'x-goog-resumable': 'start'
+ }
+
+ # Send an HTTP POST request to the given upload_url
+ req = Request(upload_url, data={}, headers=headers)
+ resp = self._url_opener.open(req)
+
+ return resp.headers['location']
+
+ def Dump(self, output):
+ """Serialize the IncrementalUploadHelper and store in file-like object.
+
+ Args:
+ output: a file-like object where the status of the IncrementalUploadHelper
+ will be written.
+
+ Raises:
+ GoogleAdsError: If a YAMLError occurs while writing to the file.
+ """
+ data = {
+ 'current_content_length': self._current_content_length,
+ 'is_last': self._is_last,
+ 'server': self._request_builder.GetServer(),
+ 'upload_url': self._upload_url,
+ 'version': self._request_builder.GetVersion()
+ }
+
+ try:
+ yaml.dump(data, output)
+ except yaml.YAMLError as e:
+ raise googleads.errors.GoogleAdsError(
+ 'Error dumping IncrementalUploadHelper to file: %s' % str(e))
+
+ def UploadOperations(self, operations, is_last=False):
+ """Uploads operations to the given uploadUrl in incremental steps.
+
+ Note: Each list of operations is expected to contain operations of the
+ same type, similar to how one would normally send operations in an
+ AdWords API Service request.
+
+ Args:
+ operations: one or more lists of operations as would be sent to the
+ AdWords API for the associated service.
+ is_last: a boolean indicating whether this is the final increment to be
+ added to the batch job.
+ """
+ if self._is_last:
+ raise googleads.errors.AdWordsBatchJobServiceInvalidOperationError(
+ 'Can\'t add new operations to a completed incremental upload.')
+ # Build the request
+ req = self._request_builder.BuildUploadRequest(
+ self._upload_url, operations,
+ current_content_length=self._current_content_length, is_last=is_last)
+ # Make the request, ignoring the urllib.error.HTTPError raised due to HTTP
+ # status code 308 (for resumable uploads).
+ try:
+ _batch_job_logger.debug('Outgoing request: %s %s %s',
+ req.get_full_url(), req.headers, req.data)
+
+ self._url_opener.open(req)
+
+ if _batch_job_logger.isEnabledFor(logging.INFO):
+ _batch_job_logger.info('Request summary: %s',
+ self._ExtractRequestSummaryFields(req))
+ except HTTPError as e:
+ if e.code != 308:
+ if _batch_job_logger.isEnabledFor(logging.WARNING):
+ _batch_job_logger.warning(
+ 'Request summary: %s',
+ self._ExtractRequestSummaryFields(req, error=e))
+ raise
+ # Update upload status.
+ self._current_content_length += len(req.data)
+ self._is_last = is_last
+
+ def _ExtractRequestSummaryFields(self, request, error=None):
+ """Extract fields used in the summary logs.
+
+ Args:
+ request: a urllib.request.Request instance configured to make the request.
+ [optional]
+ error: a urllib.error.HttpError instance used to retrieve error details.
+
+ Returns:
+ A dict containing the fields to be output in the summary logs.
+ """
+ headers = request.headers
+ summary_fields = {
+ 'server': request.get_full_url(),
+ 'contentRange': headers['Content-range'],
+ 'contentLength': headers['Content-length']
+ }
+
+ if error:
+ summary_fields['isError'] = True
+ summary_fields['errorMessage'] = error.reason
+ else:
+ summary_fields['isError'] = False
+
+ return summary_fields
+
+
+@googleads.common.RegisterUtility(
+ 'ReportDownloader', {'DownloadReport': 'File',
+ 'DownloadReportWithAwql': 'File',
+ 'DownloadReportAsStream': 'Stream',
+ 'DownloadReportAsStreamWithAwql': 'Stream',
+ 'DownloadReportAsString': 'String',
+ 'DownloadReportAsStringWithAwql': 'String'})
class ReportDownloader(object):
"""A utility that can be used to download reports from AdWords."""
@@ -424,9 +1165,11 @@ class ReportDownloader(object):
_SCHEMA_FORMAT = '/'.join([_END_POINT_FORMAT, 'reportDefinition.xsd'])
# The name of the complex type representing a report definition.
_REPORT_DEFINITION_NAME = 'reportDefinition'
+ # Used to extract the reporting URL for logging.
+ _SERVER_PATTERN = re.compile('https?://(.+?)/.*')
def __init__(self, adwords_client, version=sorted(_SERVICE_MAP.keys())[-1],
- server=_DEFAULT_ENDPOINT):
+ server=None):
"""Initializes a ReportDownloader.
Args:
@@ -438,40 +1181,49 @@ def __init__(self, adwords_client, version=sorted(_SERVICE_MAP.keys())[-1],
in future releases to point to what is then the latest version.
server: A string identifying the webserver hosting the AdWords API.
"""
- if server[-1] == '/': server = server[:-1]
+ if not server:
+ server = _DEFAULT_ENDPOINT
+
+ server = server.rstrip('/')
self._adwords_client = adwords_client
self._namespace = self._NAMESPACE_FORMAT % version
self._end_point = self._END_POINT_FORMAT % (server, version)
- self._header_handler = _AdWordsHeaderHandler(adwords_client, version)
-
- proxy_option = None
- if self._adwords_client.https_proxy:
- proxy_option = {'https': self._adwords_client.https_proxy}
- # Create an Opener to handle requests when downloading reports.
- self.url_opener = urllib2.build_opener(
- urllib2.ProxyHandler({'https': self._adwords_client.https_proxy}))
- else:
- self.url_opener = urllib2.build_opener()
+ self._header_handler = _AdWordsHeaderHandler(
+ adwords_client, version, self._adwords_client.enable_compression,
+ self._adwords_client.custom_http_headers)
+ self.proxy_config = self._adwords_client.proxy_config
+ handlers = self.proxy_config.GetHandlers()
+ self.url_opener = build_opener(*handlers)
+ if self._adwords_client.custom_http_headers:
+ self.url_opener.addheaders.extend(
+ adwords_client.custom_http_headers.items())
schema_url = self._SCHEMA_FORMAT % (server, version)
- schema = suds.client.Client(
- schema_url,
- doctor=suds.xsd.doctor.ImportDoctor(suds.xsd.doctor.Import(
- self._namespace, schema_url)),
- proxy=proxy_option, cache=self._adwords_client.cache).wsdl.schema
- self._report_definition_type = schema.elements[
- (self._REPORT_DEFINITION_NAME, self._namespace)]
- self._marshaller = suds.mx.literal.Literal(schema)
+ service_class = googleads.common.GetSchemaHelperForLibrary()
+ self.schema_helper = service_class(
+ schema_url, self._adwords_client.timeout,
+ self.proxy_config, self._namespace, self._adwords_client.cache)
def _DownloadReportCheckFormat(self, file_format, output):
- if(file_format.startswith('GZIPPED_')
- and not (('b' in getattr(output, 'mode', 'w')) or
- type(output) is io.BytesIO)):
- raise googleads.errors.GoogleAdsValueError('Need to specify a binary'
- ' output for GZIPPED formats.')
-
- def DownloadReport(self, report_definition, output=sys.stdout,
- skip_report_header=None, skip_report_summary=None):
+ """Verifies file format compatibility with given output."""
+ encoding = getattr(output, 'encoding', None)
+
+ # StringIO instances have an encoding set to None, and BytesIO instances
+ # lack an encoding attribute. As a result, if encoding is ever set, it
+ # indicates that the specified output is incompatible with GZIPPED formats.
+ if encoding and file_format.startswith('GZIPPED_'):
+ raise googleads.errors.GoogleAdsValueError(
+ 'Need to specify a binary output for GZIPPED formats.')
+
+ # Because StringIO instances always have encoding set to None, it's
+ # necessary to verify that StringIO instances aren't used with GZIPPED
+ # formats.
+ if (file_format.startswith('GZIPPED_')
+ and isinstance(output, io.StringIO)):
+ raise googleads.errors.GoogleAdsValueError(
+ 'Need to specify a binary output for GZIPPED formats.')
+
+ def DownloadReport(self, report_definition, output=sys.stdout, **kwargs):
"""Downloads an AdWords report using a report definition.
The report contents will be written to the given output.
@@ -484,12 +1236,24 @@ def DownloadReport(self, report_definition, output=sys.stdout,
output: A writable object where the contents of the report will be written
to. If the report is gzip compressed, you need to specify an output
that can write binary data.
+ **kwargs: Optional keyword arguments.
+
+ Keyword Arguments:
+ client_customer_id: A string containing a client_customer_id intended to
+ override the default value set for the client.
+ include_zero_impressions: A boolean indicating whether the report should
+ show rows with zero impressions.
skip_report_header: A boolean indicating whether to include a header row
containing the report name and date range. If false or not specified,
report output will include the header row.
+ skip_column_header: A boolean indicating whether to include column names
+ in reports. If false or not specified, report output will include the
+ column names.
skip_report_summary: A boolean indicating whether to include a summary row
containing the report totals. If false or not specified, report output
will include the summary row.
+ use_raw_enum_values: A boolean indicating whether to return enum field
+ values as enums instead of display values.
Raises:
AdWordsReportBadRequestError: if the report download fails due to
@@ -501,10 +1265,9 @@ def DownloadReport(self, report_definition, output=sys.stdout,
"""
self._DownloadReportCheckFormat(report_definition['downloadFormat'], output)
self._DownloadReport(self._SerializeReportDefinition(report_definition),
- output, skip_report_header, skip_report_summary)
+ output, **kwargs)
- def DownloadReportAsStream(self, report_definition, skip_report_header=None,
- skip_report_summary=None):
+ def DownloadReportAsStream(self, report_definition, **kwargs):
"""Downloads an AdWords report using a report definition.
This will return a stream, allowing you to retrieve the report contents.
@@ -513,13 +1276,24 @@ def DownloadReportAsStream(self, report_definition, skip_report_header=None,
report_definition: A dictionary or instance of the ReportDefinition class
generated from the schema. This defines the contents of the report
that will be downloaded.
- [optional]
+ **kwargs: Optional keyword arguments.
+
+ Keyword Arguments:
+ client_customer_id: A string containing a client_customer_id intended to
+ override the default value set for the client.
+ include_zero_impressions: A boolean indicating whether the report should
+ show rows with zero impressions.
skip_report_header: A boolean indicating whether to include a header row
containing the report name and date range. If false or not specified,
report output will include the header row.
+ skip_column_header: A boolean indicating whether to include column names
+ in reports. If false or not specified, report output will include the
+ column names.
skip_report_summary: A boolean indicating whether to include a summary row
containing the report totals. If false or not specified, report output
will include the summary row.
+ use_raw_enum_values: A boolean indicating whether to return enum field
+ values as enums instead of display values.
Returns:
A stream to be used in retrieving the report contents.
@@ -533,12 +1307,9 @@ def DownloadReportAsStream(self, report_definition, skip_report_header=None,
network error.
"""
return self._DownloadReportAsStream(
- self._SerializeReportDefinition(report_definition), skip_report_header,
- skip_report_summary)
+ self._SerializeReportDefinition(report_definition), **kwargs)
- def DownloadReportAsStreamWithAwql(self, query, file_format,
- skip_report_header=None,
- skip_report_summary=None):
+ def DownloadReportAsStreamWithAwql(self, query, file_format, **kwargs):
"""Downloads an AdWords report using an AWQL query.
The report contents will be returned as a stream.
@@ -549,13 +1320,24 @@ def DownloadReportAsStreamWithAwql(self, query, file_format,
file_format: A string representing the output format for your report.
Acceptable values can be found in our API documentation:
https://developers.google.com/adwords/api/docs/guides/reporting
- [optional]
+ **kwargs: Optional keyword arguments.
+
+ Keyword Arguments:
+ client_customer_id: A string containing a client_customer_id intended to
+ override the default value set for the client.
+ include_zero_impressions: A boolean indicating whether the report should
+ show rows with zero impressions.
skip_report_header: A boolean indicating whether to include a header row
containing the report name and date range. If false or not specified,
report output will include the header row.
+ skip_column_header: A boolean indicating whether to include column names
+ in reports. If false or not specified, report output will include the
+ column names.
skip_report_summary: A boolean indicating whether to include a summary row
containing the report totals. If false or not specified, report output
will include the summary row.
+ use_raw_enum_values: A boolean indicating whether to return enum field
+ values as enums instead of display values.
Returns:
A stream to be used in retrieving the report contents.
@@ -569,10 +1351,9 @@ def DownloadReportAsStreamWithAwql(self, query, file_format,
network error.
"""
return self._DownloadReportAsStream(self._SerializeAwql(query, file_format),
- skip_report_header, skip_report_summary)
+ **kwargs)
- def DownloadReportAsString(self, report_definition,
- skip_report_header=None, skip_report_summary=None):
+ def DownloadReportAsString(self, report_definition, **kwargs):
"""Downloads an AdWords report using a report definition.
The report contents will be returned as a string.
@@ -581,13 +1362,24 @@ def DownloadReportAsString(self, report_definition,
report_definition: A dictionary or instance of the ReportDefinition class
generated from the schema. This defines the contents of the report
that will be downloaded.
- [optional]
+ **kwargs: Optional keyword arguments.
+
+ Keyword Arguments:
+ client_customer_id: A string containing a client_customer_id intended to
+ override the default value set for the client.
+ include_zero_impressions: A boolean indicating whether the report should
+ show rows with zero impressions.
skip_report_header: A boolean indicating whether to include a header row
containing the report name and date range. If false or not specified,
report output will include the header row.
+ skip_column_header: A boolean indicating whether to include column names
+ in reports. If false or not specified, report output will include the
+ column names.
skip_report_summary: A boolean indicating whether to include a summary row
containing the report totals. If false or not specified, report output
will include the summary row.
+ use_raw_enum_values: A boolean indicating whether to return enum field
+ values as enums instead of display values.
Returns:
A string containing the report contents.
@@ -600,17 +1392,16 @@ def DownloadReportAsString(self, report_definition,
AdWordsReportError: if the request fails for any other reason; e.g. a
network error.
"""
+ response = None
try:
- response = StringIO.StringIO()
- self._DownloadReport(self._SerializeReportDefinition(report_definition),
- response, skip_report_header, skip_report_summary)
- return response.getvalue()
+ response = self._DownloadReportAsStream(
+ self._SerializeReportDefinition(report_definition), **kwargs)
+ return response.read().decode('utf-8')
finally:
- response.close()
+ if response:
+ response.close()
- def DownloadReportAsStringWithAwql(self, query, file_format,
- skip_report_header=None,
- skip_report_summary=None):
+ def DownloadReportAsStringWithAwql(self, query, file_format, **kwargs):
"""Downloads an AdWords report using an AWQL query.
The report contents will be returned as a string.
@@ -621,13 +1412,24 @@ def DownloadReportAsStringWithAwql(self, query, file_format,
file_format: A string representing the output format for your report.
Acceptable values can be found in our API documentation:
https://developers.google.com/adwords/api/docs/guides/reporting
- [optional]
+ **kwargs: Optional keyword arguments.
+
+ Keyword Arguments:
+ client_customer_id: A string containing a client_customer_id intended to
+ override the default value set for the client.
+ include_zero_impressions: A boolean indicating whether the report should
+ show rows with zero impressions.
skip_report_header: A boolean indicating whether to include a header row
containing the report name and date range. If false or not specified,
report output will include the header row.
+ skip_column_header: A boolean indicating whether to include column names
+ in reports. If false or not specified, report output will include the
+ column names.
skip_report_summary: A boolean indicating whether to include a summary row
containing the report totals. If false or not specified, report output
will include the summary row.
+ use_raw_enum_values: A boolean indicating whether to return enum field
+ values as enums instead of display values.
Returns:
A string containing the report contents.
@@ -640,23 +1442,24 @@ def DownloadReportAsStringWithAwql(self, query, file_format,
AdWordsReportError: if the request fails for any other reason; e.g. a
network error.
"""
+ response = None
try:
- response = StringIO.StringIO()
- self._DownloadReport(self._SerializeAwql(query, file_format), response,
- skip_report_header, skip_report_summary)
- return response.getvalue()
+ response = self._DownloadReportAsStream(
+ self._SerializeAwql(query, file_format), **kwargs)
+ return response.read().decode('utf-8')
finally:
- response.close()
+ if response:
+ response.close()
def DownloadReportWithAwql(self, query, file_format, output=sys.stdout,
- skip_report_header=None, skip_report_summary=None):
+ **kwargs):
"""Downloads an AdWords report using an AWQL query.
The report contents will be written to the given output.
Args:
- query: A string containing the query which specifies the data you want
- your report to include.
+ query: A string or ReportQuery object containing the query which
+ specifies the data you want your report to include.
file_format: A string representing the output format for your report.
Acceptable values can be found in our API documentation:
https://developers.google.com/adwords/api/docs/guides/reporting
@@ -664,12 +1467,24 @@ def DownloadReportWithAwql(self, query, file_format, output=sys.stdout,
output: A writable object where the contents of the report will be written
to. If the report is gzip compressed, you need to specify an output
that can write binary data.
+ **kwargs: Optional keyword arguments.
+
+ Keyword Arguments:
+ client_customer_id: A string containing a client_customer_id intended to
+ override the default value set for the client.
+ include_zero_impressions: A boolean indicating whether the report should
+ show rows with zero impressions.
skip_report_header: A boolean indicating whether to include a header row
containing the report name and date range. If false or not specified,
report output will include the header row.
+ skip_column_header: A boolean indicating whether to include column names
+ in reports. If false or not specified, report output will include the
+ column names.
skip_report_summary: A boolean indicating whether to include a summary row
containing the report totals. If false or not specified, report output
will include the summary row.
+ use_raw_enum_values: A boolean indicating whether to return enum field
+ values as enums instead of display values.
Raises:
AdWordsReportBadRequestError: if the report download fails due to
@@ -681,57 +1496,98 @@ def DownloadReportWithAwql(self, query, file_format, output=sys.stdout,
"""
self._DownloadReportCheckFormat(file_format, output)
self._DownloadReport(self._SerializeAwql(query, file_format), output,
- skip_report_header, skip_report_summary)
+ **kwargs)
- def _DownloadReport(self, post_body, output, skip_report_header,
- skip_report_summary):
+ def _DownloadReport(self, post_body, output, **kwargs):
"""Downloads an AdWords report, writing the contents to the given file.
+ This will attempt to determine the encoding of the specified output and
+ read the report with the appropriate StreamReader.
+
Args:
post_body: The contents of the POST request's body as a URL encoded
string.
output: A writable object where the contents of the report will be written
to.
+ **kwargs: A dictionary containing optional keyword arguments.
+
+ Keyword Arguments:
+ client_customer_id: A string containing a client_customer_id intended to
+ override the default value set for the client.
+ include_zero_impressions: A boolean indicating whether the report should
+ show rows with zero impressions.
skip_report_header: A boolean indicating whether to include a header row
containing the report name and date range. If false or not specified,
report output will include the header row.
+ skip_column_header: A boolean indicating whether to include column names
+ in reports. If false or not specified, report output will include the
+ column names.
skip_report_summary: A boolean indicating whether to include a summary row
containing the report totals. If false or not specified, report output
will include the summary row.
+ use_raw_enum_values: A boolean indicating whether to return enum field
+ values as enums instead of display values.
Raises:
AdWordsReportBadRequestError: if the report download fails due to
improper input. In the event of certain other failures, a
- urllib2.URLError (Python 2) or urllib.error.URLError (Python 3) will be
- raised.
+ urllib.error.URLError will be raised.
AdWordsReportError: if the request fails for any other reason; e.g. a
network error.
"""
- response = self._DownloadReportAsStream(post_body, skip_report_header,
- skip_report_summary)
+ response = None
+ try:
+ response = self._DownloadReportAsStream(post_body, **kwargs)
+
+ # Determine encoding of provided output.
+ if isinstance(output, io.StringIO):
+ encoding = 'utf-8'
+ else:
+ encoding = getattr(output, 'encoding', None)
+
+ # If any encoding is found, apply the appropriate StreamReader to the
+ # response. When reading in chunks, this prevents truncation of multi-byte
+ # characters; e.g. utf-8. For more details, see:
+ # https://github.com/googleads/googleads-python-lib/issues/281
+ if encoding:
+ stream_reader = codecs.getreader(encoding)
+ response = stream_reader(response)
+
+ while True:
+ chunk = response.read(_CHUNK_SIZE)
+ if not chunk: break
+ output.write(chunk)
+ finally:
+ if response:
+ response.close()
- while True:
- chunk = response.read(CHUNK_SIZE)
- if not chunk:
- break
- output.write(chunk.decode() if sys.version_info[0] == 3
- and (getattr(output, 'mode', 'w') == 'w'
- and type(output) is not io.BytesIO)
- else chunk)
+ def _DownloadReportAsStream(self, post_body, **kwargs):
+ """Downloads an AdWords report, returning a stream-like object.
- def _DownloadReportAsStream(self, post_body, skip_report_header,
- skip_report_summary):
- """Downloads an AdWords report, returning a stream.
+ This will return a http.client.HTTPResponse instance, reading from which
+ will return binary data.
Args:
post_body: The contents of the POST request's body as a URL encoded
string.
+ **kwargs: Optional keyword arguments.
+
+ Keyword Arguments:
+ client_customer_id: A string containing a client_customer_id intended to
+ override the default value set for the client.
+ include_zero_impressions: A boolean indicating whether the report should
+ show rows with zero impressions.
skip_report_header: A boolean indicating whether to include a header row
containing the report name and date range. If false or not specified,
report output will include the header row.
+ skip_column_header: A boolean indicating whether to include column names
+ in reports. If false or not specified, report output will include the
+ column names.
skip_report_summary: A boolean indicating whether to include a summary row
containing the report totals. If false or not specified, report output
will include the summary row.
+ use_raw_enum_values: A boolean indicating whether to return enum field
+ values as enums instead of display values.
Returns:
A stream to be used in retrieving the report contents.
@@ -739,58 +1595,146 @@ def _DownloadReportAsStream(self, post_body, skip_report_header,
Raises:
AdWordsReportBadRequestError: if the report download fails due to
improper input. In the event of certain other failures, a
- urllib2.URLError (Python 2) or urllib.error.URLError (Python 3) will be
- raised.
+ urllib.error.URLError will be raised.
AdWordsReportError: if the request fails for any other reason; e.g. a
network error.
"""
if sys.version_info[0] == 3:
post_body = bytes(post_body, 'utf8')
- request = urllib2.Request(
+
+ request = Request(
self._end_point, post_body,
- self._header_handler.GetReportDownloadHeaders(skip_report_header,
- skip_report_summary))
+ self._header_handler.GetReportDownloadHeaders(**kwargs))
try:
- return self.url_opener.open(request)
- except urllib2.HTTPError, e:
- raise self._ExtractError(e)
-
- def _SerializeAwql(self, query, file_format):
- """Serializes an AWQL query and file format for transport.
+ if _report_logger.isEnabledFor(logging.DEBUG):
+ _report_logger.debug('Outgoing request: %s %s',
+ self._SanitizeRequestHeaders(request.headers),
+ post_body)
+
+ response = self.url_opener.open(request)
+
+ if _report_logger.isEnabledFor(logging.INFO):
+ _report_logger.info(
+ 'Request Summary: %s', self._ExtractRequestSummaryFields(request))
+
+ if _report_logger.isEnabledFor(logging.DEBUG):
+ _report_logger.debug('Incoming response: %s %s %s REDACTED REPORT DATA',
+ self._ExtractResponseHeaders(response.headers),
+ response.code, response.msg)
+ return response
+ except HTTPError as e:
+ error = self._ExtractError(e)
+ if _report_logger.isEnabledFor(logging.WARNING):
+ _report_logger.warning(
+ 'Request Summary: %s', self._ExtractRequestSummaryFields(
+ request, error=error))
+ raise error
+
+ def _SanitizeRequestHeaders(self, headers):
+ """Removes sensitive data from request headers for use in logging.
Args:
- query: A string representing the AWQL query used in the report.
- file_format: A string representing the file format of the generated
- report.
+ headers: a dict containing the headers to be sanitized.
Returns:
- The given query and format URL encoded into the format needed for an
- AdWords report request as a string. This is intended to be a POST body.
+ A dict containing a sanitized copy of the provided headers.
"""
- return urllib.urlencode({'__fmt': file_format, '__rdquery': query})
+ sanitized_headers = dict(headers)
- def _SerializeReportDefinition(self, report_definition):
- """Serializes a report definition for transport.
+ sanitized_headers['Developertoken'] = 'REDACTED'
+ sanitized_headers['Authorization'] = 'REDACTED'
+
+ return sanitized_headers
+
+ def _ExtractResponseHeaders(self, headers):
+ """Extracts the given headers to a dict for logging.
Args:
- report_definition: A dictionary or ReportDefinition object to be
- serialized.
+ headers: a httplib.HTTPMessage instance containing response headers.
Returns:
- The given report definition serialized into XML and then URL encoded into
+ A dict containing the contents of the response headers.
+ """
+ header_lines = str(headers).split('\n')
+ headers = {}
+
+ for header_line in header_lines:
+ if header_line:
+ k, v = header_line.split(': ')
+ headers[k] = v
+
+ return headers
+
+ def _ExtractRequestSummaryFields(self, request, error=None):
+ """Extract fields used in the summary logs.
+
+ Args:
+ request: a urllib.request.Request instance.
+ [optional]
+ error: a googleads.errors.AdWordsReportError instance or subclass used to
+ retrieve error details. This should only be present when an error
+ occurred, otherwise it should be set to None for successful requests.
+
+ Returns:
+ A dict containing the fields to be output in the summary logs.
+ """
+ server = (self._SERVER_PATTERN.search(request.get_full_url())
+ .group(1))
+ headers = request.headers
+
+ summary_fields = {
+ 'clientCustomerId': headers.get('Clientcustomerid'),
+ 'includeZeroImpressions': headers.get('Includezeroimpressions', False),
+ 'server': server,
+ 'skipColumnHeader': headers.get('Skipcolumnheader', False),
+ 'skipReportHeader': headers.get('Skipreportheader', False),
+ 'skipReportSummary': headers.get('Skipreportsummary', False),
+ }
+
+ if error:
+ summary_fields['isError'] = True
+ summary_fields['errorMessage'] = error.content
+ else:
+ summary_fields['isError'] = False
+
+ return summary_fields
+
+ def _SerializeAwql(self, query, file_format):
+ """Serializes an AWQL query and file format for transport.
+
+ Args:
+ query: A string or ReportQuery object representing the AWQL query used in
+ the report.
+ file_format: A string representing the file format of the generated
+ report.
+
+ Returns:
+ The given query and format URL encoded into the format needed for an
+ AdWords report request as a string. This is intended to be a POST body.
+ """
+ return urlencode({'__fmt': file_format, '__rdquery': str(query)})
+
+ def _SerializeReportDefinition(self, report_definition):
+ """Serializes a report definition for transport.
+
+ Args:
+ report_definition: A dictionary or ReportDefinition object to be
+ serialized.
+
+ Returns:
+ The given report definition serialized into XML and then URL encoded into
the format needed for an AdWords report request as a string. This is
intended to be a POST body.
"""
- content = suds.mx.Content(
- tag=self._REPORT_DEFINITION_NAME, value=report_definition,
- name=self._REPORT_DEFINITION_NAME, type=self._report_definition_type)
- return urllib.urlencode({'__rdxml': self._marshaller.process(content)})
+ return urlencode(
+ {'__rdxml': self.schema_helper.GetSoapXMLForComplexType(
+ self._REPORT_DEFINITION_NAME, report_definition)})
def _ExtractError(self, error):
"""Attempts to extract information from a report download error XML message.
Args:
- error: A urllib2.HTTPError describing the report download failure.
+ error: A urllib.error.HTTPError describing the report download failure.
Returns:
An error that should be raised. If the content was an XML error message,
@@ -812,3 +1756,741 @@ def _ExtractError(self, error):
pass
return googleads.errors.AdWordsReportError(
error.code, error, content)
+
+
+class _QueryBuilder(object):
+ """A query builder for building AWQL (AdWords Query Language) queries."""
+
+ def __init__(self, query_builder=None):
+ """Creates the query builder with the optional specified query builder.
+
+ This class shouldn't be instantiated directly or extended. Use
+ ReportQueryBuilder if you want to create a query for reporting or
+ ServiceQueryBuilder if you want to create a query for services.
+
+ Args:
+ query_builder: An optional query builder whose properties will be copied
+ over to this instance.
+
+ Returns:
+ The query builder.
+
+ Raises:
+ GoogleAdsValueError: If the passed query_builder isn't of the QueryBuilder
+ type.
+ """
+ if query_builder is None:
+ self.where_builders = []
+ else:
+ try:
+ self.where_builders = list(query_builder.where_builders)
+ except (AttributeError, TypeError):
+ raise googleads.errors.GoogleAdsValueError(
+ 'The passed query builder should be of the QueryBuilder type.')
+
+ def Select(self, *fields):
+ """Sets a provided list of fields as selected fields for the query.
+
+ Args:
+ *fields: The specified list of fields to be added to a SELECT clause.
+
+ Returns:
+ This query builder.
+ """
+ raise NotImplementedError('You must subclass _QueryBuilder.')
+
+ def Where(self, field):
+ """Creates a WHERE builder using a provided field.
+
+ Args:
+ field: the field to be added as an argument in the WHERE clause.
+
+ Returns:
+ The created WHERE builder.
+ """
+ where_builder = _WhereBuilder(self, field)
+ self.where_builders.append(where_builder)
+ return where_builder
+
+
+class _WhereBuilder(object):
+ """A WHERE builder for building a WHERE clause in AWQL queries."""
+
+ def __init__(self, query_builder, field):
+ """Creates the WHERE builder with specified query builder and field.
+
+ This class should be instantiated through _QueryBuilder.Where. Don't call
+ this constructor directly.
+
+ Args:
+ query_builder: The query builder that this WHERE builder links to.
+ field: The field to be used in the WHERE condition.
+
+ Returns:
+ The WHERE builder.
+ """
+ self._field = field
+ self._query_builder = query_builder
+ self._awql = None
+
+ def EqualTo(self, value):
+ """Sets the type of the WHERE clause as "equal to".
+
+ Args:
+ value: The value to be used in the WHERE condition.
+
+ Returns:
+ The query builder that this WHERE builder links to.
+ """
+ self._awql = self._CreateSingleValueCondition(value, '=')
+ return self._query_builder
+
+ def NotEqualTo(self, value):
+ """Sets the type of the WHERE clause as "not equal to".
+
+ Args:
+ value: The value to be used in the WHERE condition.
+
+ Returns:
+ The query builder that this WHERE builder links to.
+ """
+ self._awql = self._CreateSingleValueCondition(value, '!=')
+ return self._query_builder
+
+ def GreaterThan(self, value):
+ """Sets the type of the WHERE clause as "greater than".
+
+ Args:
+ value: The value to be used in the WHERE condition.
+
+ Returns:
+ The query builder that this WHERE builder links to.
+ """
+ self._awql = self._CreateSingleValueCondition(value, '>')
+ return self._query_builder
+
+ def GreaterThanOrEqualTo(self, value):
+ """Sets the type of the WHERE clause as "greater than or equal to".
+
+ Args:
+ value: The value to be used in the WHERE condition.
+
+ Returns:
+ The query builder that this WHERE builder links to.
+ """
+ self._awql = self._CreateSingleValueCondition(value, '>=')
+ return self._query_builder
+
+ def LessThan(self, value):
+ """Sets the type of the WHERE clause as "less than".
+
+ Args:
+ value: The value to be used in the WHERE condition.
+
+ Returns:
+ The query builder that this WHERE builder links to.
+ """
+ self._awql = self._CreateSingleValueCondition(value, '<')
+ return self._query_builder
+
+ def LessThanOrEqualTo(self, value):
+ """Sets the type of the WHERE clause as "less than or equal to.
+
+ Args:
+ value: The value to be used in the WHERE condition.
+
+ Returns:
+ The query builder that this WHERE builder links to.
+ """
+ self._awql = self._CreateSingleValueCondition(value, '<=')
+ return self._query_builder
+
+ def StartsWith(self, value):
+ """Sets the type of the WHERE clause as "starts with".
+
+ Args:
+ value: The value to be used in the WHERE condition.
+
+ Returns:
+ The query builder that this WHERE builder links to.
+ """
+ self._awql = self._CreateSingleValueCondition(value, 'STARTS_WITH')
+ return self._query_builder
+
+ def StartsWithIgnoreCase(self, value):
+ """Sets the type of the WHERE clause as "starts with ignore case".
+
+ Args:
+ value: The value to be used in the WHERE condition.
+
+ Returns:
+ The query builder that this WHERE builder links to.
+ """
+ self._awql = self._CreateSingleValueCondition(value,
+ 'STARTS_WITH_IGNORE_CASE')
+ return self._query_builder
+
+ def Contains(self, value):
+ """Sets the type of the WHERE clause as "contains".
+
+ Args:
+ value: The value to be used in the WHERE condition.
+
+ Returns:
+ The query builder that this WHERE builder links to.
+ """
+ self._awql = self._CreateSingleValueCondition(value, 'CONTAINS')
+ return self._query_builder
+
+ def ContainsIgnoreCase(self, value):
+ """Sets the type of the WHERE clause as "contains ignore case".
+
+ Args:
+ value: The value to be used in the WHERE condition.
+
+ Returns:
+ The query builder that this WHERE builder links to.
+ """
+ self._awql = self._CreateSingleValueCondition(value, 'CONTAINS_IGNORE_CASE')
+ return self._query_builder
+
+ def DoesNotContain(self, value):
+ """Sets the type of the WHERE clause as "does not contain".
+
+ Args:
+ value: The value to be used in the WHERE condition.
+
+ Returns:
+ The query builder that this WHERE builder links to.
+ """
+ self._awql = self._CreateSingleValueCondition(value, 'DOES_NOT_CONTAIN')
+ return self._query_builder
+
+ def DoesNotContainIgnoreCase(self, value):
+ """Sets the type of the WHERE clause as "doesn not contain ignore case".
+
+ Args:
+ value: The value to be used in the WHERE condition.
+
+ Returns:
+ The query builder that this WHERE builder links to.
+ """
+ self._awql = self._CreateSingleValueCondition(
+ value, 'DOES_NOT_CONTAIN_IGNORE_CASE')
+ return self._query_builder
+
+ def In(self, *values):
+ """Sets the type of the WHERE clause as "in".
+
+ Args:
+ *values: The values to be used in the WHERE condition.
+
+ Returns:
+ The query builder that this WHERE builder links to.
+ """
+ self._awql = self._CreateMultipleValuesCondition(values, 'IN')
+ return self._query_builder
+
+ def NotIn(self, *values):
+ """Sets the type of the WHERE clause as "in".
+
+ Args:
+ *values: The values to be used in the WHERE condition.
+
+ Returns:
+ The query builder that this WHERE builder links to.
+ """
+ self._awql = self._CreateMultipleValuesCondition(values, 'NOT_IN')
+ return self._query_builder
+
+ def ContainsAny(self, *values):
+ """Sets the type of the WHERE clause as "contains any".
+
+ Args:
+ *values: The values to be used in the WHERE condition.
+
+ Returns:
+ The query builder that this WHERE builder links to.
+ """
+ self._awql = self._CreateMultipleValuesCondition(values, 'CONTAINS_ANY')
+ return self._query_builder
+
+ def ContainsNone(self, *values):
+ """Sets the type of the WHERE clause as "contains none".
+
+ Args:
+ *values: The values to be used in the WHERE condition.
+
+ Returns:
+ The query builder that this WHERE builder links to.
+ """
+ self._awql = self._CreateMultipleValuesCondition(values, 'CONTAINS_NONE')
+ return self._query_builder
+
+ def ContainsAll(self, *values):
+ """Sets the type of the WHERE clause as "contains all".
+
+ Args:
+ *values: The values to be used in the WHERE condition.
+
+ Returns:
+ The query builder that this WHERE builder links to.
+ """
+ self._awql = self._CreateMultipleValuesCondition(values, 'CONTAINS_ALL')
+ return self._query_builder
+
+ def Build(self):
+ """Builds the WHERE clause by returning the stored AWQL.
+
+ Returns:
+ The resulting WHERE clause in AWQL format.
+ """
+ return self._awql
+
+ def _CreateSingleValueCondition(self, value, operator):
+ """Creates a single-value condition with the provided value and operator."""
+ if isinstance(value, str):
+ value = '"%s"' % value
+ return '%s %s %s' % (self._field, operator, value)
+
+ def _CreateMultipleValuesCondition(self, values, operator):
+ """Creates a condition with the provided list of values and operator."""
+ values = ['"%s"' % value if isinstance(value, str) else
+ str(value) for value in values]
+ return '%s %s [%s]' % (self._field, operator, ', '.join(values))
+
+
+@googleads.common.RegisterUtility('ReportQueryBuilder')
+class ReportQueryBuilder(_QueryBuilder):
+ """A query builder for building AWQL queries for reporting."""
+
+ def __init__(self, query_builder=None):
+ """Creates the report query builder with the optionally specified builder.
+
+ Creates the report query builder by initializing all attributes including
+ the report name, time range, start and end date. If the optional query
+ builder are specified, copy all its attributes to this instance.
+
+ Args:
+ query_builder: An optional query builder whose attributes will be copied
+ over to this instance.
+
+ Returns:
+ This report query builder.
+
+ Raises:
+ GoogleAdsValueError: If the passed query_builder isn't of the QueryBuilder
+ type.
+ """
+ _QueryBuilder.__init__(self, query_builder)
+ if query_builder is None:
+ self.select = None
+ self.from_report = None
+ self.date_range = None
+ self.start_date = None
+ self.end_date = None
+ else:
+ try:
+ self.select = list(query_builder.select)
+ self.from_report = query_builder.from_report
+ self.date_range = query_builder.date_range
+ self.start_date = query_builder.start_date
+ self.end_date = query_builder.end_date
+ except (AttributeError, TypeError):
+ raise googleads.errors.GoogleAdsValueError(
+ 'The passed query builder should be of ReportQueryBuilder type.')
+
+ def Select(self, *fields):
+ """Sets a provided list of fields as selected fields for the query.
+
+ Subsequent calls to this method overwrite the entire set of selected fields
+ with the new one.
+
+ Args:
+ *fields: The specified list of fields to be added to a SELECT clause.
+
+ Returns:
+ This report query builder.
+ """
+ self.select = list(fields)
+ return self
+
+ def From(self, report_name):
+ """Sets a provided report name as the argument to FROM clause.
+
+ Args:
+ report_name: The specified report name.
+
+ Returns:
+ This report query builder.
+ """
+ self.from_report = report_name
+ return self
+
+ def During(self, date_range=None, start_date=None, end_date=None):
+ """Sets arguments for the DURING clause of the query.
+
+ Sets arguments for the DURING clause using the provided date range or start
+ and end dates. Only the date range or start and end date should be
+ specified. If both are supplied, an error will be thrown. A valid date range
+ string can be found at
+ https://developers.google.com/adwords/api/docs/guides/reporting#date_ranges.
+ Start and end dates should be in 'YYYYMMDD' format.
+
+ Args:
+ date_range: The specified date range string, e.g., YESTERDAY.
+ start_date: The start date string in 'YYYYMMDD' format or an instance of
+ datetime.date.
+ end_date: The end date string in 'YYYYMMDD' format or an instance of
+ datetime.date.
+
+ Returns:
+ This report query builder.
+
+ Raises:
+ ValueError: If all the arguments are None or both date_range and start
+ and end dates have values or if start_date has value but end_date
+ doesn't (and vice versa).
+ """
+ if date_range is None and (start_date is None or end_date is None):
+ raise ValueError(
+ 'Either date_range or both start_date and end_date must not be None.')
+ if date_range is not None and (start_date is not None
+ or end_date is not None):
+ raise ValueError(
+ 'If date_range is not None, start_date and end_date must be None '
+ '(and vice versa).')
+ self.date_range = date_range
+ self.start_date = start_date
+ self.end_date = end_date
+ return self
+
+ def Build(self):
+ """Builds a ReportQuery object containing the created AWQL query.
+
+ Returns:
+ The created ReportQuery object.
+
+ Raises:
+ ValueError: If the selected fields or report name is not specified.
+ """
+ if self.select is None:
+ raise ValueError('Must use Select() to specify SELECT clause for valid'
+ ' AWQL first.')
+ if self.from_report is None:
+ raise ValueError('Must use From() to specify FROM clause for valid AWQL'
+ ' first.')
+
+ parts = ['SELECT ', (', '.join(self.select))]
+ parts.extend([' FROM ', self.from_report])
+ where_clause = (' WHERE %s' % ' AND '.join([builder.Build() for builder
+ in self.where_builders])
+ if self.where_builders else '')
+ parts += where_clause
+
+ if self.date_range:
+ parts.extend([' DURING ', self.date_range])
+ elif self._start_date and self._end_date:
+ parts.extend([' DURING ', '%s,%s' % (self._start_date, self._end_date)])
+ awql = ''.join(parts)
+
+ return ReportQuery(awql)
+
+ @property
+ def start_date(self):
+ """Gets the start date of the query."""
+ return self._start_date
+
+ @start_date.setter
+ def start_date(self, start_date):
+ """Sets the start date of the query to the provided value."""
+ if isinstance(start_date, datetime.date):
+ self._start_date = '{:%Y%m%d}'.format(start_date)
+ else:
+ self._start_date = start_date
+
+ @property
+ def end_date(self):
+ """Gets the end date of the query."""
+ return self._end_date
+
+ @end_date.setter
+ def end_date(self, end_date):
+ """Sets the end date of the query to the provided value."""
+ if isinstance(end_date, datetime.date):
+ self._end_date = '{:%Y%m%d}'.format(end_date)
+ else:
+ self._end_date = end_date
+
+
+class ReportQuery(object):
+ """A report query storing an AWQL query."""
+
+ def __init__(self, awql):
+ """Creates a report query instance storing the provided AWQL query."""
+ self._awql = awql
+
+ def __str__(self):
+ """Returns the stored AWQL query."""
+ return self._awql
+
+
+@googleads.common.RegisterUtility('ServiceQueryBuilder')
+class ServiceQueryBuilder(_QueryBuilder):
+ """A query builder for building AWQL queries for services."""
+
+ _ORDER_BY_CLAUSE = namedtuple('OrderByClause', ['field', 'direction'])
+
+ def __init__(self, query_builder=None):
+ """Creates the service query builder with the optionally specified builder.
+
+ Creates the service query builder by initializing all attributes including
+ oder by list, start index, and page size.
+ If the optional query builder are specified, copy all its attributes to this
+ instance.
+
+ Args:
+ query_builder: An optional query builder whose attributes will be copied
+ over to this instance.
+
+ Returns:
+ This service query builder.
+
+ Raises:
+ GoogleAdsValueError: If the passed query_builder isn't of the QueryBuilder
+ type.
+ """
+ _QueryBuilder.__init__(self, query_builder)
+ if query_builder is None:
+ self.select = set()
+ self.order_by_list = []
+ self.start_index = None
+ self.page_size = None
+ else:
+ try:
+ self.select = query_builder.select
+ self.order_by_list = query_builder.order_by_list
+ self.start_index = query_builder.start_index
+ self.page_size = query_builder.page_size
+ except (AttributeError, TypeError):
+ raise googleads.errors.GoogleAdsValueError(
+ 'The passed query builder should be of ServiceQueryBuilder type.')
+
+ def Select(self, *fields):
+ """Sets a provided list of fields as selected fields for the query.
+
+ Subsequent calls to this method overwrite the entire set of selected fields
+ with the new one. Duplicate field names will be treated as one field.
+
+ Args:
+ *fields: The specified list of fields to be added to a SELECT clause.
+
+ Returns:
+ This service query builder.
+ """
+ self.select.update(fields)
+ return self
+
+ def OrderBy(self, field, ascending=True):
+ """Adds the provided field to the order-by list with the provided direction.
+
+ Args:
+ field: The specified field to be added to the order-by list.
+ ascending: If true, the newly created order-by clause will be in ascending
+ order. Otherwise, it will be in descending order.
+
+ Returns:
+ This service query builder.
+ """
+ order_by = self._ORDER_BY_CLAUSE(field, 'ASC' if ascending else 'DESC')
+ self.order_by_list.append(order_by)
+ return self
+
+ def Limit(self, start_index, page_size):
+ """Sets the LIMIT clause using the provided start index and page size.
+
+ Args:
+ start_index: The specified start index for the LIMIT clause.
+ page_size: The optional page size for the LIMIT clause.
+
+ Returns:
+ This service query builder.
+
+ Raises:
+ ValueError: If start_index is None but the page_size is not None or vice
+ versa.
+ """
+ if ((start_index is None and page_size is not None)
+ or (start_index is not None and page_size is None)):
+ raise ValueError('Either both start_index and page_size must be None, or'
+ ' neither')
+ self.start_index = start_index
+ self.page_size = page_size
+ return self
+
+ def Build(self):
+ """Builds a ServiceQuery object containing AWQL queries.
+
+ Returns:
+ The created ServiceQuery object.
+
+ Raises:
+ ValueError: If the selected fields or service name is not specified.
+ """
+ if not self.select:
+ raise ValueError('Must use Select() to specify SELECT clause for valid'
+ ' AWQL first')
+
+ parts = ['SELECT ', (', '.join(self.select))]
+ where_clause = (' WHERE %s' % ' AND '.join(builder.Build() for builder
+ in self.where_builders)
+ if self.where_builders else '')
+ parts += where_clause
+
+ if self.order_by_list:
+ parts.extend([' ORDER BY ',
+ ', '.join('%s %s' % (order_by.field, order_by.direction)
+ for order_by in self.order_by_list)])
+ awql = ''.join(parts)
+
+ return ServiceQuery(awql, self.start_index, self.page_size)
+
+ @property
+ def select(self):
+ """Gets the select set of the query."""
+ return self._select
+
+ @select.setter
+ def select(self, select):
+ """Sets the select set of the query to the copy of provided value."""
+ self._select = set(select)
+
+ @property
+ def order_by_list(self):
+ """Gets the order-by list of the query."""
+ return self._order_by_list
+
+ @order_by_list.setter
+ def order_by_list(self, order_by_list):
+ """Sets the order-by list of the query to the copy of provided value."""
+ self._order_by_list = list(order_by_list)
+
+
+class ServiceQuery(object):
+ """A service query storing an AWQL query."""
+
+ _BID_LANDSCAPE_PAGES = ('AdGroupBidLandscapePage',
+ 'CriterionBidLandscapePage')
+ _LANDSCAPE_POINTS = 'landscapePoints'
+ _TOTAL_NUM_ENTRIES = 'totalNumEntries'
+ _ENTRIES = 'entries'
+ _PAGE_TYPE = 'Page.Type'
+
+ def __init__(self, awql, start_index, page_size):
+ """Creates a service query instance storing the provided AWQL query."""
+ self._awql = awql
+ self._start_index = start_index
+ self._page_size = page_size
+ self._total_num_entries = None
+
+ def NextPage(self, page=None):
+ """Sets the LIMIT clause of the AWQL to the next page.
+
+ This method is meant to be used with HasNext(). When using DataService,
+ page is needed, as its paging mechanism is different from other services.
+ For details, see
+ https://developers.google.com/adwords/api/docs/guides/bid-landscapes#paging_through_results.
+
+ Args:
+ page: An optional dict-like page returned in an API response, where the
+ type depends on the configured SOAP client. The page contains the
+ 'totalNumEntries' key whose value represents the total number of
+ results from making the query to the AdWords API services. This page
+ is required when using this method with DataService.
+
+ Returns:
+ This service query object.
+
+ Raises:
+ ValueError: If the start index of this object is None, meaning that the
+ LIMIT clause hasn't been set before.
+ """
+ if self._start_index is None:
+ raise ValueError('Cannot page through query with no LIMIT clause.')
+
+ # DataService has a different paging mechanism, resulting in different
+ # method of determining if there is still a page left.
+ page_size = None
+ if (page and self._PAGE_TYPE in page
+ and page[self._PAGE_TYPE] in self._BID_LANDSCAPE_PAGES):
+ page_size = sum([len(bid_landscape[self._LANDSCAPE_POINTS])
+ for bid_landscape in page[self._ENTRIES]])
+
+ increment = page_size or self._page_size
+ self._start_index += increment
+ return self
+
+ def HasNext(self, page):
+ """Checks if there is still a page left to query.
+
+ This method is meant to be used with NextPage(). When using DataService,
+ the paging mechanism is different from other services. For details, see
+ https://developers.google.com/adwords/api/docs/guides/bid-landscapes#paging_through_results.
+
+ Args:
+ page: A dict-like page returned in an API response, where the type depends
+ on the configured SOAP client. The page contains the 'totalNumEntries'
+ key whose value represents the total number of results from making the
+ query to the AdWords API services.
+
+ Returns:
+ True if there is still a page left.
+
+ Raises:
+ ValueError: If the start index of this object is None, meaning that the
+ LIMIT clause hasn't been set before.
+ """
+ if self._start_index is None:
+ raise ValueError('Cannot page through query with no LIMIT clause.')
+ if page is None:
+ raise ValueError('The passed page cannot be None.')
+
+ # DataService has a different paging mechanism, resulting in different
+ # method of determining if there is still a page left.
+ if (self._PAGE_TYPE in page
+ and page[self._PAGE_TYPE] in self._BID_LANDSCAPE_PAGES):
+ if self._ENTRIES in page:
+ total_landscape_points = sum([len(bid_landscape[self._LANDSCAPE_POINTS])
+ for bid_landscape in page[self._ENTRIES]])
+ else:
+ total_landscape_points = 0
+ return total_landscape_points >= self._page_size
+
+ if not self._total_num_entries:
+ self._total_num_entries = page[self._TOTAL_NUM_ENTRIES]
+ return self._start_index + self._page_size < self._total_num_entries
+
+ def Pager(self, service):
+ """A page generator for this service query and the provided service.
+
+ This generates a page as a result from using the provided service's query()
+ method until there are no more results to fetch.
+
+ Args:
+ service: The service object for making a query using this service query.
+
+ Yields:
+ A resulting page from querying the provided service.
+ """
+ has_page = True
+ while has_page:
+ page = service.query(self)
+ yield page
+ has_page = self.HasNext(page)
+ if has_page:
+ self.NextPage()
+
+ def __str__(self):
+ """Returns the stored AWQL query combined with the LIMIT clause."""
+ awql = self._awql + ' LIMIT %s,%s' % (self._start_index, self._page_size)
+ return awql
diff --git a/googleads/common.py b/googleads/common.py
index 337733e5..94462c44 100644
--- a/googleads/common.py
+++ b/googleads/common.py
@@ -14,32 +14,75 @@
"""Common client library functions and classes used by all products."""
-__author__ = 'Joseph DiLallo'
-
+import abc
+import base64
+import binascii
+from functools import wraps
+import inspect
+import locale
+import logging
+import logging.config
import os
+import ssl
import sys
+import threading
import warnings
+from urllib.request import HTTPSHandler, ProxyHandler, build_opener
-import httplib2
-import socks
-import suds
+import lxml.builder
+import lxml.etree
+import requests.exceptions
import yaml
-
+import zeep
+import zeep.cache
+import zeep.exceptions
+import zeep.helpers
+import zeep.transports
+import zeep.xsd
import googleads.errors
import googleads.oauth2
+import googleads.util
+
+
+_logger = logging.getLogger(__name__)
+
+_PY_VERSION_MAJOR = sys.version_info.major
+_PY_VERSION_MINOR = sys.version_info.minor
+_PY_VERSION_MICRO = sys.version_info.micro
+_DEPRECATED_VERSION_TEMPLATE = (
+ 'This library is being run by an unsupported Python version (%s.%s.%s). In '
+ 'order to benefit from important security improvements and ensure '
+ 'compatibility with this library, upgrade to Python 3.6 or higher.')
-VERSION = '3.2.0'
+VERSION = '33.0.0'
_COMMON_LIB_SIG = 'googleads/%s' % VERSION
-_PROXY_YAML_KEY = 'proxy_info'
-_PYTHON_VERSION = 'Python/%d.%d' % (sys.version_info[0], sys.version_info[1])
+_LOGGING_KEY = 'logging'
+_HTTP_PROXY_YAML_KEY = 'http'
+_HTTPS_PROXY_YAML_KEY = 'https'
+_PROXY_CONFIG_KEY = 'proxy_config'
+_PYTHON_VERSION = 'Python/%d.%d.%d' % (
+ _PY_VERSION_MAJOR, _PY_VERSION_MINOR, _PY_VERSION_MICRO)
-# The keys in the authentication dictionary that are used to construct OAuth 2.0
-# credentials.
-_OAUTH_2_AUTH_KEYS = ('client_id', 'client_secret', 'refresh_token')
+# The required keys in the authentication dictionary that are used to construct
+# installed application OAuth2 credentials.
+_OAUTH2_INSTALLED_APP_KEYS = ('client_id', 'client_secret', 'refresh_token')
-# The keys in the proxy dictionary that are used to construct a ProxyInfo
-# instance.
-_PROXY_KEYS = ('host', 'port')
+# The keys in the authentication dictionary that are used to construct service
+# account OAuth2 credentials.
+_OAUTH2_SERVICE_ACCT_KEYS = ('path_to_private_key_file',)
+_OAUTH2_SERVICE_ACCT_KEYS_OPTIONAL = ('delegated_account',)
+
+# A key used to configure the client to accept and automatically decompress
+# gzip encoded SOAP responses.
+ENABLE_COMPRESSION_KEY = 'enable_compression'
+
+# A key used to configure the client to send arbitrary headers in SOAP requests.
+CUSTOM_HEADERS_KEY = 'custom_http_headers'
+
+# Global variables used to enable and store utility usage stats.
+_utility_registry = googleads.util.UtilityRegistry()
+_UTILITY_REGISTER_YAML_KEY = 'include_utilities_in_user_agent'
+_UTILITY_LOCK = threading.Lock()
def GenerateLibSig(short_name):
@@ -50,19 +93,44 @@ def GenerateLibSig(short_name):
Returns:
A library signature string to append to user-supplied user-agent value.
"""
- return ' (%s, %s, %s)' % (short_name, _COMMON_LIB_SIG, _PYTHON_VERSION)
+ with _UTILITY_LOCK:
+ utilities_used = ', '.join([utility for utility
+ in sorted(_utility_registry)])
+ _utility_registry.Clear()
+
+ if utilities_used:
+ return ' (%s, %s, %s, %s)' % (short_name, _COMMON_LIB_SIG, _PYTHON_VERSION,
+ utilities_used)
+ else:
+ return ' (%s, %s, %s)' % (short_name, _COMMON_LIB_SIG, _PYTHON_VERSION)
-def LoadFromStorage(path, product_yaml_key, required_client_values,
- optional_product_values):
+class CommonClient(object):
+ """Contains shared startup code between Ad Manager and AdWords clients."""
+
+ def __init__(self):
+ # Warn users on deprecated Python versions on initialization.
+ if _PY_VERSION_MAJOR == 3 and _PY_VERSION_MINOR < 6:
+ _logger.warning(_DEPRECATED_VERSION_TEMPLATE, _PY_VERSION_MAJOR,
+ _PY_VERSION_MINOR, _PY_VERSION_MICRO)
+
+ # Warn users about using non-utf8 encoding
+ _, encoding = locale.getdefaultlocale()
+ if encoding is None or encoding.lower() != 'utf-8':
+ _logger.warn('Your default encoding, %s, is not UTF-8. Please run this'
+ ' script with UTF-8 encoding to avoid errors.', encoding)
+
+
+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 OAuth 2.0 credentials. It may also optionally provide
- proxy_info in order to configure a proxy.
+ 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 be used.
+ yaml_doc: the yaml document whose keys should be used.
product_yaml_key: The key to read in the yaml as a string.
required_client_values: A tuple of strings representing values which must
be in the yaml file for a supported API. If one of these keys is not in
@@ -72,27 +140,40 @@ def LoadFromStorage(path, product_yaml_key, required_client_values,
Returns:
A dictionary map of the keys in the yaml file to their values. This will not
- contain the keys used for OAuth 2.0 client creation and instead will have a
+ contain the keys used for OAuth2 client creation and instead will have a
GoogleOAuth2Client object stored in the 'oauth2_client' field.
Raises:
A GoogleAdsValueError if the given yaml file does not contain the
information necessary to instantiate a client object - either a
- required_client_values key was missing or an OAuth 2.0 key was missing.
+ required_client_values key was missing or an OAuth2 key was missing.
"""
- if not os.path.isabs(path):
- path = os.path.expanduser(path)
+ data = yaml.safe_load(yaml_doc) or {}
+
+ if 'dfp' in data:
+ raise googleads.errors.GoogleAdsValueError(
+ 'Please replace the "dfp" key in the configuration YAML string with'
+ '"ad_manager" to fix this issue.')
+
+ logging_config = data.get(_LOGGING_KEY)
+ if logging_config:
+ logging.config.dictConfig(logging_config)
+
try:
- with open(path, 'r') as handle:
- data = yaml.safe_load(handle.read())
- product_data = data.get(product_yaml_key) or {}
- proxy_data = data.get(_PROXY_YAML_KEY) or {}
- except IOError:
+ product_data = data[product_yaml_key]
+ except KeyError:
raise googleads.errors.GoogleAdsValueError(
- 'Given yaml file, %s, could not be opened.' % path)
+ 'The "%s" configuration is missing'
+ % (product_yaml_key,))
+
+ if not isinstance(product_data, dict):
+ raise googleads.errors.GoogleAdsValueError(
+ 'The "%s" configuration is empty or invalid'
+ % (product_yaml_key,))
+
+ IncludeUtilitiesInUserAgent(data.get(_UTILITY_REGISTER_YAML_KEY, True))
original_keys = list(product_data.keys())
- original_proxy_keys = list(proxy_data.keys())
client_kwargs = {}
try:
for key in required_client_values:
@@ -100,40 +181,20 @@ def LoadFromStorage(path, product_yaml_key, required_client_values,
del product_data[key]
except KeyError:
raise googleads.errors.GoogleAdsValueError(
- 'Your yaml file, %s, is missing some of the required values. Required '
+ 'Some of the required values are missing. Required '
'values are: %s, actual values are %s'
- % (path, required_client_values, original_keys))
+ % (required_client_values, original_keys))
- try:
- proxy_info = (httplib2.ProxyInfo(socks.PROXY_TYPE_HTTP, proxy_data['host'],
- proxy_data['port'])
- if proxy_data else None)
- client_kwargs['https_proxy'] = ('%s:%s' % (proxy_info.proxy_host,
- proxy_info.proxy_port)
- if proxy_info else None)
- except KeyError:
- raise googleads.errors.GoogleAdsValueError(
- 'Your yaml file, %s, is missing some of the required proxy values.'
- 'Required values are: %s, actual values are %s'
- % (path, _PROXY_KEYS, original_proxy_keys))
+ proxy_config_data = data.get(_PROXY_CONFIG_KEY, {})
+ proxy_config = _ExtractProxyConfig(product_yaml_key, proxy_config_data)
+ client_kwargs['proxy_config'] = proxy_config
+ client_kwargs['oauth2_client'] = _ExtractOAuth2Client(
+ product_yaml_key, product_data, proxy_config)
- ca_certs = proxy_data.get('ca_certs', None)
- disable_ssl_certificate_validation = proxy_data.get(
- 'disable_ssl_certificate_validation', True)
+ client_kwargs[ENABLE_COMPRESSION_KEY] = data.get(
+ ENABLE_COMPRESSION_KEY, False)
- try:
- client_kwargs['oauth2_client'] = (
- googleads.oauth2.GoogleRefreshTokenClient(
- product_data['client_id'], product_data['client_secret'],
- product_data['refresh_token'], proxy_info,
- disable_ssl_certificate_validation, ca_certs))
- for auth_key in _OAUTH_2_AUTH_KEYS:
- del product_data[auth_key]
- except KeyError:
- raise googleads.errors.GoogleAdsValueError(
- 'Your yaml file, %s, is missing some of the required OAuth 2.0 '
- 'values. Required values are: %s, actual values are %s'
- % (path, _OAUTH_2_AUTH_KEYS, original_keys))
+ client_kwargs[CUSTOM_HEADERS_KEY] = data.get(CUSTOM_HEADERS_KEY, None)
for value in optional_product_values:
if value in product_data:
@@ -141,109 +202,524 @@ def LoadFromStorage(path, product_yaml_key, required_client_values,
del product_data[value]
if product_data:
- warnings.warn(
- 'Your yaml file, %s, contains the following unrecognized '
- 'keys: %s. They were ignored.' % (path, product_data), stacklevel=3)
+ warnings.warn('Could not recognize the following keys: %s. '
+ 'They were ignored.' % (product_data,), stacklevel=3)
return client_kwargs
-def _PackForSuds(obj, factory):
- """Packs SOAP input into the format we want for suds.
+def LoadFromStorage(path, product_yaml_key, required_client_values,
+ optional_product_values):
+ """Loads the data necessary for instantiating a client from file storage.
- 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 are copied - we don't mutate the input.
+ 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:
- obj: A parameter for a SOAP request which will be packed. If this is
- a dictionary or list, the contents will recursively be packed. If this
- is not a dictionary or list, the contents will be recursively searched
- for instances of unpacked dictionaries or lists.
- factory: The suds.client.Factory object which can create instances of the
- classes generated from the WSDL.
+ path: A path string to the yaml document whose keys should be used.
+ product_yaml_key: The key to read in the yaml as a string.
+ required_client_values: A tuple of strings representing values which must
+ be in the yaml file for a supported API. If one of these keys is not in
+ the yaml file, an error will be raised.
+ optional_product_values: A tuple of strings representing optional values
+ which may be in the yaml file.
Returns:
- If the given obj was a dictionary that contained the 'xsi_type' key, this
- will be an instance of a class generated from the WSDL. Otherwise, this will
- be the same data type as the input obj was.
+ A dictionary map of the keys in the yaml file to their values. This will not
+ contain the keys used for OAuth2 client creation and instead will have a
+ GoogleOAuth2Client object stored in the 'oauth2_client' field.
+
+ Raises:
+ A GoogleAdsValueError if the given yaml file does not contain the
+ information necessary to instantiate a client object - either a
+ required_client_values key was missing or an OAuth2 key was missing.
"""
- if obj in ({}, None):
- # Force suds to serialize empty objects. There are legitimate use cases for
- # this, for example passing in an empty SearchCriteria object to a DFA
- # search method in order to select everything.
- return suds.null()
- elif isinstance(obj, dict):
- if 'xsi_type' in obj:
- try:
- new_obj = factory.create(obj['xsi_type'])
- except suds.TypeNotFound:
- new_obj = factory.create(':'.join(['ns0', obj['xsi_type']]))
- # Suds sends an empty XML element for enum types which are not set. None
- # of Google's Ads APIs will accept this. Initializing all of the fields in
- # a suds object to None will ensure that they don't get serialized at all
- # unless the user sets a value. User values explicitly set to None will be
- # packed into a suds.null() object.
- for param, _ in new_obj:
- # Another problem is that the suds.mx.appender.ObjectAppender won't
- # serialize object types with no fields set, but both AdWords and DFP
- # rely on sending objects with just the xsi:type set. The below "if"
- # statement is an ugly hack that gets this to work in all(?) situations
- # by taking advantage of the fact that these classes generally all have
- # a type field. The only other option is to monkey patch ObjectAppender.
- if param.endswith('.Type'):
- setattr(new_obj, param, obj['xsi_type'])
- else:
- setattr(new_obj, param, None)
- for key in obj:
- if key == 'xsi_type': continue
- setattr(new_obj, key, _PackForSuds(obj[key], factory))
- else:
- new_obj = {}
- for key in obj:
- new_obj[key] = _PackForSuds(obj[key], factory)
- return new_obj
- elif isinstance(obj, (list, tuple)):
- return [_PackForSuds(item, factory) for item in obj]
+
+ if not os.path.isabs(path):
+ path = os.path.expanduser(path)
+
+ try:
+ with open(path, 'rb') as handle:
+ yaml_doc = handle.read()
+ except IOError:
+ raise googleads.errors.GoogleAdsValueError(
+ 'Given yaml file, %s, could not be opened.' % path)
+
+ try:
+ client_kwargs = LoadFromString(yaml_doc, product_yaml_key,
+ required_client_values,
+ optional_product_values)
+ except googleads.errors.GoogleAdsValueError as e:
+ raise googleads.errors.GoogleAdsValueError(
+ 'Given yaml file, %s, could not find some keys. %s' % (path, e))
+
+ return client_kwargs
+
+
+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_config: a ProxyConfig instance.
+
+ Returns:
+ An instantiated GoogleOAuth2Client subclass.
+
+ Raises:
+ A GoogleAdsValueError if the OAuth2 configuration for the given product is
+ misconfigured.
+ """
+ oauth2_kwargs = {
+ 'proxy_config': proxy_config
+ }
+
+ if all(config in product_data for config in _OAUTH2_INSTALLED_APP_KEYS):
+ oauth2_args = [
+ product_data['client_id'], product_data['client_secret'],
+ product_data['refresh_token']
+ ]
+ oauth2_client = googleads.oauth2.GoogleRefreshTokenClient
+ for key in _OAUTH2_INSTALLED_APP_KEYS:
+ del product_data[key]
+ elif all(config in product_data for config in _OAUTH2_SERVICE_ACCT_KEYS):
+ oauth2_args = [
+ product_data['path_to_private_key_file'],
+ googleads.oauth2.GetAPIScope(product_yaml_key),
+ ]
+ oauth2_kwargs.update({
+ 'sub': product_data.get('delegated_account')
+ })
+ oauth2_client = googleads.oauth2.GoogleServiceAccountClient
+ for key in _OAUTH2_SERVICE_ACCT_KEYS:
+ del product_data[key]
+ for optional_key in _OAUTH2_SERVICE_ACCT_KEYS_OPTIONAL:
+ if optional_key in product_data:
+ del product_data[optional_key]
else:
- _RecurseOverObject(obj, factory)
- return obj
+ raise googleads.errors.GoogleAdsValueError(
+ 'Your yaml file is incorrectly configured for OAuth2. You need to '
+ 'specify credentials for either the installed application flow (%s) '
+ 'or service account flow (%s).' %
+ (_OAUTH2_INSTALLED_APP_KEYS, _OAUTH2_SERVICE_ACCT_KEYS))
+
+ return oauth2_client(*oauth2_args, **oauth2_kwargs)
+
+
+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:
+ If there is a proxy to configure in proxy_config, this will return a
+ ProxyConfig instance with those settings. Otherwise, it will return None.
+
+ Raises:
+ A GoogleAdsValueError if one of the required keys specified by _PROXY_KEYS
+ is missing.
+ """
+ cafile = proxy_config_data.get('cafile', None)
+ disable_certificate_validation = proxy_config_data.get(
+ 'disable_certificate_validation', False)
+
+ http_proxy = proxy_config_data.get(_HTTP_PROXY_YAML_KEY)
+ https_proxy = proxy_config_data.get(_HTTPS_PROXY_YAML_KEY)
+ proxy_config = ProxyConfig(
+ http_proxy=http_proxy,
+ https_proxy=https_proxy,
+ cafile=cafile,
+ disable_certificate_validation=disable_certificate_validation)
+
+ return proxy_config
+
+
+def IncludeUtilitiesInUserAgent(value):
+ """Configures the logging of utilities in the User-Agent.
+
+ Args:
+ value: a bool indicating that you want to include utility names in the
+ User-Agent if set True, otherwise, these will not be added.
+ """
+ with _UTILITY_LOCK:
+ _utility_registry.SetEnabled(value)
+
+
+def AddToUtilityRegistry(utility_name):
+ """Directly add a utility to the registry, not a decorator.
+
+ Args:
+ utility_name: The name of the utility to add.
+ """
+ with _UTILITY_LOCK:
+ _utility_registry.Add(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.
+
+ Args:
+ utility_name: A str specifying the utility name associated with the class.
+ version_mapping: A dict containing optional version strings to append to the
+ utility string for individual methods; where the key is the method name and
+ the value is the text to be appended as the version.
+
+ Returns:
+ The decorated class.
+ """
+ def IsFunctionOrMethod(member):
+ """Determines if given member is a function or method.
+
+ These two are used in combination to ensure that inspect finds all of a
+ given utility class's methods in both Python 2 and 3.
+
+ Args:
+ member: object that is a member of a class, to be determined whether it is
+ a function or method.
+
+ Returns:
+ A boolean that is True if the provided member is a function or method, or
+ False if it isn't.
+ """
+ return inspect.isfunction(member) or inspect.ismethod(member)
+
+ def MethodDecorator(utility_method, version):
+ """Decorates a method in the utility class."""
+ registry_name = ('%s/%s' % (utility_name, version) if version
+ else utility_name)
+ @wraps(utility_method)
+ def Wrapper(*args, **kwargs):
+ AddToUtilityRegistry(registry_name)
+ return utility_method(*args, **kwargs)
+ return Wrapper
+
+ def ClassDecorator(cls):
+ """Decorates a utility class."""
+ for name, method in inspect.getmembers(cls, predicate=IsFunctionOrMethod):
+ # Public methods of the class will have the decorator applied.
+ if not name.startswith('_'):
+ # The decorator will only be applied to unbound methods; this prevents
+ # it from clobbering class methods. If the attribute doesn't exist, set
+ # None for PY3 compatibility.
+ if not getattr(method, '__self__', None):
+ setattr(cls, name, MethodDecorator(
+ method, version_mapping.get(name) if version_mapping else None))
+ return cls
+
+ return ClassDecorator
+
+
+class ProxyConfig(object):
+ """A utility for configuring the usage of a proxy."""
+
+ def __init__(self, http_proxy=None, https_proxy=None, cafile=None,
+ disable_certificate_validation=False):
+ self._http_proxy = http_proxy
+ self._https_proxy = https_proxy
+ self.proxies = {}
+ if self._https_proxy:
+ self.proxies['https'] = str(self._https_proxy)
+ if self._http_proxy:
+ self.proxies['http'] = str(self._http_proxy)
+
+ self.disable_certificate_validation = disable_certificate_validation
+ self.cafile = None if disable_certificate_validation else cafile
+ # Initialize the context used to generate the HTTPSHandler.
+ self.ssl_context = self._InitSSLContext(
+ self.cafile, self.disable_certificate_validation)
+
+ 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_certificate_validation: A boolean indicating whether
+ certificate verification is disabled. For security purposes, it is
+ highly recommended that certificate verification remain enabled.
+
+ Returns:
+ An ssl.SSLContext instance, or None if the version of Python being used
+ doesn't support it.
+ """
+ try:
+ if disable_ssl_certificate_validation:
+ ssl._create_default_https_context = ssl._create_unverified_context
+ ssl_context = ssl.create_default_context()
+ else:
+ ssl_context = ssl.create_default_context(cafile=cafile)
+ except AttributeError:
+ # Earlier versions lack ssl.create_default_context()
+ # Rather than raising the exception, no context will be provided for
+ # legacy support. Of course, this means no certificate validation is
+ # taking place!
+ return None
+
+ return ssl_context
+
+ def BuildOpener(self):
+ """Builds an OpenerDirector instance using the ProxyConfig settings.
+
+ This will return a urllib2.request.OpenerDirector instance.
+
+ Returns:
+ An OpenerDirector instance instantiated with settings defined in the
+ ProxyConfig instance.
+ """
+ return build_opener(*self.GetHandlers())
+
+ def GetHandlers(self):
+ """Retrieve the appropriate urllib handlers for the given configuration.
+
+ Returns:
+ A list of urllib.request.BaseHandler subclasses to be used when making
+ calls with proxy.
+ """
+ handlers = []
+
+ if self.ssl_context:
+ handlers.append(HTTPSHandler(context=self.ssl_context))
+
+ if self.proxies:
+ handlers.append(ProxyHandler(self.proxies))
+
+ return handlers
+
+
+class _ZeepProxyTransport(zeep.transports.Transport):
+ """A Zeep transport which configures caching, proxy support, and timeouts."""
+ def __init__(self, timeout, proxy_config, cache):
+ """Initializes _ZeepProxyTransport.
+
+ Args:
+ timeout: An integer timeout in MS for connections.
+ proxy_config: A ProxyConfig instance representing proxy settings.
+ cache: A zeep.cache.Base instance representing a cache strategy to employ.
+ """
+ if not cache:
+ cache = zeep.cache.SqliteCache()
+ elif cache == ZeepServiceProxy.NO_CACHE:
+ cache = None
+
+ super(_ZeepProxyTransport, self).__init__(
+ timeout=timeout, operation_timeout=timeout, cache=cache)
+
+ self.session.proxies = proxy_config.proxies
+
+
+
+class SoapPacker(object):
+ """A utility class to be passed to argument packing functions.
+
+ A subclass should be used in cases where custom logic is needed to pack a
+ given object in argument packing functions.
+ """
+
+ @classmethod
+ def Pack(cls, obj):
+ raise NotImplementedError('You must subclass SoapPacker.')
+
+def GetSchemaHelperForLibrary():
+ return ZeepSchemaHelper
-def _RecurseOverObject(obj, factory, parent=None):
- """Recurses over a nested structure to look for changes in Suds objects.
+
+class GoogleSchemaHelper(object):
+ """Base class for type to xml conversion.
+
+ Only used for AdWords reporting specialness. A subclass should be created
+ for each underlying SOAP implementation.
+ """
+ __metaclass__ = abc.ABCMeta
+
+ @abc.abstractmethod
+ 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 XML for the type.
+ """
+ return
+
+
+class ZeepSchemaHelper(GoogleSchemaHelper):
+ """Zeep schema helper implementation."""
+ def __init__(self, endpoint, timeout,
+ proxy_config, namespace_override, cache):
+ """Initializes a ZeepSchemaHelper.
+
+ Args:
+ endpoint: A string representing the URL to connect to.
+ timeout: An integer timeout in MS used to determine connection timeouts.
+ proxy_config: A googleads.common.ProxyConfig instance which represents
+ the proxy settings needed.
+ namespace_override: A string to doctor the WSDL namespace with.
+ cache: An instance of zeep.cache.Base to use for caching.
+
+ Raises:
+ GoogleAdsValueError: The wrong type was given for caching.
+ """
+
+ if cache and not (isinstance(cache, zeep.cache.Base) or
+ cache == ZeepServiceProxy.NO_CACHE):
+ raise googleads.errors.GoogleAdsValueError(
+ 'Must use a proper zeep cache with zeep.')
+
+ transport = _ZeepProxyTransport(timeout, proxy_config, cache)
+ try:
+ data = transport.load(endpoint)
+ except requests.exceptions.HTTPError as e:
+ raise googleads.errors.GoogleAdsSoapTransportError(str(e))
+
+ self.schema = zeep.xsd.Schema(lxml.etree.fromstring(data))
+ self._namespace_override = namespace_override
+ self._element_maker = lxml.builder.ElementMaker(
+ namespace=namespace_override, nsmap={'tns': namespace_override})
+
+ def GetSoapXMLForComplexType(self, type_name, value):
+ """Return an XML string representing a SOAP complex type.
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 instances of the
- classes generated from the WSDL.
- parent: The parent object that contains the obj parameter to be inspected.
+ 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.
+ """
+ element = self.schema.get_element(
+ '{%s}%s' % (self._namespace_override, type_name))
+ result_element = self._element_maker(element.qname.localname)
+ element_value = element(**value)
+ element.type.render(result_element, element_value)
+ data = lxml.etree.tostring(result_element).strip()
+ return data
+
+
+def GetServiceClassForLibrary():
+ return ZeepServiceProxy
+
+
+class GoogleSoapService(object):
+ """Base class for a SOAP service representation.
+
+ A subclass should be created for each underlying SOAP implementation.
"""
- if _IsSudsIterable(obj):
- # Since in-place modification of the Suds object is taking place, the
- # iterator should be done over a frozen copy of the unpacked fields.
- copy_of_obj = tuple(obj)
- for item in copy_of_obj:
- if _IsSudsIterable(item):
- if 'xsi_type' in item:
- if isinstance(obj, tuple):
- parent[obj[0]] = _PackForSuds(obj[1], factory)
- else:
- obj.remove(item)
- obj.append(_PackForSuds(item, factory))
- _RecurseOverObject(item, factory, obj)
+ __metaclass__ = abc.ABCMeta
+
+ def __init__(self, header_handler, packer, version):
+ """Initializes a SOAP service.
+
+ Args:
+ header_handler: A googleads.common.HeaderHandler instance used to set
+ SOAP and HTTP headers.
+ packer: A googleads.common.SoapPacker instance used to transform
+ entities.
+ version: the version of the current API, e.g. 'v201811'
+ """
+ self._header_handler = header_handler
+ self._packer = packer
+ self._version = version
+ self._method_proxies = {}
+
+ @abc.abstractmethod
+ def CreateSoapElementForType(self, type_name):
+ """Create an instance of a SOAP type.
+
+ Args:
+ type_name: The name of the type.
+
+ Returns:
+ An instance of type type_name.
+ """
+
+ @abc.abstractmethod
+ 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.
+ """
+
+ @abc.abstractmethod
+ 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.
+ """
+
+ @abc.abstractmethod
+ 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.
+ """
+
+ def __getattr__(self, attr):
+ """Support service.method() syntax."""
+ if self._WsdlHasMethod(attr):
+ if attr not in self._method_proxies:
+ self._method_proxies[attr] = self._CreateMethod(attr)
+ return self._method_proxies[attr]
+ else:
+ raise googleads.errors.GoogleAdsValueError('Service %s not found' % attr)
-def _IsSudsIterable(obj):
- """A short helper method to determine if a field is iterable for Suds."""
- return (obj and not isinstance(obj, basestring) and hasattr(obj, '__iter__'))
+class _ZeepAuthHeaderPlugin(zeep.Plugin):
+ """A zeep plugin responsible for setting our custom HTTP headers."""
+ def __init__(self, header_handler):
+ """Instantiate a new _ZeepAuthHeaderPlugin.
-class SudsServiceProxy(object):
- """Wraps a suds service object, allowing custom logic to be injected.
+ Args:
+ header_handler: A googleads.common.HeaderHandler instance.
+ """
+ self._header_handler = header_handler
+
+ 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 options dict for the SOAP binding.
+
+ Returns:
+ A tuple of the envelope and headers.
+ """
+ custom_headers = self._header_handler.GetHTTPHeaders()
+ http_headers.update(custom_headers)
+ return envelope, http_headers
+
+
+class ZeepServiceProxy(GoogleSoapService):
+ """Wraps a zeep service object, allowing custom logic to be injected.
This class is responsible for refreshing the HTTP and SOAP headers, so changes
to the client object will be reflected in future SOAP calls, and for
@@ -251,32 +727,243 @@ class SudsServiceProxy(object):
with all SOAP complex types.
Attributes:
- suds_client: The suds.client.Client this service belongs to. If you are
- familiar with suds and want to use autogenerated classes, you can access
- the client and its factory,
+ zeep_client: The zeep.Client this service belongs to. If you are
+ familiar with zeep, you can utilize this directly.
"""
- def __init__(self, suds_client, header_handler):
- """Initializes a suds service proxy.
+ NO_CACHE = 'zeep_no_cache'
+
+ def __init__(self, endpoint, header_handler, packer,
+ proxy_config, timeout, version, cache=None):
+ """Initializes a zeep service proxy.
Args:
- suds_client: The suds.client.Client whose service will be wrapped. Note
- that this is the client itself, not the client's embedded service
- object.
+ endpoint: A URL for the service.
header_handler: A HeaderHandler responsible for setting the SOAP and HTTP
headers on the service client.
+ packer: An optional subclass of googleads.common.SoapPacker that provides
+ customized packing logic.
+ proxy_config: A ProxyConfig that represents proxy settings.
+ timeout: An integer to set the connection timeout.
+ version: the version of the current API, e.g. 'v201811'
+ cache: An instance of zeep.cache.Base to pass to the underlying SOAP
+ library for caching. A file cache by default. To disable, pass
+ googleads.common.ZeepServiceProxy.NO_CACHE.
+
+ Raises:
+ GoogleAdsValueError: The wrong type was given for caching.
"""
- self.suds_client = suds_client
- self._header_handler = header_handler
- self._method_proxies = {}
+ super(ZeepServiceProxy, self).__init__(header_handler, packer, version)
- def __getattr__(self, attr):
- if attr in self.suds_client.wsdl.services[0].ports[0].methods:
- if attr not in self._method_proxies:
- self._method_proxies[attr] = self._CreateMethod(attr)
- return self._method_proxies[attr]
+ if cache and not (isinstance(cache, zeep.cache.Base) or
+ cache == self.NO_CACHE):
+ raise googleads.errors.GoogleAdsValueError(
+ 'Must use a proper zeep cache with zeep.')
+
+ transport = _ZeepProxyTransport(timeout, proxy_config, cache)
+ plugins = [_ZeepAuthHeaderPlugin(header_handler),
+ googleads.util.ZeepLogger()]
+ try:
+ self.zeep_client = zeep.Client(
+ endpoint, transport=transport, plugins=plugins)
+ except requests.exceptions.HTTPError as e:
+ raise googleads.errors.GoogleAdsSoapTransportError(str(e))
+
+ first_service = list(self.zeep_client.wsdl.services.values())[0]
+ first_port = list(first_service.ports.values())[0]
+ self._method_bindings = first_port.binding
+
+ def CreateSoapElementForType(self, type_name):
+ """Create an instance of a SOAP type.
+
+ Args:
+ type_name: The name of the type.
+
+ Returns:
+ An instance of type type_name.
+ """
+ return self.zeep_client.get_type(type_name)()
+
+ 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(method, args, set_type_attrs=True)
+ headers = self._GetZeepFormattedSOAPHeaders()
+
+ return self.zeep_client.create_message(
+ self.zeep_client.service, method, *packed_args, _soapheaders=headers)
+
+ 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:
+ return False
+
+ def _GetBindingNamespace(self):
+ """Return a string with the namespace of the service binding in the WSDL."""
+ return (list(self.zeep_client.wsdl.bindings.values())[0]
+ .port_name.namespace)
+
+ 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 complex objects which include
+ inherited types.
+
+ Args:
+ method_name: The name of the method that will be called.
+ args: A list of dictionaries containing arguments to the method.
+ 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:
+ A list of XML objects that can be passed to zeep.
+ """
+ # Get the params for the method to find the initial types to instantiate.
+ op_params = self.zeep_client.get_element(
+ '{%s}%s' % (self._GetBindingNamespace(), method_name)).type.elements
+ result = [self._PackArgumentsHelper(param, param_data, set_type_attrs)
+ for ((_, param), param_data) in zip(op_params, args)]
+ return result
+
+ @classmethod
+ 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
+ except (TypeError, binascii.Error):
+ pass
+ return False
+
+ 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 is only necessary for batch job service.
+
+ Returns:
+ An instance of type 'elem'.
+ """
+ if self._packer:
+ data = self._packer.Pack(data, self._version)
+
+ if isinstance(data, dict): # Instantiate from simple Python dict
+ # See if there is a manually specified derived type.
+ type_override = data.get('xsi_type')
+ if type_override:
+ elem_type = self._DiscoverElementTypeFromLocalname(type_override)
+ else:
+ elem_type = elem.type
+
+ data_formatted = data.items()
+ packed_result = self._CreateComplexTypeFromData(
+ elem_type, type_override is not None, data_formatted, set_type_attrs)
+ elif isinstance(data, zeep.xsd.CompoundValue):
+ # Here the data is already a SOAP element but we still need to look
+ # through it in case it has been edited with Python dicts.
+ elem_type = data._xsd_type
+ data_formatted = zip(dir(data), [data[k] for k in dir(data)])
+ packed_result = self._CreateComplexTypeFromData(
+ elem_type, False, data_formatted, set_type_attrs)
+ elif isinstance(data, (list, tuple)):
+ packed_result = [self._PackArgumentsHelper(elem, item, set_type_attrs)
+ for item in data]
else:
- return getattr(self.suds_client.service, attr)
+ packed_result = data
+
+ return packed_result
+
+ 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 any
+ namespace.
+ """
+ elem_type = None
+ last_exception = None
+ for ns_prefix in self.zeep_client.wsdl.types.prefix_map.values():
+ try:
+ elem_type = self.zeep_client.get_type(
+ '{%s}%s' % (ns_prefix, type_localname))
+ except zeep.exceptions.LookupError as e:
+ last_exception = e
+ continue
+ break
+ if not elem_type:
+ raise last_exception
+ return elem_type
+
+ 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 hydrate the type 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 fully initialized SOAP element.
+ """
+ elem_arguments = dict(elem_type.elements)
+
+ # A post order traversal of the original data, need to instantiate from
+ # the bottom up.
+ instantiated_arguments = {
+ k: self._PackArgumentsHelper(elem_arguments[k], v, set_type_attrs)
+ for k, v in data if k != 'xsi_type'}
+ if set_type_attrs:
+ found_type_attr = next((e_name for e_name, _ in elem_type.elements
+ if e_name.endswith('.Type')), None)
+ if found_type_attr and type_is_override:
+ instantiated_arguments[found_type_attr] = elem_type.qname.localname
+ # Now go back through the tree instantiating SOAP types as we go.
+ return elem_type(**instantiated_arguments)
+
+
+ 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
def _CreateMethod(self, method_name):
"""Create a method wrapping an invocation to the SOAP service.
@@ -287,20 +974,39 @@ def _CreateMethod(self, method_name):
Returns:
A callable that can be used to make the desired SOAP request.
"""
- soap_service_method = getattr(self.suds_client.service, method_name)
+ soap_service_method = self.zeep_client.service[method_name]
def MakeSoapRequest(*args):
- """Perform a SOAP call."""
- self._header_handler.SetHeaders(self.suds_client)
- return soap_service_method(*[_PackForSuds(arg, self.suds_client.factory)
- for arg in args])
-
+ AddToUtilityRegistry('zeep')
+ soap_headers = self._GetZeepFormattedSOAPHeaders()
+ packed_args = self._PackArguments(method_name, args)
+ try:
+ return soap_service_method(
+ *packed_args, _soapheaders=soap_headers)['body']['rval']
+ except zeep.exceptions.Fault as e:
+ error_list = ()
+ if e.detail is not None:
+ underlying_exception = e.detail.find(
+ '{%s}ApiExceptionFault' % self._GetBindingNamespace())
+ fault_type = self.zeep_client.get_element(
+ '{%s}ApiExceptionFault' % self._GetBindingNamespace())
+ fault = fault_type.parse(
+ underlying_exception, self.zeep_client.wsdl.types)
+ error_list = fault.errors or error_list
+ raise googleads.errors.GoogleAdsServerFault(
+ e.detail, errors=error_list, message=e.message)
return MakeSoapRequest
class HeaderHandler(object):
"""A generic header handler interface that must be subclassed by each API."""
- def SetHeaders(self, client):
- """Sets the SOAP and HTTP headers on the given suds client."""
- raise NotImplementedError('You must subclass HeaderHandler.')
+ __metaclass__ = abc.ABCMeta
+
+ @abc.abstractmethod
+ def GetSOAPHeaders(self, create_method):
+ """Returns the required SOAP Headers."""
+
+ @abc.abstractmethod
+ def GetHTTPHeaders(self):
+ """Returns the required HTTP headers."""
diff --git a/googleads/dfa.py b/googleads/dfa.py
deleted file mode 100644
index afccf285..00000000
--- a/googleads/dfa.py
+++ /dev/null
@@ -1,190 +0,0 @@
-# Copyright 2013 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Client library for the DoubleClick for Advertisers API."""
-
-__author__ = 'Joseph DiLallo'
-
-import os
-
-import suds.client
-import suds.sax.element
-import suds.transport
-import suds.wsse
-
-import googleads.common
-import googleads.errors
-
-
-class DfaClient(object):
- """A central location to set headers and create web service clients.
-
- Attributes:
- username: A string representation of your DFA username.
- oauth2_client: A googleads.oauth2.GoogleOAuth2Client used to authorize your
- requests.
- application_name: An arbitrary string which will be used to identify your
- application
- https_proxy: A string identifying the URL of a proxy that all HTTPS requests
- should be routed through. Modifying this value will not affect any SOAP
- service clients you've already created.
- """
-
- # The key in the storage yaml which contains DFA data.
- _YAML_KEY = 'dfa'
- # A list of values which must be provided to use DFA.
- _REQUIRED_INIT_VALUES = ('application_name', 'username')
- # A list of values which may optionally be provided when using DFA.
- _OPTIONAL_INIT_VALUES = ()
- # The format of SOAP service WSDLs. A server, version, and service name need
- # to be formatted in.
- _SOAP_SERVICE_FORMAT = '%s/%s/api/dfa-api/%s?wsdl'
- # A giant dictionary of DFA versions and the services they support.
- _SERVICE_MAP = {
- 'v1.19': ('ad', 'advertiser', 'advertisergroup', 'campaign', 'changelog',
- 'contentcategory', 'creative', 'creativefield', 'creativegroup',
- 'login', 'network', 'placement', 'site', 'size', 'spotlight',
- 'strategy', 'subnetwork', 'user', 'userrole', 'report'),
- 'v1.20': ('ad', 'advertiser', 'advertisergroup', 'campaign', 'changelog',
- 'contentcategory', 'creative', 'creativefield', 'creativegroup',
- 'login', 'network', 'placement', 'site', 'size', 'spotlight',
- 'strategy', 'subnetwork', 'user', 'userrole', 'report'),
- }
-
- @classmethod
- def LoadFromStorage(cls, path=None):
- """Creates an DfaClient with information stored in a yaml file.
-
- Args:
- [optional]
- path: The path string to the file containing cached DFA data.
-
- Returns:
- A DfaClient initialized with the values cached in the file.
-
- Raises:
- A GoogleAdsValueError if the given yaml file does not contain the
- information necessary to instantiate a client object - either a
- required key was missing or an OAuth 2.0 key was missing.
- """
- if path is None:
- path = os.path.join(os.path.expanduser('~'), 'googleads.yaml')
-
- return cls(**googleads.common.LoadFromStorage(
- path, cls._YAML_KEY, cls._REQUIRED_INIT_VALUES,
- cls._OPTIONAL_INIT_VALUES))
-
- def __init__(self, username, oauth2_client, application_name,
- https_proxy=None, cache=None):
- """Initializes a DfaClient.
-
- For more information on these arguments, see our SOAP headers guide:
- https://developers.google.com/doubleclick-advertisers/docs/SOAP_headers
-
- Args:
- username: A string representation of your DFA username. This is likely not
- the same as your Google Account name.
- oauth2_client: A googleads.oauth2.GoogleOAuth2Client used to authorize
- your requests.
- application_name: An arbitrary string which will be used to identify your
- application
- [optional]
- https_proxy: A string identifying the proxy that all HTTPS requests
- should be routed through.
- cache: A subclass of suds.cache.Cache; defaults to None.
- """
- self.username = username
- self.oauth2_client = oauth2_client
- self.application_name = application_name
- self.https_proxy = https_proxy
- self.cache = cache
- self._header_handler = _DfaHeaderHandler(self)
-
- def GetService(self, service_name, version=sorted(_SERVICE_MAP.keys())[-1],
- server='https://advertisersapi.doubleclick.com'):
- """Creates a service client for the given service.
-
- Args:
- service_name: A string identifying which DFA service to create a service
- client for.
- [optional]
- version: A string identifying the DFA version to connect to. This defaults
- to what is currently the latest version. This will be updated in
- future releases to point to what is then the latest version.
- server: A string identifying the webserver hosting the DFA API.
-
- Returns:
- A suds.client.ServiceSelector which has the headers and proxy configured
- for use.
-
- Raises:
- A GoogleAdsValueError if the service or version provided do not exist.
- """
- server = server[:-1] if server[-1] == '/' else server
- try:
- proxy_option = None
- if self.https_proxy:
- proxy_option = {
- 'https': self.https_proxy
- }
-
- client = suds.client.Client(
- self._SOAP_SERVICE_FORMAT % (server, version, service_name),
- proxy=proxy_option, cache=self.cache, timeout=3600)
- except suds.transport.TransportError:
- if version in self._SERVICE_MAP:
- if service_name in self._SERVICE_MAP[version]:
- raise
- else:
- raise googleads.errors.GoogleAdsValueError(
- 'Unrecognized service for the DFA API. Service given: %s '
- 'Supported services: %s'
- % (service_name, self._SERVICE_MAP[version]))
- else:
- raise googleads.errors.GoogleAdsValueError(
- 'Unrecognized version of the DFA API. Version given: %s Supported '
- 'versions: %s' % (version, self._SERVICE_MAP.keys()))
-
- return googleads.common.SudsServiceProxy(client, self._header_handler)
-
-
-class _DfaHeaderHandler(googleads.common.HeaderHandler):
- """Handler which sets the headers for a DFA SOAP call."""
-
- # The library signature for DFA, to be appended to all application_names.
- _LIB_SIG = googleads.common.GenerateLibSig('DfaApi-Python')
-
- def __init__(self, dfa_client):
- """Initializes a DfaHeaderHandler.
-
- Args:
- dfa_client: The DfaClient whose data will be used to fill in the headers.
- We retain a reference to this object so that the header handler picks
- up changes to the client.
- """
- self._dfa_client = dfa_client
-
- def SetHeaders(self, suds_client):
- """Sets the SOAP and HTTP headers on the given suds client."""
- wsse_header = suds.wsse.Security()
- wsse_header.tokens.append(
- suds.wsse.UsernameToken(self._dfa_client.username))
- request_header = suds.sax.element.Element('RequestHeader')
- request_header.append(
- suds.sax.element.Element('applicationName').setText(
- ''.join([self._dfa_client.application_name, self._LIB_SIG])))
-
- suds_client.set_options(
- wsse=wsse_header, soapheaders=request_header,
- headers=self._dfa_client.oauth2_client.CreateHttpHeader())
diff --git a/googleads/dfp.py b/googleads/dfp.py
deleted file mode 100644
index 28a261fd..00000000
--- a/googleads/dfp.py
+++ /dev/null
@@ -1,571 +0,0 @@
-# Copyright 2013 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Client library for the DoubleClick for Publishers API."""
-
-__author__ = 'Joseph DiLallo'
-
-import csv
-import datetime
-import logging
-import os
-import time
-import urllib2
-
-import pytz
-import suds.client
-import suds.transport
-
-import googleads.common
-import googleads.errors
-
-# The default application name.
-DEFAULT_APPLICATION_NAME = 'INSERT_APPLICATION_NAME_HERE'
-# The endpoint server for DFP.
-DEFAULT_ENDPOINT = 'https://ads.google.com'
-# The suggested page limit per page fetched from the API.
-SUGGESTED_PAGE_LIMIT = 500
-# The chunk size used for report downloads.
-_CHUNK_SIZE = 16 * 1024
-# A giant dictionary of DFP versions and the services they support.
-_SERVICE_MAP = {
- 'v201403':
- ('ActivityGroupService', 'ActivityService', 'AdRuleService',
- 'AudienceSegmentService', 'BaseRateService', 'CompanyService',
- 'ContactService', 'ContentBundleService',
- 'ContentMetadataKeyHierarchyService', 'ContentService',
- 'CreativeService', 'CreativeSetService', 'CreativeTemplateService',
- 'CreativeWrapperService', 'CustomFieldService',
- 'CustomTargetingService', 'ExchangeRateService', 'ForecastService',
- 'InventoryService', 'LabelService',
- 'LineItemCreativeAssociationService', 'LineItemService',
- 'LineItemTemplateService', 'LiveStreamEventService', 'NetworkService',
- 'OrderService', 'PlacementService', 'ProductService',
- 'ProductTemplateService', 'ProposalLineItemService', 'ProposalService',
- 'PublisherQueryLanguageService', 'RateCardCustomizationService',
- 'RateCardCustomizationGroupService', 'RateCardService',
- 'ReconciliationOrderReportService', 'ReconciliationReportRowService',
- 'ReconciliationReportService', 'ReportService',
- 'SuggestedAdUnitService', 'TeamService', 'UserService',
- 'UserTeamAssociationService', 'WorkflowRequestService'),
- 'v201405':
- ('ActivityGroupService', 'ActivityService', 'AdRuleService',
- 'AudienceSegmentService', 'BaseRateService', 'CompanyService',
- 'ContactService', 'ContentBundleService',
- 'ContentMetadataKeyHierarchyService', 'ContentService',
- 'CreativeService', 'CreativeSetService', 'CreativeTemplateService',
- 'CreativeWrapperService', 'CustomFieldService',
- 'CustomTargetingService', 'ExchangeRateService', 'ForecastService',
- 'InventoryService', 'LabelService',
- 'LineItemCreativeAssociationService', 'LineItemService',
- 'LineItemTemplateService', 'LiveStreamEventService', 'NetworkService',
- 'OrderService', 'PlacementService', 'ProductService',
- 'ProductTemplateService', 'ProposalLineItemService', 'ProposalService',
- 'PublisherQueryLanguageService', 'RateCardCustomizationService',
- 'RateCardCustomizationGroupService', 'RateCardService',
- 'ReconciliationOrderReportService', 'ReconciliationReportRowService',
- 'ReconciliationReportService', 'ReportService',
- 'SuggestedAdUnitService', 'TeamService', 'UserService',
- 'UserTeamAssociationService', 'WorkflowRequestService'),
- 'v201408':
- ('ActivityGroupService', 'ActivityService', 'AdRuleService',
- 'AudienceSegmentService', 'BaseRateService', 'CompanyService',
- 'ContactService', 'ContentBundleService',
- 'ContentMetadataKeyHierarchyService', 'ContentService',
- 'CreativeService', 'CreativeSetService', 'CreativeTemplateService',
- 'CreativeWrapperService', 'CustomFieldService',
- 'CustomTargetingService', 'ExchangeRateService', 'ForecastService',
- 'InventoryService', 'LabelService',
- 'LineItemCreativeAssociationService', 'LineItemService',
- 'LineItemTemplateService', 'LiveStreamEventService', 'NetworkService',
- 'OrderService', 'PlacementService', 'PremiumRateService',
- 'ProductService', 'ProductTemplateService', 'ProposalLineItemService',
- 'ProposalService', 'PublisherQueryLanguageService', 'RateCardService',
- 'ReconciliationOrderReportService', 'ReconciliationReportRowService',
- 'ReconciliationReportService', 'ReportService',
- 'SuggestedAdUnitService', 'TeamService', 'UserService',
- 'UserTeamAssociationService', 'WorkflowRequestService'),
- 'v201411':
- ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService',
- 'AdRuleService', 'AudienceSegmentService', 'BaseRateService',
- 'CompanyService', 'ContactService', 'ContentBundleService',
- 'ContentMetadataKeyHierarchyService', 'ContentService',
- 'CreativeService', 'CreativeSetService', 'CreativeTemplateService',
- 'CreativeWrapperService', 'CustomFieldService',
- 'CustomTargetingService', 'ExchangeRateService', 'ForecastService',
- 'InventoryService', 'LabelService',
- 'LineItemCreativeAssociationService', 'LineItemService',
- 'LineItemTemplateService', 'LiveStreamEventService', 'NetworkService',
- 'OrderService', 'PlacementService', 'PremiumRateService',
- 'ProductService', 'ProductTemplateService', 'ProposalLineItemService',
- 'ProposalService', 'PublisherQueryLanguageService', 'RateCardService',
- 'ReconciliationOrderReportService', 'ReconciliationReportRowService',
- 'ReconciliationReportService', 'ReportService', 'SharedAdUnitService',
- 'SuggestedAdUnitService', 'TeamService', 'UserService',
- 'UserTeamAssociationService', 'WorkflowRequestService'),
- 'v201502':
- ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService',
- 'AdRuleService', 'AudienceSegmentService', 'BaseRateService',
- 'CompanyService', 'ContactService', 'ContentBundleService',
- 'ContentMetadataKeyHierarchyService', 'ContentService',
- 'CreativeService', 'CreativeSetService', 'CreativeTemplateService',
- 'CreativeWrapperService', 'CustomFieldService',
- 'CustomTargetingService', 'ExchangeRateService', 'ForecastService',
- 'InventoryService', 'LabelService',
- 'LineItemCreativeAssociationService', 'LineItemService',
- 'LineItemTemplateService', 'LiveStreamEventService', 'NetworkService',
- 'OrderService', 'PackageService', 'PlacementService',
- 'PremiumRateService', 'ProductService', 'ProductPackageService',
- 'ProductPackageItemService', 'ProductTemplateService',
- 'ProposalLineItemService', 'ProposalService',
- 'PublisherQueryLanguageService', 'RateCardService',
- 'ReconciliationOrderReportService', 'ReconciliationReportRowService',
- 'ReconciliationReportService', 'ReportService', 'SharedAdUnitService',
- 'SuggestedAdUnitService', 'TeamService', 'UserService',
- 'UserTeamAssociationService', 'WorkflowRequestService'),
-}
-
-
-class DfpClient(object):
- """A central location to set headers and create web service clients.
-
- Attributes:
- oauth2_client: A googleads.oauth2.GoogleOAuth2Client used to authorize your
- requests.
- application_name: An arbitrary string which will be used to identify your
- application
- network_code: A string identifying the network code of the network you are
- accessing. All requests other than some NetworkService calls require
- this header to be set.
- https_proxy: A string identifying the URL of a proxy that all HTTPS requests
- should be routed through. Modifying this value will not affect any SOAP
- service clients you've already created.
- """
-
- # The key in the storage yaml which contains DFP data.
- _YAML_KEY = 'dfp'
- # A list of values which must be provided to use DFP.
- _REQUIRED_INIT_VALUES = ('application_name',)
- # A list of values which may optionally be provided when using DFP.
- _OPTIONAL_INIT_VALUES = (
- 'network_code', 'https_proxy')
- # The format of SOAP service WSDLs. A server, version, and service name need
- # to be formatted in.
- _SOAP_SERVICE_FORMAT = '%s/apis/ads/publisher/%s/%s?wsdl'
-
- @classmethod
- def LoadFromStorage(cls, path=None):
- """Creates a DfpClient with information stored in a yaml file.
-
- Args:
- [optional]
- path: str The path to the file containing cached DFP data.
-
- Returns:
- A DfpClient initialized with the values cached in the file.
-
- Raises:
- A GoogleAdsValueError if the given yaml file does not contain the
- information necessary to instantiate a client object - either a
- required key was missing or an OAuth 2.0 key was missing.
- """
- if path is None:
- path = os.path.join(os.path.expanduser('~'), 'googleads.yaml')
-
- return cls(**googleads.common.LoadFromStorage(
- path, cls._YAML_KEY, cls._REQUIRED_INIT_VALUES,
- cls._OPTIONAL_INIT_VALUES))
-
- def __init__(self, oauth2_client, application_name, network_code=None,
- https_proxy=None, cache=None):
- """Initializes a DfpClient.
-
- For more information on these arguments, see our SOAP headers guide:
- https://developers.google.com/doubleclick-publishers/docs/soap_xml
-
- Args:
- oauth2_client: A googleads.oauth2.GoogleOAuth2Client used to authorize
- your requests.
- application_name: An arbitrary string which will be used to identify your
- application
- [optional]
- network_code: A string identifying the network code of the network you are
- accessing. All requests other than getAllNetworks and getCurrentUser
- calls require this header to be set.
- https_proxy: A string identifying the proxy that all HTTPS requests
- should be routed through.
- cache: A subclass of suds.cache.Cache; defaults to None.
- """
- if application_name is DEFAULT_APPLICATION_NAME:
- raise googleads.errors.GoogleAdsValueError(
- 'Application name must be set and not be the default [%s]' %
- DEFAULT_APPLICATION_NAME)
-
- self.oauth2_client = oauth2_client
- self.application_name = application_name
- self.network_code = network_code
- self.https_proxy = https_proxy
- self.cache = cache
- self._header_handler = _DfpHeaderHandler(self)
-
- def GetService(self, service_name, version=sorted(_SERVICE_MAP.keys())[-1],
- server=DEFAULT_ENDPOINT):
- """Creates a service client for the given service.
-
- Args:
- service_name: A string identifying which DFP service to create a service
- client for.
- [optional]
- version: A string identifying the DFP version to connect to. This defaults
- to what is currently the latest version. This will be updated in
- future releases to point to what is then the latest version.
- server: A string identifying the webserver hosting the DFP API.
-
- Returns:
- A suds.client.ServiceSelector which has the headers and proxy configured
- for use.
-
- Raises:
- A GoogleAdsValueError if the service or version provided do not exist.
- """
- server = server[:-1] if server[-1] == '/' else server
- try:
- proxy_option = None
- if self.https_proxy:
- proxy_option = {
- 'https': self.https_proxy
- }
-
- client = suds.client.Client(
- self._SOAP_SERVICE_FORMAT % (server, version, service_name),
- proxy=proxy_option, cache=self.cache, timeout=3600)
- except suds.transport.TransportError:
- if version in _SERVICE_MAP:
- if service_name in _SERVICE_MAP[version]:
- raise
- else:
- raise googleads.errors.GoogleAdsValueError(
- 'Unrecognized service for the DFP API. Service given: %s '
- 'Supported services: %s'
- % (service_name, _SERVICE_MAP[version]))
- else:
- raise googleads.errors.GoogleAdsValueError(
- 'Unrecognized version of the DFP API. Version given: %s Supported '
- 'versions: %s' % (version, _SERVICE_MAP.keys()))
-
- return googleads.common.SudsServiceProxy(client, self._header_handler)
-
- def GetDataDownloader(self, version=sorted(_SERVICE_MAP.keys())[-1],
- server=DEFAULT_ENDPOINT):
- """Creates a downloader for DFP reports and PQL result sets.
-
- This is a convenience method. It is functionally identical to calling
- DataDownloader(dfp_client, version, server)
-
- Args:
- [optional]
- version: A string identifying the DFP version to connect to. This defaults
- to what is currently the latest version. This will be updated in
- future releases to point to what is then the latest version.
- server: A string identifying the webserver hosting the DFP API.
-
- Returns:
- A DataDownloader tied to this DfpClient, ready to download reports.
- """
- return DataDownloader(self, version, server)
-
-
-class _DfpHeaderHandler(googleads.common.HeaderHandler):
- """Handler which sets the headers for a DFP SOAP call."""
-
- # The library signature for DFP, to be appended to all application_names.
- _LIB_SIG = googleads.common.GenerateLibSig('DfpApi-Python')
- # The name of the WSDL-defined SOAP Header class used in all requests.
- _SOAP_HEADER_CLASS = 'SoapRequestHeader'
-
- def __init__(self, dfp_client):
- """Initializes a DfpHeaderHandler.
-
- Args:
- dfp_client: The DfpClient whose data will be used to fill in the headers.
- We retain a reference to this object so that the header handler picks
- up changes to the client.
- """
- self._dfp_client = dfp_client
-
- def SetHeaders(self, suds_client):
- """Sets the SOAP and HTTP headers on the given suds client."""
- header = suds_client.factory.create(self._SOAP_HEADER_CLASS)
- header.networkCode = self._dfp_client.network_code
- header.applicationName = ''.join([self._dfp_client.application_name,
- self._LIB_SIG])
-
- suds_client.set_options(
- soapheaders=header,
- headers=self._dfp_client.oauth2_client.CreateHttpHeader())
-
-
-class FilterStatement(object):
- """A statement object for PQL and get*ByStatement queries.
-
- The FilterStatement object allows for user control of limit/offset. It
- automatically limits queries to the suggested page limit if not explicitly
- set.
- """
-
- def __init__(
- self, where_clause='', values=None, limit=SUGGESTED_PAGE_LIMIT, offset=0):
- self.where_clause = where_clause
- self.values = values
- self.limit = limit
- self.offset = offset
-
- def ToStatement(self):
- """Returns this statement object in the format DFP requires."""
- return {'query': ('%s LIMIT %d OFFSET %d' %
- (self.where_clause, self.limit, self.offset)),
- 'values': self.values}
-
-
-class DataDownloader(object):
- """A utility that can be used to download reports and PQL result sets."""
-
- def __init__(self, dfp_client, version=sorted(_SERVICE_MAP.keys())[-1],
- server=DEFAULT_ENDPOINT):
- """Initializes a DataDownloader.
-
- Args:
- dfp_client: The DfpClient whose attributes will be used to authorize your
- report download and PQL query requests.
- [optional]
- version: A string identifying the DFP version to connect to. This defaults
- to what is currently the latest version. This will be updated in
- future releases to point to what is then the latest version.
- server: A string identifying the webserver hosting the DFP API.
- """
- if server[-1] == '/': server = server[:-1]
- self._dfp_client = dfp_client
- self._version = version
- self._server = server
- self._report_service = None
- self._pql_service = None
-
- def _GetReportService(self):
- """Lazily initializes a report service client."""
- if not self._report_service:
- self._report_service = self._dfp_client.GetService(
- 'ReportService', self._version, self._server)
- return self._report_service
-
- def _GetPqlService(self):
- """Lazily initializes a PQL service client."""
- if not self._pql_service:
- self._pql_service = self._dfp_client.GetService(
- 'PublisherQueryLanguageService', self._version, self._server)
- return self._pql_service
-
- 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 suds-generated ReportJob class.
-
- Returns:
- The completed report job's ID as a string.
-
- Raises:
- A DfpReportError if the report job fails to complete.
- """
- service = self._GetReportService()
- report_job_id = service.runReportJob(report_job)['id']
- status = service.getReportJob(report_job_id)['reportJobStatus']
- while status != 'COMPLETED' and status != 'FAILED':
- logging.debug('Report job status: %s', status)
- time.sleep(30)
- status = service.getReportJob(report_job_id)['reportJobStatus']
-
- if status == 'FAILED':
- raise googleads.errors.DfpReportError(report_job_id)
- else:
- logging.debug('Report has completed successfully')
- return report_job_id
-
- def DownloadReportToFile(self, report_job_id, export_format, outfile):
- """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 write to.
- """
- service = self._GetReportService()
- report_url = service.getReportDownloadURL(report_job_id, export_format)
- response = urllib2.urlopen(report_url)
- while True:
- chunk = response.read(_CHUNK_SIZE)
- if not chunk: break
- outfile.write(chunk)
-
- 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: list dict of bind values to use with the pql_query.
-
- Returns:
- a list of lists with the first being the header row and each subsequent
- list being a row of results.
- """
- results = []
- self._PageThroughPqlSet(pql_query, results.append, values)
- return results
-
- 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.
- [optional]
- values: list dict of bind values to use with the pql_query.
- """
- pql_writer = csv.writer(file_handle, delimiter=',',
- quotechar='"', quoting=csv.QUOTE_ALL)
- self._PageThroughPqlSet(pql_query, pql_writer.writerow, values)
-
- 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.
- """
- if 'value' in pql_value:
- field = pql_value['value']
- elif 'values' in pql_value:
- field = pql_value['values']
- else:
- field = None
-
- if field:
- if isinstance(field, list):
- if all(DfpClassType(single_field) == DfpClassType(field[0])
- for single_field in field):
- return ','.join([
- '"%s"' % str(self._ConvertValueForCsv(single_field))
- for single_field in field])
- else:
- raise googleads.errors.GoogleAdsValueError(
- 'The set value returned contains unsupported mix value types')
-
- class_type = DfpClassType(pql_value)
-
- if class_type == 'TextValue':
- return field.replace('"', '""').encode('UTF8')
- elif class_type == 'NumberValue':
- return float(field) if '.' in field else int(field)
- elif class_type == 'DateTimeValue':
- return self._ConvertDateTimeToOffset(field)
- elif class_type == 'DateValue':
- return datetime.date(int(field['date']['year']),
- int(field['date']['month']),
- int(field['date']['day'])).isoformat()
- else:
- return field
- else:
- return '-'
-
- 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 output the results (csv or in
- memory)
- values: list dict of bind values to use with the pql_query.
- """
- result_set_size = 0
- pql_service = self._GetPqlService()
- filter_statement = FilterStatement(pql_query, values, SUGGESTED_PAGE_LIMIT)
-
- while True:
- response = pql_service.select(filter_statement.ToStatement())
-
- if 'rows' in response:
- # Write the header row only on first pull
- if filter_statement.offset == 0:
- header = response['columnTypes']
- output_function([label['labelName'] for label in header])
-
- entities = response['rows']
- result_set_size = len(entities)
-
- for entity in entities:
- output_function([self._ConvertValueForCsv(value) for value
- in entity['values']])
-
- filter_statement.offset += result_set_size
- if result_set_size != SUGGESTED_PAGE_LIMIT:
- break
- else:
- break
-
- 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 of the date time value uniform to
- ReportService.
- """
- date_time_obj = datetime.datetime(int(date_time_value['date']['year']),
- int(date_time_value['date']['month']),
- int(date_time_value['date']['day']),
- int(date_time_value['hour']),
- int(date_time_value['minute']),
- int(date_time_value['second']))
- date_time_str = pytz.timezone(
- date_time_value['timeZoneID']).localize(date_time_obj).isoformat()
-
- if date_time_str[-5:] == '00:00':
- return date_time_str[:-6] + 'Z'
- else:
- return date_time_str
-
-
-def DfpClassType(value):
- """Returns the class type for the Suds object.
-
- Args:
- value: generic Suds object to return type for.
-
- Returns:
- str: A string representation of the value response type.
- """
- return value.__class__.__name__
diff --git a/googleads/errors.py b/googleads/errors.py
index 4243cb83..b6770ce1 100644
--- a/googleads/errors.py
+++ b/googleads/errors.py
@@ -14,8 +14,6 @@
"""Errors used by the Google Ads Client Library."""
-__author__ = 'Joseph DiLallo'
-
class GoogleAdsError(Exception):
"""Parent class of all errors raised by this library."""
@@ -27,6 +25,20 @@ class GoogleAdsValueError(GoogleAdsError):
pass
+class GoogleAdsSoapTransportError(GoogleAdsError):
+ pass
+
+
+class GoogleAdsServerFault(GoogleAdsError):
+
+ def __init__(self, document, errors=(), message=None):
+ super(GoogleAdsServerFault, self).__init__(
+ message if message else 'Server Error')
+
+ self.errors = errors
+ self.document = document
+
+
class AdWordsReportError(GoogleAdsError):
"""Error indicating that an AdWords report download request failed.
@@ -91,20 +103,25 @@ def __init__(self, type_, trigger, field_path, code, error, content):
self.field_path = field_path
-class DfpReportError(GoogleAdsError):
- """Error indicating that a DFP report download request failed.
+class AdWordsBatchJobServiceInvalidOperationError(GoogleAdsError):
+ """Error indicating that an upload operation is malformed."""
+ pass
+
+
+class AdManagerReportError(GoogleAdsError):
+ """Error indicating that an Ad Manager report download request failed.
Attributes:
report_job_id: The ID of the report job which failed.
"""
def __init__(self, report_job_id):
- """Initializes a DfpReportError.
+ """Initializes a AdManagerReportError.
Args:
report_job_id: The ID of the report job which failed.
"""
- super(DfpReportError, self).__init__(
- 'DFP report job failed. The ID of the failed report is: %s'
+ super(AdManagerReportError, self).__init__(
+ 'Ad Manager report job failed. The ID of the failed report is: %s'
% report_job_id)
self.report_job_id = report_job_id
diff --git a/googleads/oauth2.py b/googleads/oauth2.py
index b5f6b0f3..9d40391b 100644
--- a/googleads/oauth2.py
+++ b/googleads/oauth2.py
@@ -11,30 +11,30 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
-
-"""OAuth 2.0 integration for the googleads library.
+"""OAuth2 integration for the googleads library.
This module provides a basic interface which the googleads library uses to
-authorize API requests and some simple implementations built on oauth2client. If
-our OAuth 2.0 workflows doesn't meet your requirements, you can implement this
+authorize API requests and some simple implementations built on
+oauth2client.
+
+If our OAuth2 workflows doesn't meet your requirements, you can implement this
interface in your own way. For example, you could pull credentials from a shared
server and/or centralize refreshing credentials to prevent every Python process
from independently refreshing the credentials.
"""
-__author__ = 'Mark Saniscalchi'
-import datetime
+import googleads.errors
+import requests
+import google.auth.transport.requests
+import google.oauth2.credentials
+import google.oauth2.service_account
-import googleads.errors
-import httplib2
-import oauth2client.client
# The scopes used for authorizing with the APIs supported by this library.
SCOPES = {'adwords': 'https://www.googleapis.com/auth/adwords',
- 'dfa': 'https://www.googleapis.com/auth/dfatrafficking',
- 'dfp': 'https://www.googleapis.com/auth/dfp'}
+ 'ad_manager': 'https://www.googleapis.com/auth/dfp'}
def GetAPIScope(api_name):
@@ -48,126 +48,209 @@ def GetAPIScope(api_name):
A string that is the scope for the given API name.
Raises:
- GoogleAdsValueError: If the given api_name is invalid; accepted valus are
- "adwords", "dfa", and "dfp".
+ GoogleAdsValueError: If the given api_name is invalid; accepted values are
+ "adwords" and "ad_manager".
"""
try:
return SCOPES[api_name]
except KeyError:
raise googleads.errors.GoogleAdsValueError(
- 'Invalid API name "%s" provided. Acceptable values are: %s'
- % (api_name, SCOPES.keys()))
+ 'Invalid API name "%s" provided. Acceptable values are: %s' %
+ (api_name, SCOPES.keys()))
class GoogleOAuth2Client(object):
- """An OAuth 2.0 client for use with Google APIs.
-
- This interface assumes all responsibilty for refreshing credentials when
- necessary.
- """
+ """An OAuth2 client for use with Google APIs."""
+ # The web address for generating OAuth2 credentials at Google.
+ _GOOGLE_OAUTH2_ENDPOINT = 'https://accounts.google.com/o/oauth2/token'
+ # The placeholder URL is used when adding the access token to our request. A
+ # well-formed URL is required, but since we're using HTTP header placement for
+ # the token, this URL is completely unused.
+ _TOKEN_URL = 'https://www.google.com'
+ _USER_AGENT = 'Google Ads Python Client Library'
def CreateHttpHeader(self):
- """Creates an OAuth 2.0 HTTP header.
+ """Creates an OAuth2 HTTP header.
- The OAuth 2.0 credentials will be refreshed as necessary.
+ The OAuth2 credentials will be refreshed as necessary.
Returns:
- A dictionary containing one entry: the OAuth 2.0 Bearer header under the
+ A dictionary containing one entry: the OAuth2 Bearer header under the
'Authorization' key.
"""
raise NotImplementedError('You must subclass GoogleOAuth2Client.')
+
+class GoogleRefreshableOAuth2Client(GoogleOAuth2Client):
+ """A refreshable OAuth2 client for use with Google APIs.
+
+ This interface assumes all responsibility for refreshing credentials when
+ necessary.
+ """
+
def Refresh(self):
"""Refreshes the access token used by the client."""
- raise NotImplementedError('You must subclass GoogleOAuth2Client.')
+ raise NotImplementedError(
+ 'You must subclass GoogleRefreshableOAuth2Client.')
-class GoogleRefreshTokenClient(GoogleOAuth2Client):
- """A simple client for using OAuth 2.0 for Google APIs with a refresh token.
+class GoogleAccessTokenClient(GoogleOAuth2Client):
+ """A simple client for using OAuth2 for Google APIs with an access token.
+
+ This class is not capable of supporting any flows other than taking an
+ existing, active access token. It does not matter which of Google's OAuth2
+ flows you used to generate the access token (installed application, web flow,
+ etc.).
+
+ When the provided access token expires, a GoogleAdsError will be raised.
+ """
+
+ def __init__(self, access_token, token_expiry):
+ """Initializes a GoogleAccessTokenClient.
+
+ Args:
+ access_token: A string containing your access token.
+ token_expiry: A datetime instance indicating when the given access token
+ expires.
+ """
+ self.creds = google.oauth2.credentials.Credentials(
+ token=access_token)
+ self.creds.expiry = token_expiry
+
+ def CreateHttpHeader(self):
+ """Creates an OAuth2 HTTP header.
+
+ The OAuth2 credentials will be refreshed as necessary. In the event that
+ the credentials fail to refresh, a message is logged but no exception is
+ raised.
+
+ Returns:
+ A dictionary containing one entry: the OAuth2 Bearer header under the
+ 'Authorization' key.
+
+ Raises:
+ GoogleAdsError: If the access token has expired.
+ """
+ oauth2_header = {}
+
+ if self.creds.expired:
+ raise googleads.errors.GoogleAdsError('Access token has expired.')
+
+ self.creds.apply(oauth2_header)
+ return oauth2_header
+
+
+class GoogleRefreshTokenClient(GoogleRefreshableOAuth2Client):
+ """A simple client for using OAuth2 for Google APIs with a refresh token.
This class is not capable of supporting any flows other than taking an
existing, active refresh token and generating credentials from it. It does not
- matter which of Google's OAuth 2.0 flows you used to generate the refresh
+ matter which of Google's OAuth2 flows you used to generate the refresh
token (installed application, web flow, etc.).
Attributes:
proxy_info: A ProxyInfo instance used for refresh requests.
"""
- # The web address for generating OAuth 2.0 credentials at Google.
- _GOOGLE_OAUTH2_ENDPOINT = 'https://accounts.google.com/o/oauth2/token'
- # We will refresh an OAuth 2.0 credential _OAUTH2_REFRESH_MINUTES_IN_ADVANCE
- # minutes in advance of its expiration.
- _OAUTH2_REFRESH_MINUTES_IN_ADVANCE = 5
- # The placeholder URL is used when adding the access token to our request. A
- # well-formed URL is required, but since we're using HTTP header placement for
- # the token, this URL is completely unused.
- _TOKEN_URL = 'https://www.google.com'
- _USER_AGENT = 'Google Ads Python Client Library'
- def __init__(self, client_id, client_secret, refresh_token, proxy_info=None,
- disable_ssl_certificate_validation=False, ca_certs=None):
+ def __init__(self, client_id, client_secret, refresh_token, **kwargs):
"""Initializes a GoogleRefreshTokenClient.
Args:
client_id: A string containing your client ID.
client_secret: A string containing your client secret.
refresh_token: A string containing your refresh token.
- [optional]
- proxy_info: A ProxyInfo instance identifying the proxy used for all
- requests.
- disable_ssl_certificate_validation: A boolean indicating whether ssl
- certificate validation should be disabled while using a proxy.
- ca_certs: A string identifying the path to a file containing root CA
- certificates for SSL server certificate validation.
+ **kwargs: Keyword arguments.
+
+ Keyword Arguments:
+ access_token: A string containing your access token.
+ token_expiry: A datetime instance indicating when the given access token
+ expires.
+ proxy_config: A googleads.common.ProxyConfig instance or None if a proxy
+ isn't being used.
"""
- self.oauth2credentials = oauth2client.client.OAuth2Credentials(
- None, client_id, client_secret, refresh_token,
- datetime.datetime(1980, 1, 1, 12), self._GOOGLE_OAUTH2_ENDPOINT,
- self._USER_AGENT)
- self.proxy_info = proxy_info
- self.disable_ssl_certificate_validation = disable_ssl_certificate_validation
- self.ca_certs = ca_certs
+ self.creds = google.oauth2.credentials.Credentials(
+ kwargs.get('access_token'), refresh_token=refresh_token,
+ client_id=client_id, client_secret=client_secret,
+ token_uri=self._GOOGLE_OAUTH2_ENDPOINT)
+ self.creds.expiry = kwargs.get('token_expiry')
+ self.proxy_config = kwargs.get('proxy_config',
+ googleads.common.ProxyConfig())
def CreateHttpHeader(self):
- """Creates an OAuth 2.0 HTTP header.
+ """Creates an OAuth2 HTTP header.
- The OAuth 2.0 credentials will be refreshed as necessary. In the event that
+ The OAuth2 credentials will be refreshed as necessary. In the event that
the credentials fail to refresh, a message is logged but no exception is
raised.
Returns:
- A dictionary containing one entry: the OAuth 2.0 Bearer header under the
+ A dictionary containing one entry: the OAuth2 Bearer header under the
'Authorization' key.
Raises:
- AccessTokenRefreshError: If the refresh fails.
+ google.auth.exceptions.RefreshError: If the refresh fails.
"""
oauth2_header = {}
- if(self.oauth2credentials.token_expiry is not None and
- (self.oauth2credentials.token_expiry - datetime.datetime.utcnow() <
- datetime.timedelta(minutes=self._OAUTH2_REFRESH_MINUTES_IN_ADVANCE))):
+ if self.creds.expiry is None or self.creds.expired:
self.Refresh()
- self.oauth2credentials.apply(oauth2_header)
+ self.creds.apply(oauth2_header)
return oauth2_header
def Refresh(self):
"""Uses the Refresh Token to retrieve and set a new Access Token.
Raises:
- AccessTokenRefreshError: If the refresh fails.
+ google.auth.exceptions.RefreshError: If the refresh fails.
"""
- self.oauth2credentials.refresh(
- httplib2.Http(
- proxy_info=self.proxy_info,
- ca_certs=self.ca_certs,
- disable_ssl_certificate_validation=(
- self.disable_ssl_certificate_validation)))
+ with requests.Session() as session:
+ session.proxies = self.proxy_config.proxies
+ session.verify = not self.proxy_config.disable_certificate_validation
+ session.cert = self.proxy_config.cafile
+ self.creds.refresh(
+ google.auth.transport.requests.Request(session=session))
-class GoogleServiceAccountClient(GoogleOAuth2Client):
- """A simple client for using OAuth 2.0 for Google APIs with a service account.
+
+class GoogleCredentialsClient(GoogleRefreshableOAuth2Client):
+ """A simple client for using OAuth2 for Google APIs with a credentials object.
+
+ This class is not capable of supporting any flows other than taking an
+ existing credentials (google.auth.credentials) to generate the refresh
+ and access tokens.
+ """
+
+ def __init__(self, credentials):
+ """Initializes an OAuth2 client using a credentials object.
+
+ Args:
+ credentials: A credentials object implementing google.auth.credentials.
+ """
+ self.creds = credentials
+
+ def CreateHttpHeader(self):
+ """Creates an OAuth2 HTTP header.
+
+ Returns:
+ A dictionary containing one entry: the OAuth2 Bearer header under the
+ 'Authorization' key.
+ """
+ if self.creds.expiry is None or self.creds.expired:
+ self.Refresh()
+
+ oauth2_header = {}
+ self.creds.apply(oauth2_header)
+ return oauth2_header
+
+ def Refresh(self):
+ """Uses the credentials object to retrieve and set a new Access Token."""
+ transport = google.auth.transport.requests.Request()
+ self.creds.refresh(transport)
+
+
+class GoogleServiceAccountClient(GoogleRefreshableOAuth2Client):
+ """A simple client for using OAuth2 for Google APIs with a service account.
This class is not capable of supporting any flows other than generating
credentials from a service account email and key file. This is incompatible
@@ -176,82 +259,69 @@ class GoogleServiceAccountClient(GoogleOAuth2Client):
Attributes:
proxy_info: A ProxyInfo instance used for refresh requests.
"""
- # We will refresh an OAuth 2.0 credential _OAUTH2_REFRESH_MINUTES_IN_ADVANCE
- # minutes in advance of its expiration.
- _OAUTH2_REFRESH_MINUTES_IN_ADVANCE = 5
_USER_AGENT = 'Google Ads Python Client Library'
+ _FILE_NOT_FOUND_TEMPLATE = 'The specified key file (%s) does not exist.'
- def __init__(self, scope, client_email, key_file,
- private_key_password='notasecret', sub=None, proxy_info=None,
- disable_ssl_certificate_validation=False, ca_certs=None):
+ def __init__(self, key_file, scope, sub=None, proxy_config=None):
"""Initializes a GoogleServiceAccountClient.
Args:
+ key_file: A string containing the path to your Service Account
+ JSON key file.
scope: The scope of the API you're authorizing for.
- client_email: A string containing your Service Account's email.
- key_file: A string containing the path to your key file.
[optional]
- private_key_password: A string containing the password for your key file.
sub: A string containing the email address of a user account you want to
impersonate.
- proxy_info: A ProxyInfo instance identifying the proxy used for all
- requests.
- disable_ssl_certificate_validation: A boolean indicating whether ssl
- certificate validation should be disabled while using a proxy.
- ca_certs: A string identifying the path to a file containing root CA
- certificates for SSL server certificate validation.
+ proxy_config: A googleads.common.ProxyConfig instance.
Raises:
+ GoogleAdsError: If an unsupported version of oauth2client is installed.
GoogleAdsValueError: If the given key file does not exist.
"""
try:
- with open(key_file) as f:
- private_key = f.read()
+ self.creds = (
+ google.oauth2.service_account.Credentials.from_service_account_file(
+ key_file, scopes=[scope], subject=sub))
except IOError:
- raise googleads.errors.GoogleAdsValueError('The specified key file (%s)'
- ' does not exist.' % key_file)
-
- self.oauth2credentials = oauth2client.client.SignedJwtAssertionCredentials(
- client_email, private_key, scope, private_key_password,
- self._USER_AGENT, sub=sub)
- self.proxy_info = proxy_info
- self.disable_ssl_certificate_validation = disable_ssl_certificate_validation
- self.ca_certs = ca_certs
+ raise googleads.errors.GoogleAdsValueError(
+ self._FILE_NOT_FOUND_TEMPLATE % key_file)
+
+ self.proxy_config = (proxy_config if proxy_config else
+ googleads.common.ProxyConfig())
self.Refresh()
def CreateHttpHeader(self):
- """Creates an OAuth 2.0 HTTP header.
+ """Creates an OAuth2 HTTP header.
- The OAuth 2.0 credentials will be refreshed as necessary. In the event that
+ The OAuth2 credentials will be refreshed as necessary. In the event that
the credentials fail to refresh, a message is logged but no exception is
raised.
Returns:
- A dictionary containing one entry: the OAuth 2.0 Bearer header under the
+ A dictionary containing one entry: the OAuth2 Bearer header under the
'Authorization' key.
Raises:
- AccessTokenRefreshError: If the refresh fails.
+ google.auth.exceptions.RefreshError: If the refresh fails.
"""
oauth2_header = {}
- if(self.oauth2credentials.token_expiry is not None and
- (self.oauth2credentials.token_expiry - datetime.datetime.utcnow() <
- datetime.timedelta(minutes=self._OAUTH2_REFRESH_MINUTES_IN_ADVANCE))):
+ if self.creds.expiry is None or self.creds.expired:
self.Refresh()
- self.oauth2credentials.apply(oauth2_header)
+ self.creds.apply(oauth2_header)
return oauth2_header
def Refresh(self):
"""Retrieve and set a new Access Token.
Raises:
- AccessTokenRefreshError: If the refresh fails.
+ google.auth.exceptions.RefreshError: If the refresh fails.
"""
- self.oauth2credentials.refresh(
- httplib2.Http(
- proxy_info=self.proxy_info,
- ca_certs=self.ca_certs,
- disable_ssl_certificate_validation=(
- self.disable_ssl_certificate_validation)))
+ with requests.Session() as session:
+ session.proxies = self.proxy_config.proxies
+ session.verify = not self.proxy_config.disable_certificate_validation
+ session.cert = self.proxy_config.cafile
+
+ self.creds.refresh(
+ google.auth.transport.requests.Request(session=session))
diff --git a/googleads/util.py b/googleads/util.py
new file mode 100644
index 00000000..b539c21c
--- /dev/null
+++ b/googleads/util.py
@@ -0,0 +1,181 @@
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Utilities used by the client library."""
+
+import logging
+import re
+import threading
+
+
+from lxml import etree
+import zeep
+
+
+_COMMON_FILTER = None
+LOGGER_FORMAT = '[%(asctime)s - %(name)s - %(levelname)s] %(message)s'
+
+
+def GetGoogleAdsCommonFilter():
+ global _COMMON_FILTER
+ if not _COMMON_FILTER:
+ _COMMON_FILTER = _GoogleAdsCommonFilter()
+ return _COMMON_FILTER
+
+
+class _AbstractDevTokenSOAPFilter(logging.Filter):
+ """Interface for sanitizing logs containing SOAP request/response data."""
+
+ _AUTHORIZATION_HEADER = 'authorization'
+ _DEVELOPER_TOKEN_SUB = re.compile(
+ r'(?<=\<(?:tns|ns0):developerToken\>)'
+ r'.*?'
+ r'(?=\(?:tns|ns0):developerToken\>)')
+ _REDACTED = 'REDACTED'
+
+ def filter(self, record):
+ raise NotImplementedError('You must implement filter().')
+
+
+class _GoogleAdsCommonFilter(_AbstractDevTokenSOAPFilter):
+ """Removes sensitive data from logs generated by googleads.common."""
+
+ def filter(self, record):
+ if record.levelno == logging.INFO and record.args:
+ content = record.args[0].str()
+ content = self._DEVELOPER_TOKEN_SUB.sub(self._REDACTED, content)
+ record.args = (content,)
+ return True
+
+
+_RESPONSE_XML_LOG_LINE = 'Incoming response: \n%s'
+_REQUEST_LOG_LINE = 'Request made: Service: "%s" Method: "%s" URL: "%s"'
+_REQUEST_XML_LOG_LINE = 'Outgoing request: %s\n%s'
+_SOAP_NAMESPACE = 'http://schemas.xmlsoap.org/soap/envelope/'
+_FAULT_XPATH = './/{%s}Fault' % _SOAP_NAMESPACE
+_HEADER_XPATH = './/{%s}Header' % _SOAP_NAMESPACE
+_REMOVE_NS_REGEXP = re.compile(r'^\{.*?\}')
+
+
+class ZeepLogger(zeep.Plugin, _AbstractDevTokenSOAPFilter):
+ """Log zeep request/response data while removing sensitive information."""
+
+ def __init__(self):
+ """Instantiates a new ZeepLogger."""
+ super(_AbstractDevTokenSOAPFilter, self).__init__()
+ self._logger = logging.getLogger('googleads.soap')
+
+ def ingress(self, envelope, http_headers, operation):
+ """Overrides the ingress function for response logging.
+
+ Args:
+ envelope: An Element with the SOAP request data.
+ http_headers: A dict of the current http headers.
+ operation: The SoapOperation instance.
+
+ Returns:
+ A tuple of the envelope and headers.
+ """
+ if self._logger.isEnabledFor(logging.DEBUG):
+ self._logger.debug(_RESPONSE_XML_LOG_LINE,
+ etree.tostring(envelope, pretty_print=True))
+
+ if self._logger.isEnabledFor(logging.WARN):
+ warn_data = {}
+ header = envelope.find(_HEADER_XPATH)
+ fault = envelope.find(_FAULT_XPATH)
+ if fault is not None:
+ warn_data['faultMessage'] = fault.find('faultstring').text
+
+ if header is not None:
+ header_data = {
+ re.sub(_REMOVE_NS_REGEXP, '', child.tag): child.text
+ for child in header[0]}
+ warn_data.update(header_data)
+
+ if 'serviceName' not in warn_data:
+ warn_service_name = operation.binding.wsdl.services.keys()
+ warn_data['serviceName'] = list(warn_service_name)[0]
+
+ if 'methodName' not in warn_data:
+ warn_data['methodName'] = operation.name
+
+ self._logger.warn('Error summary: %s', warn_data)
+
+ return envelope, http_headers
+
+ def egress(self, envelope, http_headers, operation, binding_options):
+ """Overrides the egress function ror request logging.
+
+ 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 envelope and headers.
+ """
+ if self._logger.isEnabledFor(logging.INFO):
+ service_keys = operation.binding.wsdl.services.keys()
+ service_name = list(service_keys)[0]
+ self._logger.info(_REQUEST_LOG_LINE, service_name, operation.name,
+ binding_options['address'])
+
+ if self._logger.isEnabledFor(logging.DEBUG):
+ http_headers_safe = http_headers.copy()
+ if self._AUTHORIZATION_HEADER in http_headers_safe:
+ http_headers_safe[self._AUTHORIZATION_HEADER] = self._REDACTED
+
+ request_string = etree.tostring(envelope, pretty_print=True)
+ safe_request = self._DEVELOPER_TOKEN_SUB.sub(
+ self._REDACTED, request_string.decode('utf-8'))
+ self._logger.debug(
+ _REQUEST_XML_LOG_LINE, http_headers_safe, safe_request)
+
+ return envelope, http_headers
+
+
+class UtilityRegistry(object):
+ """Utility that registers product utilities used in generating a request."""
+
+ def __contains__(self, utility):
+ with self._lock:
+ return utility in self._registry
+
+ def __init__(self):
+ self._enabled = True
+ self._registry = set()
+ self._lock = threading.Lock()
+
+ def __iter__(self):
+ with self._lock:
+ return iter(self._registry.copy())
+
+ def __len__(self):
+ with self._lock:
+ return len(self._registry)
+
+ def Add(self, obj):
+ with self._lock:
+ if self._enabled:
+ self._registry.add(obj)
+
+ def Clear(self):
+ with self._lock:
+ self._registry.clear()
+
+ def SetEnabled(self, value):
+ with self._lock:
+ self._enabled = value
diff --git a/setup.py b/setup.py
index 2d453a1d..ddccd6a8 100755
--- a/setup.py
+++ b/setup.py
@@ -1,4 +1,4 @@
-#!/usr/bin/python
+#!/usr/bin/env python
#
# Copyright 2013 Google Inc. All Rights Reserved.
#
@@ -16,7 +16,6 @@
"""Setup script for the Google Ads Python Client Library."""
-__author__ = 'Joseph Dilallo'
import os
import re
@@ -25,8 +24,19 @@
PACKAGES = ['googleads']
-DEPENDENCIES = ['httplib2', 'oauth2client', 'suds-jurko', 'pysocks', 'pytz',
- 'PyYAML']
+DEPENDENCIES = ['google-auth>=1.0.0,<2.0.0',
+ 'google-auth-oauthlib>=0.0.1,<1.0.0', 'pytz>=2015.7',
+ 'PyYAML>=5.1, <6.0', 'requests>=2.0.0,<3.0.0',
+ 'xmltodict>=0.9.2,<1.0.0', 'zeep>=2.5.0']
+
+# Note: Breaking change introduced in pyfakefs 3.3.
+TEST_DEPENDENCIES = ['mock>=2.0.0,<3.0.0', 'pyfakefs>=3.2,<3.3']
+
+CLASSIFIERS = [
+ 'Intended Audience :: Developers',
+ 'License :: OSI Approved :: Apache Software License',
+ 'Programming Language :: Python :: 3.7'
+]
def GetVersion():
@@ -51,12 +61,16 @@ def GetVersion():
The googleads Python Client Libraries support the following products:
* AdWords API
-* DoubleClick for Advertisers API
-* DoubleClick for Publishers API
+* Google Ad Manager API
You can find more information about the Google Ads Python Client Libraries
`here `_.
+Supported Python Versions
+=========================
+
+This library is supported for Python 3.7+.
+
Installation
============
@@ -85,20 +99,18 @@ def GetVersion():
`issue tracker `_.
"""
-extra_params = {}
-if sys.version_info[0] == 3:
- extra_params['use_2to3'] = True
-
setup(name='googleads',
version=GetVersion(),
description='Google Ads Python Client Library',
- author='Joseph DiLallo',
- author_email='jdilallo@google.com',
+ author='Mark Saniscalchi',
+ author_email='api.msaniscalchi@gmail.com',
url='https://github.com/googleads/googleads-python-lib',
license='Apache License 2.0',
long_description=long_description,
packages=PACKAGES,
platforms='any',
- keywords='adwords adxbuyer dfp dfa google',
+ keywords='adwords dfp admanager google',
+ classifiers=CLASSIFIERS,
install_requires=DEPENDENCIES,
- **extra_params)
+ tests_require=TEST_DEPENDENCIES,
+ test_suite='tests')
diff --git a/examples/adwords/v201406/__init__.py b/tests/__init__.py
similarity index 100%
rename from examples/adwords/v201406/__init__.py
rename to tests/__init__.py
diff --git a/tests/ad_manager_test.py b/tests/ad_manager_test.py
new file mode 100644
index 00000000..44e31f1c
--- /dev/null
+++ b/tests/ad_manager_test.py
@@ -0,0 +1,1012 @@
+# Copyright 2013 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Unit tests to cover the ad_manager module."""
+
+
+import datetime
+import unittest
+
+import mock
+import pytz
+import io
+import googleads.ad_manager
+import googleads.common
+import googleads.errors
+from . import testing
+
+
+CURRENT_VERSION = sorted(googleads.ad_manager._SERVICE_MAP.keys())[-1]
+
+
+class BaseValue(object):
+
+ def __init__(self, original_object):
+ self.original_object = original_object
+
+ def __getitem__(self, key):
+ return self.original_object[key]
+
+ def __contains__(self, key):
+ if key in self.original_object:
+ return True
+ return False
+
+
+class TextValue(BaseValue):
+
+ def __init__(self, original_object):
+ BaseValue.__init__(self, original_object)
+
+
+class NumberValue(BaseValue):
+
+ def __init__(self, original_object):
+ BaseValue.__init__(self, original_object)
+
+
+class DateValue(BaseValue):
+
+ def __init__(self, original_object):
+ BaseValue.__init__(self, original_object)
+
+
+class DateTimeValue(BaseValue):
+
+ def __init__(self, original_object):
+ BaseValue.__init__(self, original_object)
+
+
+class BooleanValue(BaseValue):
+
+ def __init__(self, original_object):
+ BaseValue.__init__(self, original_object)
+
+
+class SetValue(object):
+
+ def __init__(self, original_object):
+ packed_objects = [DecideValue(obj_to_pack) for obj_to_pack
+ in original_object['values']]
+ self.original_object = {'values': packed_objects}
+
+ def __getitem__(self, key):
+ return self.original_object[key]
+
+ def __contains__(self, key):
+ if key in self.original_object:
+ return True
+ return False
+
+
+def DecideValue(original_object):
+ class_type = original_object['xsi_type']
+ if class_type == 'TextValue':
+ return TextValue(original_object)
+ elif class_type == 'NumberValue':
+ return NumberValue(original_object)
+ elif class_type == 'DateValue':
+ return DateValue(original_object)
+ elif class_type == 'DateTimeValue':
+ return DateTimeValue(original_object)
+ elif class_type == 'SetValue':
+ return SetValue(original_object)
+ else:
+ return BooleanValue(original_object)
+
+
+class AdManagerHeaderHandlerTest(testing.CleanUtilityRegistryTestCase):
+ """Tests for the googleads.ad_manager._AdManagerHeaderHandler class."""
+
+ def setUp(self):
+ self.ad_manager_client = mock.Mock()
+ self.enable_compression = False
+ self.custom_headers = ()
+ self.header_handler = googleads.ad_manager._AdManagerHeaderHandler(
+ self.ad_manager_client, self.enable_compression, self.custom_headers)
+ self.utility_name = 'TestUtility'
+ self.default_sig_template = ' (%s, %s, %s)'
+ self.util_sig_template = ' (%s, %s, %s, %s)'
+ self.network_code = 'my network code is code'
+ self.app_name = 'application name'
+ self.oauth_header = {'oauth': 'header'}
+
+ @googleads.common.RegisterUtility(self.utility_name)
+ class TestUtility(object):
+
+ def Test(self):
+ pass
+
+ self.test_utility = TestUtility()
+
+ def testGetHTTPHeaders(self):
+ self.ad_manager_client.oauth2_client.CreateHttpHeader.return_value = (
+ self.oauth_header)
+
+ header_result = self.header_handler.GetHTTPHeaders()
+
+ # Check that the returned headers have the correct values.
+ self.assertEqual(header_result, self.oauth_header)
+
+ def testGetHTTPHeadersWithCustomHeaders(self):
+ self.ad_manager_client.oauth2_client.CreateHttpHeader.return_value = (
+ self.oauth_header)
+ self.header_handler.custom_http_headers = {'X-My-Header': 'abc'}
+
+ header_result = self.header_handler.GetHTTPHeaders()
+
+ # Check that the returned headers have the correct values.
+ self.assertEqual(header_result, {'oauth': 'header', 'X-My-Header': 'abc'})
+
+ def testGetSOAPHeaders(self):
+ create_method = mock.Mock()
+ self.ad_manager_client.network_code = self.network_code
+ self.ad_manager_client.application_name = self.app_name
+
+ header_result = self.header_handler.GetSOAPHeaders(create_method)
+
+ # Check that the SOAP header has the correct values.
+ create_method.assert_called_once_with('ns0:SoapRequestHeader')
+ self.assertEqual(self.network_code, header_result.networkCode)
+ self.assertEqual(
+ ''.join([
+ self.app_name,
+ googleads.common.GenerateLibSig(
+ googleads.ad_manager._AdManagerHeaderHandler._PRODUCT_SIG)]),
+ header_result.applicationName)
+
+ def testGetSOAPHeadersUserAgentWithUtility(self):
+ create_method = mock.Mock()
+ self.ad_manager_client.network_code = self.network_code
+ self.ad_manager_client.application_name = self.app_name
+
+ with mock.patch('googleads.common._COMMON_LIB_SIG') as mock_common_sig:
+ with mock.patch('googleads.common._PYTHON_VERSION') as mock_py_ver:
+ self.test_utility.Test() # This will register TestUtility.
+ soap_header = self.header_handler.GetSOAPHeaders(create_method)
+ self.assertEqual(
+ ''.join([
+ self.app_name,
+ self.util_sig_template % (
+ googleads.ad_manager._AdManagerHeaderHandler._PRODUCT_SIG,
+ mock_common_sig,
+ mock_py_ver,
+ self.utility_name)]),
+ soap_header.applicationName)
+
+ def testGetHeadersUserAgentWithAndWithoutUtility(self):
+ create_method = mock.Mock()
+
+ self.ad_manager_client.network_code = self.network_code
+ self.ad_manager_client.application_name = self.app_name
+
+ with mock.patch('googleads.common._COMMON_LIB_SIG') as mock_common_sig:
+ with mock.patch('googleads.common._PYTHON_VERSION') as mock_py_ver:
+ # Check headers when utility registered.
+ self.test_utility.Test() # This will register TestUtility.
+ soap_header = self.header_handler.GetSOAPHeaders(create_method)
+ self.assertEqual(
+ ''.join([
+ self.app_name,
+ self.util_sig_template % (
+ googleads.ad_manager._AdManagerHeaderHandler._PRODUCT_SIG,
+ mock_common_sig,
+ mock_py_ver,
+ self.utility_name)]),
+ soap_header.applicationName)
+
+ # Check headers when no utility should be registered.
+ soap_header = self.header_handler.GetSOAPHeaders(create_method)
+ self.assertEqual(
+ ''.join([
+ self.app_name,
+ self.default_sig_template % (
+ googleads.ad_manager._AdManagerHeaderHandler._PRODUCT_SIG,
+ mock_common_sig,
+ mock_py_ver)]),
+ soap_header.applicationName)
+
+ # Verify that utility is registered in subsequent uses.
+ self.test_utility.Test() # This will register TestUtility.
+ soap_header = self.header_handler.GetSOAPHeaders(create_method)
+ self.assertEqual(
+ ''.join([
+ self.app_name,
+ self.util_sig_template % (
+ googleads.ad_manager._AdManagerHeaderHandler._PRODUCT_SIG,
+ mock_common_sig,
+ mock_py_ver,
+ self.utility_name)]),
+ soap_header.applicationName)
+
+
+class AdManagerClientTest(unittest.TestCase):
+ """Tests for the googleads.ad_manager.AdManagerClient class."""
+
+ def setUp(self):
+ self.network_code = '12345'
+ self.application_name = 'application name'
+ self.oauth2_client = mock.Mock()
+ self.oauth2_client.CreateHttpHeader.return_value = {}
+ self.proxy_host = 'myproxy'
+ self.proxy_port = 443
+ self.https_proxy = 'http://myproxy:443'
+ self.proxy_config = googleads.common.ProxyConfig(
+ https_proxy=self.https_proxy)
+ self.cache = None
+ self.version = sorted(googleads.ad_manager._SERVICE_MAP.keys())[-1]
+
+ def CreateAdManagerClient(self, **kwargs):
+ if 'proxy_config' not in kwargs:
+ kwargs['proxy_config'] = self.proxy_config
+
+ if 'cache' not in kwargs:
+ kwargs['cache'] = self.cache
+
+ return googleads.ad_manager.AdManagerClient(
+ self.oauth2_client, self.application_name, self.network_code,
+ **kwargs)
+
+ def testLoadFromString(self):
+ with mock.patch('googleads.common.LoadFromString') as mock_load:
+ mock_load.return_value = {
+ 'network_code': 'abcdEFghIjkLMOpqRs',
+ 'oauth2_client': True,
+ 'application_name': 'unit testing'
+ }
+ self.assertIsInstance(
+ googleads.ad_manager.AdManagerClient.LoadFromString(''),
+ googleads.ad_manager.AdManagerClient)
+
+ def testLoadFromStorage(self):
+ with mock.patch('googleads.common.LoadFromStorage') as mock_load:
+ mock_load.return_value = {
+ 'network_code': 'abcdEFghIjkLMOpqRs',
+ 'oauth2_client': True,
+ 'application_name': 'unit testing'
+ }
+ self.assertIsInstance(
+ googleads.ad_manager.AdManagerClient.LoadFromStorage(),
+ googleads.ad_manager.AdManagerClient)
+
+ def testLoadFromStorageWithCompressionEnabled(self):
+ enable_compression = True
+ application_name_gzip_template = '%s (gzip)'
+ default_app_name = 'unit testing'
+ custom_headers = {'X-My-Header': 'abc'}
+
+ with mock.patch('googleads.common.LoadFromStorage') as mock_load:
+ with mock.patch('googleads.ad_manager._AdManagerHeaderHandler') as mock_h:
+ mock_load.return_value = {
+ 'network_code': 'abcdEFghIjkLMOpqRs',
+ 'oauth2_client': True,
+ 'application_name': default_app_name,
+ 'enable_compression': enable_compression,
+ 'custom_http_headers': custom_headers
+ }
+ ad_manager = googleads.ad_manager.AdManagerClient.LoadFromStorage()
+ self.assertEqual(
+ application_name_gzip_template % default_app_name,
+ ad_manager.application_name)
+ mock_h.assert_called_once_with(
+ ad_manager, enable_compression, custom_headers)
+
+ def testInitializeWithDefaultApplicationName(self):
+ self.application_name = 'INSERT_APPLICATION_NAME_HERE'
+ self.assertRaises(
+ googleads.errors.GoogleAdsValueError,
+ googleads.ad_manager.AdManagerClient, self.oauth2_client,
+ self.application_name, self.network_code, self.https_proxy, self.cache)
+
+ def testInitializeWithUselessApplicationName(self):
+ self.application_name = 'try_to_trick_me_INSERT_APPLICATION_NAME_HERE'
+ self.assertRaises(
+ googleads.errors.GoogleAdsValueError,
+ googleads.ad_manager.AdManagerClient, self.oauth2_client,
+ self.application_name, self.network_code, self.https_proxy, self.cache)
+
+ def testGetService_success(self):
+ ad_manager = self.CreateAdManagerClient(
+ cache='cache', proxy_config='proxy', timeout='timeout')
+ service_name = googleads.ad_manager._SERVICE_MAP[self.version][0]
+
+ # Use a custom server. Also test what happens if the server ends with a
+ # trailing slash
+ server = 'https://testing.test.com/'
+ with mock.patch('googleads.common.'
+ 'GetServiceClassForLibrary') as mock_get_service:
+ impl = mock.Mock()
+ mock_service = mock.Mock()
+ impl.return_value = mock_service
+ mock_get_service.return_value = impl
+
+ service = ad_manager.GetService(service_name, self.version, server)
+
+ impl.assert_called_once_with(
+ 'https://testing.test.com/apis/ads/publisher/%s/%s?wsdl'
+ % (self.version, service_name), ad_manager._header_handler,
+ googleads.ad_manager._AdManagerPacker, 'proxy', 'timeout',
+ self.version, cache='cache')
+ self.assertEqual(service, mock_service)
+
+
+ def testGetService_badService(self):
+ ad_manager = self.CreateAdManagerClient()
+ with mock.patch('googleads.common.'
+ 'GetServiceClassForLibrary') as mock_get_service:
+ mock_get_service.side_effect = (
+ googleads.errors.GoogleAdsSoapTransportError('', ''))
+ self.assertRaises(
+ googleads.errors.GoogleAdsValueError, ad_manager.GetService,
+ 'GYIVyievfyiovslf', self.version)
+
+ def testGetService_badVersion(self):
+ ad_manager = self.CreateAdManagerClient()
+ with mock.patch('googleads.common.'
+ 'GetServiceClassForLibrary') as mock_get_service:
+ mock_get_service.side_effect = (
+ googleads.errors.GoogleAdsSoapTransportError('', ''))
+ self.assertRaises(
+ googleads.errors.GoogleAdsValueError, ad_manager.GetService,
+ 'CampaignService', '11111')
+
+ def testGetService_transportError(self):
+ service = googleads.ad_manager._SERVICE_MAP[self.version][0]
+ ad_manager = self.CreateAdManagerClient()
+ with mock.patch('googleads.common.'
+ 'GetServiceClassForLibrary') as mock_get_service:
+ mock_get_service.side_effect = (
+ googleads.errors.GoogleAdsSoapTransportError('', ''))
+ self.assertRaises(googleads.errors.GoogleAdsSoapTransportError,
+ ad_manager.GetService, service, self.version)
+
+
+class AdManagerPackerTest(unittest.TestCase):
+ """Tests for the googleads.ad_manager._AdManagerPacker class."""
+
+ def setUp(self):
+ self.packer = googleads.ad_manager._AdManagerPacker
+
+ def testPackDate(self):
+ input_date = datetime.date(2017, 1, 2)
+ result = self.packer.Pack(input_date, CURRENT_VERSION)
+ self.assertEqual(result, {'year': 2017, 'month': 1, 'day': 2})
+
+ def testPackDateTime(self):
+ input_date = datetime.datetime(2017, 1, 2, 3, 4, 5)
+ input_date = pytz.timezone('America/New_York').localize(input_date)
+ result = self.packer.Pack(input_date, CURRENT_VERSION)
+ self.assertEqual(result, {'date': {'year': 2017, 'month': 1, 'day': 2},
+ 'hour': 3, 'minute': 4, 'second': 5,
+ 'timeZoneId': 'America/New_York'})
+
+ def testPackDateTimeNeedsTimeZone(self):
+ input_date = datetime.datetime(2017, 1, 2, 3, 4, 5)
+ self.assertRaises(googleads.errors.GoogleAdsValueError,
+ self.packer.Pack, input_date, CURRENT_VERSION)
+
+ def testPackUnsupportedObjectType(self):
+ obj = object()
+ self.assertEqual(googleads.ad_manager._AdManagerPacker.
+ Pack(obj, CURRENT_VERSION), obj)
+
+
+class DataDownloaderTest(unittest.TestCase):
+ """Tests for the googleads.ad_manager.AdManagerClient class."""
+
+ def setUp(self):
+ network_code = '12345'
+ application_name = 'application name'
+ oauth2_client = 'unused'
+ self.https_proxy = 'myproxy.com:443'
+ self.ad_manager = googleads.ad_manager.AdManagerClient(
+ oauth2_client, application_name, network_code, self.https_proxy)
+ self.version = sorted(googleads.ad_manager._SERVICE_MAP.keys())[-1]
+ self.report_downloader = self.ad_manager.GetDataDownloader()
+ self.pql_service = mock.Mock()
+ self.report_service = mock.Mock()
+ self.report_downloader._pql_service = self.pql_service
+ self.report_downloader._report_service = self.report_service
+ self.generic_header = [{'labelName': 'Some random header...'},
+ {'labelName': 'Another header...'}]
+
+ row1_field1 = {
+ 'value': 'Some random PQL response...',
+ 'xsi_type': 'TextValue'
+ }
+
+ row1_field2 = {
+ 'value': {
+ 'year': '1999', 'month': '04', 'day': '03'
+ },
+ 'xsi_type': 'DateValue'
+ }
+
+ row1_field3 = {
+ 'value': '123',
+ 'xsi_type': 'NumberValue'
+ }
+
+ row1_field4 = {
+ 'value': {
+ 'date': {
+ 'year': '2012',
+ 'month': '11',
+ 'day': '05'
+ },
+ 'hour': '12',
+ 'minute': '12',
+ 'second': '12',
+ 'timeZoneId': 'PST8PDT'},
+ 'xsi_type': 'DateTimeValue'
+ }
+
+ row1_field5 = {
+ 'value': None,
+ 'xsi_type': 'NumberValue'
+ }
+
+ row1_field6 = {
+ 'values': [{
+ 'value': 'Whatcha thinkin about?',
+ 'xsi_type': 'TextValue'
+ }, {
+ 'value': 'Oh nothing, just String stuff...',
+ 'xsi_type': 'TextValue'
+ }],
+ 'xsi_type': 'SetValue'
+ }
+
+ row2_field1 = {
+ 'value': 'A second row of PQL response!',
+ 'xsi_type': 'TextValue'
+ }
+
+ row2_field2 = {
+ 'value': {
+ 'year': '2009',
+ 'month': '02',
+ 'day': '05'
+ },
+ 'xsi_type': 'DateValue'
+ }
+
+ row2_field3 = {
+ 'value': '345',
+ 'xsi_type': 'NumberValue'
+ }
+
+ row2_field4 = {
+ 'value': {
+ 'date': {
+ 'year': '2013',
+ 'month': '01',
+ 'day': '03'
+ },
+ 'hour': '02',
+ 'minute': '02',
+ 'second': '02',
+ 'timeZoneId': 'GMT'
+ },
+ 'xsi_type': 'DateTimeValue'
+ }
+
+ row2_field5 = {
+ 'value': '123456',
+ 'xsi_type': 'NumberValue'
+ }
+
+ row2_field6 = {
+ 'values': [{
+ 'value': 'Look at how many commas and "s there are',
+ 'xsi_type': 'TextValue'
+ }, {
+ 'value': 'this,is...how,Christopher Walken, talks',
+ 'xsi_type': 'TextValue'
+ }],
+ 'xsi_type': 'SetValue'
+ }
+
+ row1 = [row1_field1, row1_field2, row1_field3, row1_field4, row1_field5,
+ row1_field6]
+ row2 = [row2_field1, row2_field2, row2_field3, row2_field4, row2_field5,
+ row2_field6]
+
+ self.generic_rval = [{
+ 'values': [DecideValue(value) for value in row1]
+ }, {
+ 'values': [DecideValue(value) for value in row2]
+ }]
+
+ def testDownloadPqlResultSetToCsv(self):
+ csv_file = io.StringIO()
+
+ self.pql_service.select.return_value = {'rows': self.generic_rval,
+ 'columnTypes': self.generic_header}
+
+ self.report_downloader.DownloadPqlResultToCsv(
+ 'SELECT Id, Name FROM Line_Item', csv_file)
+
+ csv_file.seek(0)
+ self.assertEqual(csv_file.readline(),
+ ('"Some random header...",'
+ '"Another header..."\r\n'))
+ self.assertEqual(csv_file.readline(),
+ ('"Some random PQL response...",'
+ '"1999-04-03",'
+ '"123",'
+ '"2012-11-05T12:12:12-08:00",'
+ '"-","""Whatcha thinkin about?"",""Oh nothing, '
+ 'just String stuff..."""\r\n'))
+ self.assertEqual(csv_file.readline(),
+ ('"A second row of PQL response!",'
+ '"2009-02-05",'
+ '"345",'
+ '"2013-01-03T02:02:02Z",'
+ '"123456","""Look at how many commas and """"s there are'
+ '"",""this,is...how,Christopher Walken, talks"""\r\n'))
+ csv_file.close()
+
+ self.pql_service.select.assert_called_once_with(
+ {'values': None,
+ 'query': ('SELECT Id, Name FROM Line_Item LIMIT 500 OFFSET 0')})
+
+ def testDownloadPqlResultToList(self):
+ self.pql_service.select.return_value = {'rows': self.generic_rval,
+ 'columnTypes': self.generic_header}
+
+ result_set = self.report_downloader.DownloadPqlResultToList(
+ 'SELECT Id, Name FROM Line_Item')
+
+ row1 = [self.report_downloader._ConvertValueForCsv(field)
+ for field in self.generic_rval[0]['values']]
+ row2 = [self.report_downloader._ConvertValueForCsv(field)
+ for field in self.generic_rval[1]['values']]
+
+ self.pql_service.select.assert_called_once_with(
+ {'values': None,
+ 'query': ('SELECT Id, Name FROM Line_Item LIMIT 500 OFFSET 0')})
+ self.assertEqual([[self.generic_header[0]['labelName'],
+ self.generic_header[1]['labelName']],
+ row1, row2], result_set)
+
+ def testDownloadPqlResultToListWithOldValuesList(self):
+ self.pql_service.select.return_value = {'rows': self.generic_rval,
+ 'columnTypes': self.generic_header}
+
+ result_set = self.report_downloader.DownloadPqlResultToList(
+ 'SELECT Id, Name FROM Line_Item WHERE Id = :id',
+ [{'key': 'id', 'value': {'xsi_type': 'NumberValue', 'value': 1}}])
+
+ row1 = [self.report_downloader._ConvertValueForCsv(field)
+ for field in self.generic_rval[0]['values']]
+ row2 = [self.report_downloader._ConvertValueForCsv(field)
+ for field in self.generic_rval[1]['values']]
+
+ self.pql_service.select.assert_called_once_with(
+ {'values': [{'key': 'id',
+ 'value': {'xsi_type': 'NumberValue', 'value': 1}}],
+ 'query': ('SELECT Id, Name FROM Line_Item '
+ 'WHERE Id = :id LIMIT 500 OFFSET 0')})
+ self.assertEqual([[self.generic_header[0]['labelName'],
+ self.generic_header[1]['labelName']],
+ row1, row2], result_set)
+
+ def testDownloadPqlResultToListWithDict(self):
+ self.pql_service.select.return_value = {'rows': self.generic_rval,
+ 'columnTypes': self.generic_header}
+
+ result_set = self.report_downloader.DownloadPqlResultToList(
+ 'SELECT Id, Name FROM Line_Item WHERE Id = :id',
+ {'id': 1})
+
+ row1 = [self.report_downloader._ConvertValueForCsv(field)
+ for field in self.generic_rval[0]['values']]
+ row2 = [self.report_downloader._ConvertValueForCsv(field)
+ for field in self.generic_rval[1]['values']]
+
+ self.pql_service.select.assert_called_once_with(
+ {'values': [{'key': 'id',
+ 'value': {'xsi_type': 'NumberValue', 'value': 1}}],
+ 'query': ('SELECT Id, Name FROM Line_Item '
+ 'WHERE Id = :id LIMIT 500 OFFSET 0')})
+ self.assertEqual([[self.generic_header[0]['labelName'],
+ self.generic_header[1]['labelName']],
+ row1, row2], result_set)
+
+ def testDownloadPqlResultToList_NoRows(self):
+ self.pql_service.select.return_value = {}
+
+ result_set = self.report_downloader.DownloadPqlResultToList(
+ 'SELECT Id, Name FROM Line_Item')
+
+ self.pql_service.select.assert_called_once_with(
+ {'values': None,
+ 'query': ('SELECT Id, Name FROM Line_Item LIMIT 500 OFFSET 0')})
+ self.assertEqual([], result_set)
+
+ def testWaitForReport_success(self):
+ id_ = '1g684'
+ input_ = {'reportQuery': 'something', 'id': id_}
+ self.report_service.getReportJobStatus.side_effect = ['IN_PROGRESS',
+ 'COMPLETED']
+ self.report_service.runReportJob.return_value = input_
+
+ with mock.patch('time.sleep') as mock_sleep:
+ rval = self.report_downloader.WaitForReport(input_)
+ mock_sleep.assert_called_once_with(30)
+ self.assertEqual(id_, rval)
+ self.report_service.getReportJobStatus.assert_any_call(id_)
+
+ def testWaitForReport_failure(self):
+ self.report_service.getReportJobStatus.return_value = 'FAILED'
+ self.report_service.runReportJob.return_value = {'id': '782yt97r2'}
+
+ self.assertRaises(
+ googleads.errors.AdManagerReportError,
+ self.report_downloader.WaitForReport, {'id': 'obj'})
+
+ def testDownloadReportToFile(self):
+ report_format = 'CSV_DUMP'
+ report_job_id = 't68t3278y429'
+ report_download_url = 'http://google.com/something'
+ report_data = 'THIS IS YOUR REPORT!'
+ report_contents = io.StringIO()
+ report_contents.write(report_data)
+ report_contents.seek(0)
+ fake_response = mock.Mock()
+ fake_response.read = report_contents.read
+ fake_response.msg = 'fake message'
+ fake_response.code = '200'
+ outfile = io.StringIO()
+
+ download_func = self.report_service.getReportDownloadUrlWithOptions
+ download_func.return_value = report_download_url
+
+ with mock.patch('urllib.request.OpenerDirector.open') as mock_open:
+ mock_open.return_value = fake_response
+
+ self.report_downloader.DownloadReportToFile(
+ report_job_id, report_format, outfile)
+ default_opts = {
+ 'exportFormat': report_format,
+ 'includeReportProperties': False,
+ 'includeTotalsRow': False,
+ 'useGzipCompression': True,
+ }
+ download_func.assert_called_once_with(report_job_id, default_opts)
+ mock_open.assert_called_once_with(report_download_url)
+ self.assertEqual(report_data, outfile.getvalue())
+
+ def testGetReportService(self):
+ self.report_downloader._ad_manager_client = mock.Mock()
+ self.report_downloader._report_service = None
+
+ self.report_downloader._GetReportService()
+ client = self.report_downloader._ad_manager_client
+ client.GetService.assert_called_once_with(
+ 'ReportService', self.version, 'https://ads.google.com')
+
+ def testGetPqlService(self):
+ self.report_downloader._ad_manager_client = mock.Mock()
+ self.report_downloader._pql_service = None
+
+ self.report_downloader._GetPqlService()
+ client = self.report_downloader._ad_manager_client
+ client.GetService.assert_called_once_with(
+ 'PublisherQueryLanguageService', self.version, 'https://ads.google.com')
+
+ def testDownloadHasCustomHeaders(self):
+ self.ad_manager.custom_http_headers = {'X-My-Headers': 'abc'}
+
+ class MyOpener(object):
+ addheaders = [('a', 'b')]
+ opener = MyOpener()
+
+ with mock.patch('googleads.ad_manager.build_opener') as mock_build_opener:
+ mock_build_opener.return_value = opener
+
+ self.ad_manager.GetDataDownloader()
+ self.assertEqual(opener.addheaders, [('a', 'b'), ('X-My-Headers', 'abc')])
+
+
+class StatementBuilderTest(testing.CleanUtilityRegistryTestCase):
+ """Tests for the StatementBuilder class."""
+
+ def testBuildBasicSelectFrom(self):
+ test_statement = googleads.ad_manager.StatementBuilder()
+ select_call_result = test_statement.Select('Id')
+ from_call_result = test_statement.From('Line_Item')
+
+ self.assertEqual(select_call_result, test_statement)
+ self.assertEqual(from_call_result, test_statement)
+ self.assertEqual(test_statement.ToStatement(),
+ {'query': ('SELECT Id FROM Line_Item LIMIT %s OFFSET 0' %
+ googleads.ad_manager.SUGGESTED_PAGE_LIMIT),
+ 'values': None})
+
+ def testLimitClause(self):
+ test_statement = googleads.ad_manager.StatementBuilder()
+ limit_call_result = (test_statement
+ .Select('Id')
+ .From('Line_Item')
+ .Limit(5))
+
+ self.assertEqual(limit_call_result, test_statement)
+ self.assertEqual(test_statement.ToStatement(),
+ {'query': 'SELECT Id FROM Line_Item LIMIT 5 OFFSET 0',
+ 'values': None})
+
+ limit_call_result.Limit(None)
+ self.assertEqual(test_statement.ToStatement(),
+ {'query': 'SELECT Id FROM Line_Item OFFSET 0',
+ 'values': None})
+
+ def testOffsetClause(self):
+ test_statement = googleads.ad_manager.StatementBuilder()
+ offset_call_result = (
+ test_statement
+ .Select('Id')
+ .From('Line_Item')
+ .Offset(100)
+ )
+
+ self.assertEqual(offset_call_result, test_statement)
+ self.assertEqual(test_statement.ToStatement(),
+ {'query': ('SELECT Id FROM Line_Item LIMIT %s OFFSET 100' %
+ googleads.ad_manager.SUGGESTED_PAGE_LIMIT),
+ 'values': None})
+
+ def testOrderByClause(self):
+ test_statement = googleads.ad_manager.StatementBuilder()
+ order_call_result = (
+ test_statement
+ .Select('Id')
+ .From('Line_Item')
+ .OrderBy('Id')
+ )
+
+ self.assertEqual(order_call_result, test_statement)
+ self.assertEqual(test_statement.ToStatement(),
+ {'query': ('SELECT Id FROM Line_Item '
+ 'ORDER BY Id ASC '
+ 'LIMIT %s OFFSET 0' %
+ googleads.ad_manager.SUGGESTED_PAGE_LIMIT),
+ 'values': None})
+
+ test_statement.OrderBy('Id', ascending=False)
+ self.assertEqual(test_statement.ToStatement(),
+ {'query': ('SELECT Id FROM Line_Item '
+ 'ORDER BY Id DESC '
+ 'LIMIT %s OFFSET 0' %
+ googleads.ad_manager.SUGGESTED_PAGE_LIMIT),
+ 'values': None})
+
+ def testConstructorArgs(self):
+ test_statement = googleads.ad_manager.StatementBuilder(
+ select_columns='Id', from_table='Line_Item', where='abc = 123',
+ order_by='Id', order_ascending=False)
+
+ self.assertEqual(test_statement.ToStatement(),
+ {'query': ('SELECT Id FROM Line_Item '
+ 'WHERE abc = 123 '
+ 'ORDER BY Id DESC '
+ 'LIMIT %s OFFSET 0' %
+ googleads.ad_manager.SUGGESTED_PAGE_LIMIT),
+ 'values': None})
+
+ def testWhereWithStringVariable(self):
+ test_statement = googleads.ad_manager.StatementBuilder()
+ where_call_result = (
+ test_statement
+ .Select('Id')
+ .From('Line_Item')
+ .Where('key = :test_key')
+ )
+ bind_call_result = test_statement.WithBindVariable('test_key', 'test_value')
+
+ target_values = [{
+ 'key': 'test_key',
+ 'value': {
+ 'xsi_type': 'TextValue',
+ 'value': 'test_value'
+ }
+ }]
+ self.assertEqual(where_call_result, test_statement)
+ self.assertEqual(bind_call_result, test_statement)
+ self.assertEqual(
+ test_statement.ToStatement(),
+ {'query': (
+ 'SELECT Id FROM Line_Item '
+ 'WHERE key = :test_key '
+ 'LIMIT %s '
+ 'OFFSET 0' % googleads.ad_manager.SUGGESTED_PAGE_LIMIT),
+ 'values': target_values})
+
+ def testWhereWithOtherTypes(self):
+ test_statement = googleads.ad_manager.StatementBuilder()
+ test_statement.Where((
+ 'bool_key = :test_bool_key '
+ 'AND number_key = :test_number_key '
+ 'AND date_key = :test_date_key '
+ 'AND datetime_key = :test_datetime_key '
+ 'AND set_key = :test_set_key'
+ ))
+
+ test_statement.WithBindVariable('test_bool_key', True)
+ test_statement.WithBindVariable('test_number_key', 5)
+ test_statement.WithBindVariable('test_date_key', datetime.date(2017, 1, 2))
+ test_dt = datetime.datetime(2017, 1, 2,
+ hour=3, minute=4, second=5,
+ )
+ test_dt = pytz.timezone('America/New_York').localize(test_dt)
+ test_statement.WithBindVariable('test_datetime_key', test_dt)
+ test_statement.WithBindVariable('test_set_key', [1, 2])
+
+ target_values = [{
+ 'key': 'test_bool_key',
+ 'value': {
+ 'xsi_type': 'BooleanValue',
+ 'value': True,
+ }
+ }, {
+ 'key': 'test_number_key',
+ 'value': {
+ 'xsi_type': 'NumberValue',
+ 'value': 5,
+ }
+ }, {
+ 'key': 'test_date_key',
+ 'value': {
+ 'xsi_type': 'DateValue',
+ 'value': {
+ 'year': 2017,
+ 'month': 1,
+ 'day': 2,
+ },
+ }
+ }, {
+ 'key': 'test_datetime_key',
+ 'value': {
+ 'xsi_type': 'DateTimeValue',
+ 'value': {
+ 'date': {
+ 'year': 2017,
+ 'month': 1,
+ 'day': 2,
+ },
+ 'hour': 3,
+ 'minute': 4,
+ 'second': 5,
+ 'timeZoneId': 'America/New_York'
+ },
+ }
+ }, {
+ 'key': 'test_set_key',
+ 'value': {
+ 'xsi_type': 'SetValue',
+ 'values': [
+ {'xsi_type': 'NumberValue', 'value': 1},
+ {'xsi_type': 'NumberValue', 'value': 2},
+ ],
+ }
+ }]
+ target_values.sort(key=lambda v: v['key'])
+
+ statement_result = test_statement.ToStatement()
+ self.assertEqual(statement_result['query'],
+ ('WHERE bool_key = :test_bool_key '
+ 'AND number_key = :test_number_key '
+ 'AND date_key = :test_date_key '
+ 'AND datetime_key = :test_datetime_key '
+ 'AND set_key = :test_set_key '
+ 'LIMIT %s '
+ 'OFFSET 0' % googleads.ad_manager.SUGGESTED_PAGE_LIMIT
+ ))
+
+ # The output order doesn't matter, and it's stored internally as a dict
+ # until rendered, which is fine, but we need to lock it down for this test.
+ self.assertEqual(
+ sorted(statement_result['values'], key=lambda v: v['key']),
+ target_values
+ )
+
+ def testBreakWithSetOfMultipleTypes(self):
+ test_statement = googleads.ad_manager.StatementBuilder()
+ test_statement.Where('key = :test_key')
+
+ self.assertRaises(
+ googleads.errors.GoogleAdsValueError,
+ test_statement.WithBindVariable,
+ 'key', [1, 'a']
+ )
+
+ def testMutateVar(self):
+ test_statement = googleads.ad_manager.StatementBuilder()
+ test_statement.Where('key = :test_key')
+ test_statement.WithBindVariable('key', 'abc')
+ test_statement.WithBindVariable('key', '123')
+
+ statement_result = test_statement.ToStatement()
+ self.assertEqual(len(statement_result['values']), 1)
+ self.assertEqual(statement_result['values'][0]['value']['value'], '123')
+
+ def testBreakWithNoTZ(self):
+ test_statement = googleads.ad_manager.StatementBuilder()
+ test_statement.Where('key = :test_key')
+
+ self.assertRaises(
+ googleads.errors.GoogleAdsValueError,
+ test_statement.WithBindVariable,
+ 'key', datetime.datetime.now().replace(tzinfo=None)
+ )
+
+ def testBreakWithUnknownType(self):
+ test_statement = googleads.ad_manager.StatementBuilder()
+ test_statement.Where('key = :test_key')
+
+ class RandomType(object):
+ pass
+
+ self.assertRaises(
+ googleads.errors.GoogleAdsValueError,
+ test_statement.WithBindVariable,
+ 'key', RandomType()
+ )
+
+ def testBreakWithBadSelectFrom(self):
+ test_statement = googleads.ad_manager.StatementBuilder()
+ test_statement.Select('Id')
+
+ self.assertRaises(googleads.errors.GoogleAdsError,
+ test_statement.ToStatement)
+
+ test_statement.Select(None).From('Line_Item')
+
+ self.assertRaises(googleads.errors.GoogleAdsError,
+ test_statement.ToStatement)
+
+
+class FilterStatementTest(testing.CleanUtilityRegistryTestCase):
+ """Tests for the FilterStatement class."""
+
+ def testFilterStatement(self):
+ values = [{
+ 'key': 'test_key',
+ 'value': {
+ 'xsi_type': 'TextValue',
+ 'value': 'test_value'
+ }
+ }]
+ test_statement = googleads.ad_manager.FilterStatement()
+ self.assertEqual(test_statement.ToStatement(),
+ {'query': ' LIMIT 500 OFFSET 0', 'values': None})
+ test_statement.offset += 30
+ self.assertEqual(test_statement.ToStatement(),
+ {'query': ' LIMIT 500 OFFSET 30', 'values': None})
+ test_statement.offset = 123
+ test_statement.limit = 5
+ self.assertEqual(test_statement.ToStatement(),
+ {'query': ' LIMIT 5 OFFSET 123', 'values': None})
+ test_statement = googleads.ad_manager.FilterStatement(
+ 'SELECT Id FROM Line_Item WHERE key = :test_key', limit=300, offset=20,
+ values=values)
+ self.assertEqual(test_statement.ToStatement(),
+ {'query': 'SELECT Id FROM Line_Item WHERE key = '
+ ':test_key LIMIT 300 OFFSET 20',
+ 'values': values})
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tests/adwords_test.py b/tests/adwords_test.py
old mode 100755
new mode 100644
index 8da8e9be..b8a97a67
--- a/tests/adwords_test.py
+++ b/tests/adwords_test.py
@@ -1,4 +1,3 @@
-#!/usr/bin/python
# -*- coding: UTF-8 -*-
#
# Copyright 2013 Google Inc. All Rights Reserved.
@@ -17,159 +16,416 @@
"""Unit tests to cover the adwords module."""
-__author__ = 'Joseph DiLallo'
-
+import datetime
import io
-import sys
+import os
+import re
import tempfile
import unittest
-import urllib
-import urllib2
-
-import mock
+from urllib.error import HTTPError
+from urllib.parse import urlencode
+from urllib.request import urlopen
+from xml.etree import ElementTree
import googleads.adwords
import googleads.common
import googleads.errors
+from . import testing
+import lxml.etree
+import mock
+import yaml
+import zeep.transports
-PYTHON2 = sys.version_info[0] == 2
-URL_REQUEST_PATH = ('urllib2' if PYTHON2 else 'urllib.request')
CURRENT_VERSION = sorted(googleads.adwords._SERVICE_MAP.keys())[-1]
+TEST_DIR = os.path.dirname(__file__)
+
+
+def GetAdWordsClient(**kwargs):
+ """Returns an initialized AdwordsClient for use in testing.
+
+ If not specified, the keyword arguments will be set to default test values.
+
+ Keyword Arguments:
+ ccid: A str value for the AdWordsClient's client_customer_id.
+ dev_token: A str value for the AdWordsClient's developer_token.
+ oauth2_client: A GoogleOAuth2Client instance or mock implementing its
+ interface.
+ proxy_config: A googleads.common.ProxyConfig instance. If not specified,
+ this will default to None to specify that no Proxy is being used.
+ report_downloader_headers: A dict containing optional report downloader
+ headers.
+ user_agent: A str value for the AdWordsClient's user_agent.
+ timeout: An integer timeout in MS for connections.
+
+ Returns:
+ An AdWordsClient instance intended for testing.
+ """
+ client_customer_id = kwargs.get('ccid', 'client customer id')
+ dev_token = kwargs.get('dev_token', 'dev_token')
+ user_agent = kwargs.get('user_agent', 'user_agent')
+ validate_only = kwargs.get('validate_only', False)
+ partial_failure = kwargs.get('partial_failure', False)
+ report_downloader_headers = kwargs.get('report_downloader_headers', {})
+ timeout = kwargs.get('timeout', 3600)
+
+ if 'oauth2_client' in kwargs:
+ oauth2_client = kwargs['oauth2_client']
+ else:
+ oauth_header = {'Authorization': 'header'}
+ oauth2_client = mock.Mock()
+ oauth2_client.CreateHttpHeader.return_value = dict(oauth_header)
+
+ client = googleads.adwords.AdWordsClient(
+ dev_token, oauth2_client, user_agent,
+ client_customer_id=client_customer_id,
+ cache=kwargs.get('cache'),
+ proxy_config=kwargs.get('proxy_config'),
+ validate_only=validate_only, partial_failure=partial_failure,
+ report_downloader_headers=report_downloader_headers, timeout=timeout)
+ return client
-class AdWordsHeaderHandlerTest(unittest.TestCase):
+
+def GetProxyConfig(http_proxy_uri=None, https_proxy_uri=None, cafile=None,
+ disable_certificate_validation=None):
+ """Returns an initialized ProxyConfig for use in testing.
+
+ Args:
+ http_proxy_uri: A str containing the full URI for the http proxy host. If
+ this is not specified, the ProxyConfig will be initialized without an
+ HTTP proxy configured.
+ https_proxy_uri: A str containing the full URI for the https proxy host. If
+ this is not specified, the ProxyConfig will be initialized without an
+ HTTPS proxy configured.
+ cafile: A str containing the path to a custom ca file.
+ disable_certificate_validation: A boolean indicating whether or not to
+ disable certificate validation.
+
+ Returns:
+ An initialized ProxyConfig using the given configurations.
+ """
+ return googleads.common.ProxyConfig(
+ http_proxy_uri, https_proxy_uri, cafile=cafile,
+ disable_certificate_validation=disable_certificate_validation)
+
+
+class AdWordsHeaderHandlerTest(testing.CleanUtilityRegistryTestCase):
"""Tests for the googleads.adwords._AdWordsHeaderHandler class."""
def setUp(self):
- self.adwords_client = mock.Mock()
+ self.report_downloader_headers = {}
+ self.oauth2_client = mock.Mock()
+ self.oauth_header = {'Authorization': 'header'}
+ self.oauth2_client.CreateHttpHeader.return_value = self.oauth_header
+ self.ccid = 'client customer id'
+ self.dev_token = 'developer token'
+ self.user_agent = 'user agent!'
+ self.validate_only = True
+ self.partial_failure = False
+ self.enable_compression = False
+ self.utility_name = 'TestUtility'
+ self.default_sig_template = ' (%s, %s, %s)'
+ self.util_sig_template = ' (%s, %s, %s, %s)'
+ self.aw_client = GetAdWordsClient(
+ ccid=self.ccid, dev_token=self.dev_token,
+ user_agent=self.user_agent, oauth2_client=self.oauth2_client,
+ validate_only=self.validate_only, partial_failure=self.partial_failure,
+ report_downloader_headers=self.report_downloader_headers)
self.header_handler = googleads.adwords._AdWordsHeaderHandler(
- self.adwords_client, CURRENT_VERSION)
-
- def testSetHeaders(self):
- suds_client = mock.Mock()
- ccid = 'client customer id'
- dev_token = 'developer token'
- user_agent = 'user agent!'
- validate_only = True
- partial_failure = False
- oauth_header = {'oauth': 'header'}
- self.adwords_client.client_customer_id = ccid
- self.adwords_client.developer_token = dev_token
- self.adwords_client.user_agent = user_agent
- self.adwords_client.validate_only = validate_only
- self.adwords_client.partial_failure = partial_failure
- self.adwords_client.oauth2_client.CreateHttpHeader.return_value = (
- oauth_header)
-
- self.header_handler.SetHeaders(suds_client)
+ self.aw_client, CURRENT_VERSION, self.enable_compression, None)
+
+ @googleads.common.RegisterUtility(self.utility_name)
+ class TestUtility(object):
+
+ def Test(self):
+ pass
+
+ self.test_utility = TestUtility()
+
+ def testGetHTTPHeaders(self):
+ header_result = self.header_handler.GetHTTPHeaders()
+ # Check that the returned headers have the correct values.
+ self.assertEqual(header_result, self.oauth_header)
+ def testGetHTTPHeadersWithCustomHeaders(self):
+ self.header_handler.custom_http_headers = {'X-My-Header': 'abc'}
+
+ header_result = self.header_handler.GetHTTPHeaders()
+
+ self.assertEqual(
+ header_result, {'Authorization': 'header', 'X-My-Header': 'abc'})
+
+ def testGetSOAPHeaders(self):
+ create_method = mock.Mock()
+ soap_header = self.header_handler.GetSOAPHeaders(create_method)
# Check that the SOAP header has the correct values.
- suds_client.factory.create.assert_called_once_with(
+ create_method.assert_called_once_with(
'{https://adwords.google.com/api/adwords/cm/%s}SoapHeader' %
CURRENT_VERSION)
- soap_header = suds_client.factory.create.return_value
- self.assertEqual(ccid, soap_header.clientCustomerId)
- self.assertEqual(dev_token, soap_header.developerToken)
+ self.assertEqual(self.ccid, soap_header.clientCustomerId)
+ self.assertEqual(self.dev_token, soap_header.developerToken)
self.assertEqual(
- ''.join([user_agent, googleads.adwords._AdWordsHeaderHandler._LIB_SIG]),
+ ''.join([self.user_agent,
+ googleads.common.GenerateLibSig(
+ googleads.adwords._AdWordsHeaderHandler._PRODUCT_SIG)]),
soap_header.userAgent)
- self.assertEqual(validate_only, soap_header.validateOnly)
- self.assertEqual(partial_failure, soap_header.partialFailure)
+ self.assertEqual(self.validate_only, soap_header.validateOnly)
+ self.assertEqual(self.partial_failure, soap_header.partialFailure)
- # Check that the suds client has the correct values.
- suds_client.set_options.assert_any_call(
- soapheaders=soap_header, headers=oauth_header)
+ def testGetHeadersUserAgentWithUtility(self):
+ create_method = mock.Mock()
- def testGetReportDownloadHeaders(self):
- ccid = 'client customer id'
- dev_token = 'developer token'
- user_agent = 'user agent!'
- oauth_header = {'Authorization': 'header'}
- self.adwords_client.client_customer_id = ccid
- self.adwords_client.developer_token = dev_token
- self.adwords_client.user_agent = user_agent
- self.adwords_client.oauth2_client.CreateHttpHeader.return_value = dict(
- oauth_header)
+ with mock.patch('googleads.common._COMMON_LIB_SIG') as mock_common_sig:
+ with mock.patch('googleads.common._PYTHON_VERSION') as mock_py_ver:
+ self.test_utility.Test() # This will register TestUtility.
+ soap_header = self.header_handler.GetSOAPHeaders(create_method)
+
+ self.assertEqual(
+ ''.join([self.user_agent,
+ self.util_sig_template % (
+ googleads.adwords._AdWordsHeaderHandler._PRODUCT_SIG,
+ mock_common_sig,
+ mock_py_ver,
+ self.utility_name)
+ ]),
+ soap_header.userAgent)
+
+ def testGetHeadersUserAgentWithAndWithoutUtility(self):
+ create_method = mock.Mock()
+
+ with mock.patch('googleads.common._COMMON_LIB_SIG') as mock_common_sig:
+ with mock.patch('googleads.common._PYTHON_VERSION') as mock_py_ver:
+ # Check headers when utility registered.
+ self.test_utility.Test() # This will register TestUtility.
+ soap_header = self.header_handler.GetSOAPHeaders(create_method)
+
+ self.assertEqual(
+ ''.join([self.user_agent,
+ self.util_sig_template % (
+ googleads.adwords._AdWordsHeaderHandler._PRODUCT_SIG,
+ mock_common_sig,
+ mock_py_ver,
+ self.utility_name)
+ ]),
+ soap_header.userAgent)
+
+ # Check headers when no utility should be registered.
+ soap_header = self.header_handler.GetSOAPHeaders(create_method)
+ self.assertEqual(
+ ''.join([self.user_agent,
+ self.default_sig_template % (
+ googleads.adwords._AdWordsHeaderHandler._PRODUCT_SIG,
+ mock_common_sig,
+ mock_py_ver)
+ ]),
+ soap_header.userAgent)
+
+ # Verify that utility is registered in subsequent uses.
+ self.test_utility.Test() # This will register TestUtility.
+ soap_header = self.header_handler.GetSOAPHeaders(create_method)
+
+ self.assertEqual(
+ ''.join([self.user_agent,
+ self.util_sig_template % (
+ googleads.adwords._AdWordsHeaderHandler._PRODUCT_SIG,
+ mock_common_sig,
+ mock_py_ver,
+ self.utility_name)
+ ]),
+ soap_header.userAgent)
+
+ def testGetReportDownloadHeadersOverrideDefaults(self):
+ self.aw_client.report_downloader_headers = {
+ 'skip_report_header': True, 'skip_column_header': False,
+ 'skip_report_summary': False, 'use_raw_enum_values': True}
expected_return_value = {
'Content-type': 'application/x-www-form-urlencoded',
- 'developerToken': dev_token,
- 'clientCustomerId': ccid,
+ 'developerToken': self.dev_token,
+ 'clientCustomerId': self.ccid,
'Authorization': 'header',
'User-Agent': ''.join([
- user_agent, googleads.adwords._AdWordsHeaderHandler._LIB_SIG,
- ',gzip'])
+ self.user_agent,
+ googleads.common.GenerateLibSig(
+ googleads.adwords._AdWordsHeaderHandler._PRODUCT_SIG),
+ ',gzip']),
+ 'skipReportHeader': 'False',
+ 'skipColumnHeader': 'True',
+ 'skipReportSummary': 'False',
+ 'useRawEnumValues': 'True'
}
+ self.assertEqual(expected_return_value,
+ self.header_handler.GetReportDownloadHeaders(
+ skip_report_header=False,
+ skip_column_header=True,
+ skip_report_summary=False,
+ use_raw_enum_values=True))
- self.adwords_client.oauth2_client.CreateHttpHeader.return_value = dict(
- oauth_header)
+ def testGetReportDownloadHeadersWithDefaultsFromConfig(self):
+ self.aw_client.report_download_headers = {
+ 'skip_report_header': True, 'skip_column_header': False,
+ 'skip_report_summary': False, 'use_raw_enum_values': True}
+ expected_return_value = {
+ 'Content-type': 'application/x-www-form-urlencoded',
+ 'developerToken': self.dev_token,
+ 'clientCustomerId': self.ccid,
+ 'Authorization': 'header',
+ 'User-Agent': ''.join([
+ self.user_agent,
+ googleads.common.GenerateLibSig(
+ googleads.adwords._AdWordsHeaderHandler._PRODUCT_SIG),
+ ',gzip']),
+ 'skipReportHeader': 'True',
+ 'skipColumnHeader': 'False',
+ 'skipReportSummary': 'False',
+ 'useRawEnumValues': 'True'
+ }
+ self.assertEqual(expected_return_value,
+ self.header_handler.GetReportDownloadHeaders())
+
+ def testGetReportDownloadHeadersWithInvalidKeyword(self):
+ self.assertRaises(
+ googleads.errors.GoogleAdsValueError,
+ self.header_handler.GetReportDownloadHeaders, invalid_key_word=True)
+
+ def testGetReportDownloadHeadersWithKeywordArguments(self):
+ updated_ccid = 'updated client customer id'
+ expected_return_value = {
+ 'Content-type': 'application/x-www-form-urlencoded',
+ 'developerToken': self.dev_token,
+ 'clientCustomerId': updated_ccid,
+ 'Authorization': 'header',
+ 'User-Agent': ''.join([
+ self.user_agent,
+ googleads.common.GenerateLibSig(
+ googleads.adwords._AdWordsHeaderHandler._PRODUCT_SIG),
+ ',gzip']),
+ 'skipReportHeader': 'True',
+ 'skipColumnHeader': 'True',
+ 'skipReportSummary': 'True',
+ 'includeZeroImpressions': 'True',
+ 'useRawEnumValues': 'True'
+ }
self.assertEqual(expected_return_value,
self.header_handler.GetReportDownloadHeaders(
- skip_report_header=False, skip_report_summary=False))
+ skip_report_header=True,
+ skip_column_header=True,
+ skip_report_summary=True,
+ include_zero_impressions=True,
+ use_raw_enum_values=True,
+ client_customer_id=updated_ccid))
+
+ def testGetReportDownloadHeadersWithNoOptionalHeaders(self):
+ expected_return_value = {
+ 'Content-type': 'application/x-www-form-urlencoded',
+ 'developerToken': self.dev_token,
+ 'clientCustomerId': self.ccid,
+ 'Authorization': 'header',
+ 'User-Agent': ''.join([
+ self.user_agent,
+ googleads.common.GenerateLibSig(
+ googleads.adwords._AdWordsHeaderHandler._PRODUCT_SIG),
+ ',gzip'])
+ }
+ self.assertEqual(expected_return_value,
+ self.header_handler.GetReportDownloadHeaders())
class AdWordsClientTest(unittest.TestCase):
"""Tests for the googleads.adwords.AdWordsClient class."""
def setUp(self):
- oauth_header = {'Authorization': 'header'}
- self.cache = None
- self.client_customer_id = 'client customer id'
- self.dev_token = 'developers developers developers'
- self.user_agent = 'users users user'
- self.oauth2_client = mock.Mock()
- self.oauth2_client.CreateHttpHeader.return_value = dict(oauth_header)
- self.https_proxy = 'myproxy:443'
- self.adwords_client = googleads.adwords.AdWordsClient(
- self.dev_token, self.oauth2_client, self.user_agent,
- client_customer_id=self.client_customer_id,
- https_proxy=self.https_proxy, cache=self.cache)
+ self.load_from_storage_path = os.path.join(
+ os.path.dirname(__file__), 'test_data/adwords_googleads.yaml')
+ self.https_proxy_uri = 'http://myproxy:443'
+ self.proxy_config = GetProxyConfig(https_proxy_uri=self.https_proxy_uri)
+ self.adwords_client = GetAdWordsClient()
+ self.aw_client = GetAdWordsClient(proxy_config=self.proxy_config)
self.header_handler = googleads.adwords._AdWordsHeaderHandler(
- self.adwords_client, CURRENT_VERSION)
+ self.adwords_client, CURRENT_VERSION, False, None)
def testLoadFromStorage(self):
+ with mock.patch('googleads.oauth2.GoogleRefreshTokenClient.Refresh'):
+ self.assertIsInstance(googleads.adwords.AdWordsClient.LoadFromStorage(
+ path=self.load_from_storage_path), googleads.adwords.AdWordsClient)
+
+ def testLoadFromStorageWithCompressionEnabled(self):
+ enable_compression = True
+ user_agent_gzip_template = '%s (gzip)'
+ default_user_agent = 'unit testing'
+
with mock.patch('googleads.common.LoadFromStorage') as mock_load:
mock_load.return_value = {
'developer_token': 'abcdEFghIjkLMOpqRs',
- 'oauth2_client': True,
- 'user_agent': 'unit testing'
+ 'oauth2_client': mock.Mock(),
+ 'user_agent': default_user_agent,
+ 'enable_compression': enable_compression
}
- self.assertIsInstance(googleads.adwords.AdWordsClient.LoadFromStorage(),
- googleads.adwords.AdWordsClient)
+ client = googleads.adwords.AdWordsClient.LoadFromStorage()
+ self.assertEqual(enable_compression, client.enable_compression)
+ self.assertEqual(user_agent_gzip_template % default_user_agent,
+ client.user_agent)
+
+ def testLoadFromStorageWithNonASCIIUserAgent(self):
+ with mock.patch('googleads.common.LoadFromStorage') as mock_load:
+ mock_load.return_value = {
+ 'developer_token': 'abcdEFghIjkLMOpqRs',
+ 'oauth2_client': mock.Mock(),
+ 'user_agent': u'ゼロ'
+ }
+ self.assertRaises(googleads.errors.GoogleAdsValueError,
+ googleads.adwords.AdWordsClient.LoadFromStorage)
+
+ def testLoadFromStorageWithNoUserAgent(self):
+ with mock.patch('googleads.common.LoadFromStorage') as mock_load:
+ mock_load.return_value = {
+ 'developer_token': 'abcdEFghIjkLMOpqRs',
+ 'oauth2_client': mock.Mock()
+ }
+
+ client = googleads.adwords.AdWordsClient.LoadFromStorage()
+ self.assertEqual(client.user_agent, 'unknown')
def testGetService_success(self):
- version = CURRENT_VERSION
- service = googleads.adwords._SERVICE_MAP[version].keys()[0]
- namespace = googleads.adwords._SERVICE_MAP[version][service]
+ client = GetAdWordsClient(
+ timeout='timeout', cache='cache', proxy_config='proxy_config')
+ client.enable_compression = True
+ service_name = list(googleads.adwords._SERVICE_MAP[CURRENT_VERSION])[0]
+ namespace = googleads.adwords._SERVICE_MAP[CURRENT_VERSION][service_name]
# Use a custom server. Also test what happens if the server ends with a
# trailing slash
server = 'https://testing.test.com/'
- https_proxy = {'https': self.https_proxy}
- with mock.patch('suds.client.Client') as mock_client:
- suds_service = self.adwords_client.GetService(service, version, server)
-
- mock_client.assert_called_once_with(
- 'https://testing.test.com/api/adwords/%s/%s/%s?wsdl'
- % (namespace, version, service), proxy=https_proxy, cache=self.cache,
- timeout=3600)
- self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy)
-
- # Use the default server and https_proxy.
- self.adwords_client.https_proxy = None
- with mock.patch('suds.client.Client') as mock_client:
- suds_service = self.adwords_client.GetService(service, version)
-
- mock_client.assert_called_once_with(
- 'https://adwords.google.com/api/adwords/%s/%s/%s?wsdl'
- % (namespace, version, service), proxy=None, cache=self.cache,
- timeout=3600)
- self.assertFalse(mock_client.return_value.set_options.called)
- self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy)
+
+ with mock.patch('googleads.common.'
+ 'GetServiceClassForLibrary') as mock_get_service:
+ with mock.patch('googleads.adwords.'
+ '_AdWordsHeaderHandler') as mock_header_handler:
+ mock_header_handler.return_value = 'header_handler'
+
+ impl = mock.Mock()
+ mock_service = mock.Mock()
+ impl.return_value = mock_service
+ mock_get_service.return_value = impl
+
+ service = client.GetService(service_name, CURRENT_VERSION, server)
+ mock_header_handler.assert_called_once_with(
+ client, CURRENT_VERSION, True, None)
+ impl.assert_called_once_with(
+ 'https://testing.test.com/api/adwords/%s/%s/%s?wsdl' % (
+ namespace, CURRENT_VERSION, service_name),
+ 'header_handler',
+ googleads.adwords._AdWordsPacker,
+ 'proxy_config',
+ 'timeout',
+ CURRENT_VERSION,
+ cache='cache')
+ self.assertEqual(service, mock_service)
def testGetService_badService(self):
version = CURRENT_VERSION
self.assertRaises(
- googleads.errors.GoogleAdsValueError, self.adwords_client.GetService,
+ googleads.errors.GoogleAdsValueError,
+ self.adwords_client.GetService,
'GYIVyievfyiovslf', version)
def testGetService_badVersion(self):
@@ -177,6 +433,12 @@ def testGetService_badVersion(self):
googleads.errors.GoogleAdsValueError, self.adwords_client.GetService,
'CampaignService', '11111')
+ def testGetBatchJobHelper(self):
+ with mock.patch('googleads.adwords.BatchJobHelper') as mock_helper:
+ self.assertEqual(
+ mock_helper.return_value,
+ self.adwords_client.GetBatchJobHelper())
+
def testGetReportDownloader(self):
with mock.patch('googleads.adwords.ReportDownloader') as mock_downloader:
self.assertEqual(
@@ -186,67 +448,1271 @@ def testGetReportDownloader(self):
self.adwords_client, 'version', 'server')
def testSetClientCustomerId(self):
- suds_client = mock.Mock()
+ create_method = mock.Mock()
ccid = 'modified'
# Check that the SOAP header has the modified client customer id.
self.adwords_client.SetClientCustomerId(ccid)
- self.header_handler.SetHeaders(suds_client)
- soap_header = suds_client.factory.create.return_value
- self.assertEqual(ccid, soap_header.clientCustomerId)
+ header_result = self.header_handler.GetSOAPHeaders(create_method)
+ self.assertEqual(ccid, header_result.clientCustomerId)
+
+
+class AdWordsClientIntegrationTest(unittest.TestCase):
+ """Integration tests for googleads.adwords.AdWordsClient."""
+
+ def testServiceMap(self):
+ server = googleads.adwords._DEFAULT_ENDPOINT
+ service_map = googleads.adwords._SERVICE_MAP
+ wsdl_url_template = googleads.adwords.AdWordsClient._SOAP_SERVICE_FORMAT
+
+ for version, services in service_map.items():
+ for service, mapping in services.items():
+ wsdl_url = wsdl_url_template % (server, mapping, version, service)
+ try:
+ urlopen(wsdl_url)
+ except HTTPError:
+ raise ValueError('AdWords API %s does not contain "%s" with mapping '
+ '"%s". The generated WSDL URL does not exist:\n%s'
+ % (version, service, mapping, wsdl_url))
+
+
+class AdWordsPackerTest(unittest.TestCase):
+ """Tests for the googleads.adwords._AdWordsPacker class."""
+
+ def setUp(self):
+ self.packer = googleads.adwords._AdWordsPacker
+ def testAdWordsPackerForServiceQuery(self):
+ query = (googleads.adwords.ServiceQueryBuilder()
+ .Select('Id', 'Name', 'Status')
+ .Where('Status').EqualTo('ENABLED')
+ .OrderBy('Name')
+ .Limit(0, 100)
+ .Build())
+
+ query_regex = (r'SELECT (.*) WHERE Status = "ENABLED"'
+ r' ORDER BY Name ASC LIMIT 0,100')
+
+ self.assertRegexpMatches(self.packer.Pack(query, CURRENT_VERSION),
+ query_regex)
+
+ def testAdWordsPackerForUnsupportedObjectType(self):
+ obj = object()
+ self.assertEqual(self.packer.Pack(obj, CURRENT_VERSION), obj)
+
+
+class BatchJobHelperTest(testing.CleanUtilityRegistryTestCase):
+
+ """Test suite for BatchJobHelper utility."""
+
+ def setUp(self):
+ """Prepare tests."""
+ self.client = GetAdWordsClient()
+ self.batch_job_helper = self.client.GetBatchJobHelper()
+
+ def testGetId(self):
+ expected = [-x for x in range(1, 101)]
+ for value in expected:
+ self.assertEqual(value, self.batch_job_helper.GetId())
+
+ def testUploadOperations(self):
+ with mock.patch('googleads.adwords.BatchJobHelper.'
+ '_UploadRequestBuilder.'
+ 'BuildUploadRequest') as mock_build_request:
+ mock_request = mock.Mock()
+ mock_request.data = 'in disguise.'
+ mock_request.get_full_url.return_value = 'https://google.com/'
+ mock_request.headers = {'Content-range': 0, 'Content-length': 0}
+ mock_build_request.return_value = mock_request
+ with mock.patch('googleads.adwords.IncrementalUploadHelper'
+ '._InitializeURL') as mock_init:
+ mock_init.return_value = 'https://www.google.com'
+ with mock.patch('urllib.request.OpenerDirector.open') as mock_open:
+ self.batch_job_helper.UploadOperations([[]])
+ mock_open.assert_called_with(mock_request)
+
+
+class BatchJobUploadRequestBuilderTest(testing.CleanUtilityRegistryTestCase):
+
+ """Test suite for the BatchJobUploadRequestBuilder."""
+
+ ENVELOPE_NS = 'http://schemas.xmlsoap.org/soap/envelope/'
+
+ def setUp(self):
+ """Prepare tests."""
+ self.client = GetAdWordsClient()
+ self.request_builder = self.client.GetBatchJobHelper()._request_builder
+ self.version = self.request_builder._version
+ self.upload_url = 'https://goo.gl/IaQQsJ'
+ self.sample_xml = ('!n3vERg0Nn4Run4r0und4NDd35Er7Y0u!~'
+ '')
+ self.complete_request_body = '%s%s%s' % (
+ self.request_builder._UPLOAD_PREFIX_TEMPLATE % (
+ self.request_builder._adwords_endpoint),
+ self.sample_xml,
+ self.request_builder._UPLOAD_SUFFIX)
+ self.request_body_complete = '%s%s%s' % (
+ self.request_builder._UPLOAD_PREFIX_TEMPLATE % (
+ self.request_builder._adwords_endpoint),
+ self.sample_xml,
+ self.request_builder._UPLOAD_SUFFIX)
+ self.request_body_start = '%s%s' % (
+ self.request_builder._UPLOAD_PREFIX_TEMPLATE %
+ self.request_builder._adwords_endpoint, self.sample_xml)
+ self.request_body_end = '%s%s' % (
+ self.sample_xml,
+ self.request_builder._UPLOAD_SUFFIX)
+ self.single_upload_headers = {
+ 'Content-type': 'application/xml',
+ 'Content-range': 'bytes %s-%s/%s' % (
+ 0,
+ self.request_builder._BATCH_JOB_INCREMENT - 1,
+ self.request_builder._BATCH_JOB_INCREMENT),
+ 'Content-length': self.request_builder._BATCH_JOB_INCREMENT
+ }
+ self.incremental_upload_headers = {
+ 'Content-type': 'application/xml',
+ 'Content-range': 'bytes %s-%s/*' % (
+ self.request_builder._BATCH_JOB_INCREMENT,
+ (self.request_builder._BATCH_JOB_INCREMENT * 2) - 1
+ ),
+ 'Content-length': self.request_builder._BATCH_JOB_INCREMENT
+ }
+
+ @classmethod
+ def setUpClass(cls):
+ test_dir = os.path.dirname(__file__)
+ with open(os.path.join(
+ test_dir, 'test_data/batch_job_util_budget_template.txt')) as handler:
+ cls.BUDGET_TEMPLATE = handler.read()
+ with open(os.path.join(
+ test_dir,
+ 'test_data/batch_job_util_campaign_criterion_template.txt')) as handler:
+ cls.CAMPAIGN_CRITERION_TEMPLATE = handler.read()
+ with open(os.path.join(
+ test_dir,
+ 'test_data/batch_job_util_campaign_label_template.txt')) as handler:
+ cls.CAMPAIGN_LABEL_TEMPLATE = handler.read()
+ with open(os.path.join(
+ test_dir, 'test_data/batch_job_util_invalid_request.txt')) as handler:
+ cls.INVALID_API_REQUEST = handler.read()
+ with open(os.path.join(
+ test_dir, 'test_data/batch_job_util_not_request.txt')) as handler:
+ cls.NOT_API_REQUEST = handler.read()
+ with open(os.path.join(
+ test_dir, 'test_data/batch_job_util_raw_request_template.txt')
+ ) as handler:
+ cls.RAW_API_REQUEST_TEMPLATE = handler.read()
+ with open(os.path.join(
+ test_dir, 'test_data/batch_job_util_operations_template.txt')
+ ) as handler:
+ cls.OPERATIONS_TEMPLATE = handler.read()
+ with open(os.path.join(
+ test_dir, 'test_data/batch_job_util_upload_template.txt')) as handler:
+ cls.UPLOAD_OPERATIONS_TEMPLATE = handler.read()
+
+ def ExpandOperandTemplate(self, operation_type, operand):
+ """Expands the appropriate operand for the given operation_type.
+
+ Args:
+ operation_type: str indicating the type of operation the operand is being
+ expanded for. Accepted types include: "BudgetOperation",
+ "CampaignCriterionOperation", and "CampaignLabelOperation".
+ operand: dict containing fields for the operation_type's operand.
+
+ Returns:
+ A str containing the expanded operand.
+
+ Raises:
+ ValueError: if an unsupported operation_type is specified.
+ """
+ if operation_type == 'BudgetOperation':
+ return self.BUDGET_TEMPLATE % (
+ operand['budgetId'], operand['name'],
+ operand['amount']['microAmount'], operand['deliveryMethod'])
+ elif operation_type == 'CampaignCriterionOperation':
+ return self.CAMPAIGN_CRITERION_TEMPLATE % (
+ operand['CampaignCriterion.Type'], operand['campaignId'],
+ operand['criterion']['Criterion.Type'],
+ operand['criterion']['text'],
+ operand['criterion']['matchType'])
+ elif operation_type == 'CampaignLabelOperation':
+ return self.CAMPAIGN_LABEL_TEMPLATE % (
+ operand['campaignId'], operand['labelId'])
+ else:
+ raise ValueError('Invalid operation_type "%s" specified.'
+ % operation_type)
+
+ def GenerateOperations(self, operation_type, num_operations):
+ """Generates a set of operations of the given type.
+
+ Args:
+ operation_type: str indicating the type of operation to be generated.
+ Accepted types include: "BudgetOperation", "CampaignCriterionOperation",
+ and "CampaignLabelOperation".
+ num_operations: a positive int defining the number of operations to be
+ generated.
+
+ Returns:
+ A tuple where the first item indicates the method to be used in the
+ request and the second is a list of dictionaries containing distinct
+ operations of the given operation_type.
+
+ Raises:
+ ValueError: if an unsupported operation_type is specified.
+ """
+ operation_range = range(1, num_operations + 1)
+
+ if operation_type == 'BudgetOperation':
+ return ('mutate', [{
+ 'operator': 'ADD',
+ 'xsi_type': 'BudgetOperation',
+ 'operand': {
+ 'budgetId': str(i),
+ 'name': 'Batch budget #%s' % i,
+ 'amount': {'microAmount': str(3333333 * i)},
+ 'deliveryMethod': 'STANDARD'}
+ } for i in operation_range])
+ elif operation_type == 'CampaignCriterionOperation':
+ return ('mutate', [{
+ 'operator': 'ADD',
+ 'xsi_type': 'CampaignCriterionOperation',
+ 'operand': {
+ 'xsi_type': 'NegativeCampaignCriterion',
+ 'campaignId': str(100 * i),
+ 'criterion': {
+ 'xsi_type': 'Keyword',
+ 'text': 'venus %s' % i,
+ 'matchType': 'BROAD'
+ }
+ }
+ } for i in operation_range])
+ elif operation_type == 'CampaignLabelOperation':
+ return ('mutateLabel', [{
+ 'operator': 'ADD',
+ 'xsi_type': 'CampaignLabelOperation',
+ 'operand': {
+ 'campaignId': 123 * i,
+ 'labelId': 321 * i}
+ } for i in operation_range])
+ else:
+ raise ValueError('Invalid operation_type "%s" specified.'
+ % operation_type)
+
+ def GenerateValidRequest(self, operation_type, num_operations=1):
+ """Generates a valid API request containing the given number of operations.
+
+ Args:
+ operation_type: str indicating the type of operation to be generated.
+ Accepted types include: "BudgetOperation", "CampaignCriterionOperation",
+ and "CampaignLabelOperation".
+ num_operations: a positive int defining the number of operations to be
+ generated.
+
+ Returns:
+ A tuple containing the operations used to construct str containing a valid
+ API request.
+
+ Raises:
+ ValueError: if an unsupported operation_type is specified.
+ """
+ method, ops = self.GenerateOperations(operation_type, num_operations)
+
+ ops_xml = ''.join([self.OPERATIONS_TEMPLATE % (
+ op['operator'], op['xsi_type'],
+ self.ExpandOperandTemplate(operation_type, op['operand'])
+ ) for op in ops])
+
+ request = self.RAW_API_REQUEST_TEMPLATE % (
+ self.version, self.version, method, ops_xml, method)
+ request = bytes(request, 'utf-8')
+ request = lxml.etree.fromstring(request)
+
+ return (ops, request)
+
+ def GenerateValidUnicodeRequest(self, operations):
+ """Generates a valid API request containing the given number of operations.
+
+ Args:
+ operations: a positive int defining the number of BudgetOperations to be
+ generated.
+
+ Returns:
+ A tuple containing the operations used to construct unicode containing a
+ valid API request.
+ """
+ ops = self.GenerateUnicodeBudgetOperations(operations)
+ method = 'mutate'
+ ops_xml = ''.join([self.OPERATIONS_TEMPLATE % (
+ op['operator'], op['xsi_type'],
+ self.ExpandOperandTemplate('BudgetOperation', op['operand'])
+ ) for op in ops])
+
+ request = (self.RAW_API_REQUEST_TEMPLATE % (
+ self.version, self.version, method, ops_xml, method)).encode('utf-8')
+ request = lxml.etree.fromstring(request)
+
+ return (ops, request)
+
+ def GenerateUnicodeBudgetOperations(self, operations):
+ """Generates request containing given number of BudgetOperations.
+
+ Args:
+ operations: a positive int defining the number of BudgetOperations to be
+ generated.
+ Returns:
+ A list of dictionaries containing distinct BudgetOperations.
+ """
+ return [{
+ 'operator': 'ADD',
+ 'xsi_type': 'BudgetOperation',
+ 'operand': {
+ 'budgetId': str(i),
+ 'name': u'アングリーバード Batch budget #%d' % i,
+ 'amount': {'microAmount': str(3333333 * i)},
+ 'deliveryMethod': 'STANDARD'}
+ } for i in range(1, operations + 1)]
+
+ def testGetPaddingLength(self):
+ length = len(self.sample_xml)
+ padding = self.request_builder._GetPaddingLength(length)
+ self.assertTrue(
+ padding == self.request_builder._BATCH_JOB_INCREMENT - length)
+
+ def testExtractOperations(self):
+ """Tests whether operations XML was extracted and formatted correctly.
+
+ Verifies that the xsi_type has been properly assigned.
+ """
+ _, operations = self.GenerateOperations('CampaignCriterionOperation', 1)
+ raw_xml = self.request_builder._GenerateRawRequestXML(operations)
+ operations_xml = self.request_builder._ExtractOperations(raw_xml)
+ # Put operations in a format that allows us to easily verify the behavior.
+ ElementTree.register_namespace(
+ 'xsi', 'http://www.w3.org/2001/XMLSchema-instance')
+ # Need to declare xsi for ElementTree to parse operations properly.
+ body = ElementTree.fromstring(
+ '%s'
+ '' % operations_xml)
+ self.assertTrue(body.tag == 'body')
+ ops_element = body.find('operations')
+ # Check that the xsi_type has been set correctly.
+ self.assertTrue(ops_element.attrib[
+ '{http://www.w3.org/2001/XMLSchema-instance}type'] ==
+ 'CampaignCriterionOperation')
+ operand = ops_element.find('operand')
+ self.assertTrue(operand.attrib[
+ '{http://www.w3.org/2001/XMLSchema-instance}type'] ==
+ 'NegativeCampaignCriterion')
+ criterion = operand.find('criterion')
+ self.assertTrue(criterion.attrib[
+ '{http://www.w3.org/2001/XMLSchema-instance}type'] ==
+ 'Keyword')
+
+ def testFormatForBatchJobService(self):
+ """Tests whether namespaces have been removed."""
+ operations_amount = 5
+ _, ops = self.GenerateOperations('CampaignCriterionOperation',
+ operations_amount)
+ root = self.request_builder._GenerateRawRequestXML(ops)
+ body = root.find('{%s}Body' % self.ENVELOPE_NS)
+ mutate = body.find('{%s}mutate' % self.request_builder._adwords_endpoint)
+ self.request_builder._FormatForBatchJobService(mutate)
+ self.assertTrue(self.request_builder._adwords_endpoint not in mutate.tag)
+ self.assertTrue(len(mutate) == operations_amount)
+
+ for ops in mutate:
+ self.assertTrue(self.request_builder._adwords_endpoint not in ops.tag)
+ for child in ops:
+ self.assertTrue(self.request_builder._adwords_endpoint not in
+ child.tag)
+ operand = ops.find('operand')
+ self.assertTrue(len(operand.attrib) == 1)
+ self.assertTrue(
+ 'ns' not in
+ operand.attrib['{http://www.w3.org/2001/XMLSchema-instance}type'])
+ for child in operand:
+ self.assertTrue(self.request_builder._adwords_endpoint not in
+ child.tag)
+ criterion = operand.find('criterion')
+ self.assertTrue(
+ 'ns' not in
+ criterion.attrib['{http://www.w3.org/2001/XMLSchema-instance}type'])
+ for child in criterion:
+ self.assertTrue(self.request_builder._adwords_endpoint not in
+ child.tag)
+
+ def testGenerateOperationsXMLNoXsiType(self):
+ """Tests whether _GenerateOperationsXML raises ValueError if no xsi_type.
+ """
+ _, operations = self.GenerateOperations('CampaignCriterionOperation', 1)
+ del operations[0]['xsi_type']
+ self.assertRaises(
+ googleads.errors.AdWordsBatchJobServiceInvalidOperationError,
+ self.request_builder._GenerateOperationsXML, operations)
+
+ def testGenerateOperationsXMLWithNoOperations(self):
+ """Tests whether _GenerateOperationsXML produces empty str if no operations.
+ """
+ _, operations = self.GenerateOperations('CampaignCriterionOperation', 0)
+ raw_xml = self.request_builder._GenerateOperationsXML(
+ operations)
+ self.assertTrue(raw_xml is '')
+
+ def testGenerateRawRequestXMLFromBogusOperation(self):
+ """Tests whether an invalid operation raises an Exception."""
+ bogus_operations = [{
+ 'operator': 'ADD',
+ 'xsi_type': 'BogusOperation',
+ 'operand': {
+ 'bogusProperty': 'bogusValue'}
+ }]
+
+ self.assertRaises(KeyError,
+ self.request_builder._GenerateRawRequestXML,
+ bogus_operations)
+
+ def testGenerateRawRequestXMLFromCampaignLabelOperation(self):
+ """Tests whether raw request xml can be produced from a label operation."""
+ ops = [{
+ 'operator': 'ADD',
+ 'xsi_type': 'CampaignLabelOperation',
+ 'operand': {'campaignId': 0, 'labelId': 0}
+ }]
+
+ root = self.request_builder._GenerateRawRequestXML(ops)
+ self.assertTrue(len(root) == 2)
+ body = root.find('{%s}Body' % self.ENVELOPE_NS)
+ self.assertTrue(len(body) == 1)
+ mutate_label = body.find('{%s}mutateLabel'
+ % self.request_builder._adwords_endpoint)
+ self.assertTrue(len(mutate_label) == len(ops))
+
+ def testGenerateRawRequestXMLFromSingleOperation(self):
+ """Tests whether raw request xml can be produced from a single operation."""
+ operations_amount = 1
+ _, ops = self.GenerateOperations('BudgetOperation', operations_amount)
+
+ root = self.request_builder._GenerateRawRequestXML(ops)
+ self.assertTrue(len(root) == 2)
+ body = root.find('{%s}Body' % self.ENVELOPE_NS)
+ self.assertTrue(len(body) == 1)
+ mutate = body.find('{%s}mutate' % self.request_builder._adwords_endpoint)
+ self.assertTrue(len(mutate) == operations_amount)
+
+ for i in range(0, operations_amount):
+ operations = mutate[i]
+ self.assertEqual(operations.tag, '{%s}operations' %
+ self.request_builder._adwords_endpoint)
+ self.assertTrue(len(operations.getchildren()) == len(ops[i].keys()))
+ self.assertEqual(operations.find(
+ '{%s}operator' % self.request_builder._adwords_endpoint).text,
+ ops[i]['operator'])
+ self.assertEqual(
+ operations.find(
+ '{%s}Operation.Type' %
+ self.request_builder._adwords_endpoint).text,
+ ops[i]['xsi_type'])
+ operand = operations.find(
+ '{%s}operand' % self.request_builder._adwords_endpoint)
+ self.assertTrue(len(operand.getchildren()) ==
+ len(ops[i]['operand'].keys()))
+ self.assertEqual(operand.find(
+ '{%s}budgetId' % self.request_builder._adwords_endpoint).text,
+ ops[i]['operand']['budgetId'])
+ self.assertEqual(operand.find(
+ '{%s}name' % self.request_builder._adwords_endpoint).text,
+ ops[i]['operand']['name'])
+ amount = operand.find('{%s}amount' %
+ self.request_builder._adwords_endpoint)
+ self.assertTrue(len(amount.getchildren()) ==
+ len(ops[i]['operand']['amount'].keys()))
+ self.assertEqual(amount.find(
+ '{%s}microAmount' % self.request_builder._adwords_endpoint).text,
+ ops[i]['operand']['amount']['microAmount'])
+ self.assertEqual(operand.find(
+ '{%s}deliveryMethod' % self.request_builder._adwords_endpoint).text,
+ ops[i]['operand']['deliveryMethod'])
+
+ def testGenerateRawRequestXMLFromMultipleOperations(self):
+ """Tests whether raw request xml can be produced for multiple operations."""
+ operations_amount = 5
+ _, ops = self.GenerateOperations('BudgetOperation', operations_amount)
+
+ root = self.request_builder._GenerateRawRequestXML(ops)
+ self.assertTrue(len(root) == 2)
+ body = root.find('{%s}Body' % self.ENVELOPE_NS)
+ self.assertTrue(len(body) == 1)
+ mutate = body.find('{%s}mutate' % self.request_builder._adwords_endpoint)
+ self.assertTrue(len(mutate) == operations_amount)
+
+ for i in range(0, operations_amount):
+ operations = mutate[i]
+ self.assertEqual(
+ operations.tag,
+ '{%s}operations' % self.request_builder._adwords_endpoint)
+ self.assertTrue(len(operations.getchildren()) == len(ops[i].keys()))
+ self.assertEqual(operations.find(
+ '{%s}operator' % self.request_builder._adwords_endpoint).text,
+ ops[i]['operator'])
+ self.assertEqual(operations.find(
+ '{%s}Operation.Type' % self.request_builder._adwords_endpoint).text,
+ ops[i]['xsi_type'])
+ operand = operations.find(
+ '{%s}operand' % self.request_builder._adwords_endpoint)
+ self.assertTrue(len(operand.getchildren()) ==
+ len(ops[i]['operand'].keys()))
+ self.assertEqual(operand.find(
+ '{%s}budgetId' % self.request_builder._adwords_endpoint).text,
+ ops[i]['operand']['budgetId'])
+ self.assertEqual(operand.find(
+ '{%s}name' % self.request_builder._adwords_endpoint).text,
+ ops[i]['operand']['name'])
+ amount = operand.find(
+ '{%s}amount' % self.request_builder._adwords_endpoint)
+ self.assertTrue(len(amount.getchildren()) ==
+ len(ops[i]['operand']['amount'].keys()))
+ self.assertEqual(amount.find(
+ '{%s}microAmount' % self.request_builder._adwords_endpoint).text,
+ ops[i]['operand']['amount']['microAmount'])
+ self.assertEqual(operand.find(
+ '{%s}deliveryMethod' % self.request_builder._adwords_endpoint).text,
+ ops[i]['operand']['deliveryMethod'])
+
+ def testGenerateRawUnicodeRequestXMLFromSingleOperation(self):
+ """Tests whether raw request xml can be produced from a single operation."""
+ operations_amount = 1
+ ops = self.GenerateUnicodeBudgetOperations(operations_amount)
+
+ root = self.request_builder._GenerateRawRequestXML(ops)
+ self.assertTrue(len(root) == 2)
+ body = root.find(u'{%s}Body' % self.ENVELOPE_NS)
+ self.assertTrue(len(body) == 1)
+ mutate = body.find(u'{%s}mutate' % self.request_builder._adwords_endpoint)
+ self.assertTrue(len(mutate) == operations_amount)
+
+ for i in range(0, operations_amount):
+ operations = mutate[i]
+ self.assertEqual(operations.tag, '{%s}operations' %
+ self.request_builder._adwords_endpoint)
+ self.assertTrue(len(operations.getchildren()) == len(ops[i].keys()))
+ self.assertEqual(operations.find(
+ '{%s}operator' % self.request_builder._adwords_endpoint).text,
+ ops[i]['operator'])
+ self.assertEqual(
+ operations.find(
+ '{%s}Operation.Type' %
+ self.request_builder._adwords_endpoint).text,
+ ops[i]['xsi_type'])
+ operand = operations.find(
+ '{%s}operand' % self.request_builder._adwords_endpoint)
+ self.assertTrue(len(operand.getchildren()) ==
+ len(ops[i]['operand'].keys()))
+ self.assertEqual(operand.find(
+ '{%s}budgetId' % self.request_builder._adwords_endpoint).text,
+ ops[i]['operand']['budgetId'])
+ self.assertEqual(operand.find(
+ '{%s}name' % self.request_builder._adwords_endpoint).text,
+ ops[i]['operand']['name'])
+ amount = operand.find('{%s}amount' %
+ self.request_builder._adwords_endpoint)
+ self.assertTrue(len(amount.getchildren()) ==
+ len(ops[i]['operand']['amount'].keys()))
+ self.assertEqual(amount.find(
+ '{%s}microAmount' % self.request_builder._adwords_endpoint).text,
+ ops[i]['operand']['amount']['microAmount'])
+ self.assertEqual(operand.find(
+ '{%s}deliveryMethod' % self.request_builder._adwords_endpoint).text,
+ ops[i]['operand']['deliveryMethod'])
+
+ def testGetRawOperationsFromValidSingleOperationMutateLabelRequest(self):
+ """Test if operations XML can be retrieved for a single-op label request."""
+ operations_amount = 1
+ ops, request = self.GenerateValidRequest('CampaignLabelOperation',
+ operations_amount)
+
+ mutate = self.request_builder._GetRawOperationsFromXML(request)
+ self.assertEqual(mutate.tag,
+ '{%s}mutateLabel' % self.request_builder._adwords_endpoint)
+ self.assertTrue(len(mutate.getchildren()) == operations_amount)
+
+ for i in range(0, operations_amount):
+ operations = mutate[i]
+ self.assertEqual(
+ operations.tag,
+ '{%s}operations' % self.request_builder._adwords_endpoint)
+ self.assertTrue(len(operations.getchildren()) == len(ops[i].keys()))
+ self.assertEqual(operations.find(
+ '{%s}operator' % self.request_builder._adwords_endpoint).text,
+ ops[i]['operator'])
+ self.assertEqual(operations.find(
+ '{%s}Operation.Type' % self.request_builder._adwords_endpoint).text,
+ ops[i]['xsi_type'])
+ operand = operations.find(
+ '{%s}operand' % self.request_builder._adwords_endpoint)
+ self.assertTrue(len(operand.getchildren()) ==
+ len(ops[i]['operand'].keys()))
+ self.assertEqual(int(operand.find(
+ '{%s}campaignId' % self.request_builder._adwords_endpoint).text),
+ ops[i]['operand']['campaignId'])
+ self.assertEqual(int(operand.find(
+ '{%s}labelId' % self.request_builder._adwords_endpoint).text),
+ ops[i]['operand']['labelId'])
+
+ def testGetRawOperationsFromValidSingleOperationRequest(self):
+ """Test if operations XML can be retrieved for a single-op request.
+
+ Also verifies that the contents of generated XML are correct.
+ """
+ operations_amount = 1
+ ops, request = self.GenerateValidRequest('BudgetOperation',
+ operations_amount)
+
+ mutate = self.request_builder._GetRawOperationsFromXML(request)
+ self.assertEqual(mutate.tag,
+ '{%s}mutate' % self.request_builder._adwords_endpoint)
+ self.assertTrue(len(mutate.getchildren()) == operations_amount)
+
+ for i in range(0, operations_amount):
+ operations = mutate[i]
+ self.assertEqual(
+ operations.tag,
+ '{%s}operations' % self.request_builder._adwords_endpoint)
+ self.assertTrue(len(operations.getchildren()) == len(ops[i].keys()))
+ self.assertEqual(operations.find(
+ '{%s}operator' % self.request_builder._adwords_endpoint).text,
+ ops[i]['operator'])
+ self.assertEqual(operations.find(
+ '{%s}Operation.Type' % self.request_builder._adwords_endpoint).text,
+ ops[i]['xsi_type'])
+ operand = operations.find(
+ '{%s}operand' % self.request_builder._adwords_endpoint)
+ self.assertTrue(len(operand.getchildren()) ==
+ len(ops[i]['operand'].keys()))
+ self.assertEqual(operand.find(
+ '{%s}budgetId' % self.request_builder._adwords_endpoint).text,
+ ops[i]['operand']['budgetId'])
+ self.assertEqual(operand.find(
+ '{%s}name' % self.request_builder._adwords_endpoint).text,
+ ops[i]['operand']['name'])
+ amount = operand.find(
+ '{%s}amount' % self.request_builder._adwords_endpoint)
+ self.assertTrue(len(amount.getchildren()) ==
+ len(ops[i]['operand']['amount'].keys()))
+ self.assertEqual(amount.find(
+ '{%s}microAmount' % self.request_builder._adwords_endpoint).text,
+ ops[i]['operand']['amount']['microAmount'])
+ self.assertEqual(operand.find(
+ '{%s}deliveryMethod' % self.request_builder._adwords_endpoint).text,
+ ops[i]['operand']['deliveryMethod'])
+
+ def testGetRawOperationsFromValidMultipleOperationRequest(self):
+ """Test whether operations XML can be retrieved for a multi-op request.
+
+ Also verifies that the contents of generated XML are correct.
+ """
+ operations_amount = 5
+ ops, request = self.GenerateValidRequest('BudgetOperation',
+ operations_amount)
+
+ mutate = self.request_builder._GetRawOperationsFromXML(request)
+ self.assertEqual(
+ mutate.tag,
+ '{%s}mutate' % self.request_builder._adwords_endpoint)
+ self.assertTrue(len(mutate.getchildren()) == operations_amount)
+
+ for i in range(0, operations_amount):
+ operations = mutate[i]
+ self.assertEqual(
+ operations.tag,
+ '{%s}operations' % self.request_builder._adwords_endpoint)
+ self.assertTrue(len(operations.getchildren()) == len(ops[i].keys()))
+ self.assertEqual(operations.find(
+ '{%s}operator' % self.request_builder._adwords_endpoint).text,
+ ops[i]['operator'])
+ self.assertEqual(operations.find(
+ '{%s}Operation.Type' % self.request_builder._adwords_endpoint).text,
+ ops[i]['xsi_type'])
+ operand = (operations.find(
+ '{%s}operand' % self.request_builder._adwords_endpoint))
+ self.assertTrue(len(operand.getchildren()) ==
+ len(ops[i]['operand'].keys()))
+ self.assertEqual(operand.find(
+ '{%s}budgetId' % self.request_builder._adwords_endpoint).text,
+ ops[i]['operand']['budgetId'])
+ self.assertEqual(operand.find(
+ '{%s}name' % self.request_builder._adwords_endpoint).text,
+ ops[i]['operand']['name'])
+ amount = (operand.find(
+ '{%s}amount' % self.request_builder._adwords_endpoint))
+ self.assertTrue(len(amount.getchildren()) ==
+ len(ops[i]['operand']['amount'].keys()))
+ self.assertEqual(amount.find(
+ '{%s}microAmount' % self.request_builder._adwords_endpoint).text,
+ ops[i]['operand']['amount']['microAmount'])
+ self.assertEqual(operand.find(
+ '{%s}deliveryMethod' % self.request_builder._adwords_endpoint).text,
+ ops[i]['operand']['deliveryMethod'])
+
+ def testGetRawOperationsFromValidMultipleOperationUnicodeRequest(self):
+ """Test whether operations XML can be retrieved for a multi-op request.
+
+ Also verifies that the contents of generated XML are correct.
+ """
+ operations_amount = 5
+ ops, request = self.GenerateValidUnicodeRequest(operations_amount)
+
+ mutate = self.request_builder._GetRawOperationsFromXML(request)
+ self.assertEqual(
+ mutate.tag,
+ u'{%s}mutate' % self.request_builder._adwords_endpoint)
+ self.assertTrue(len(mutate.getchildren()) == operations_amount)
+
+ for i in range(0, operations_amount):
+ operations = mutate[i]
+ self.assertEqual(
+ operations.tag,
+ '{%s}operations' % self.request_builder._adwords_endpoint)
+ self.assertTrue(len(operations.getchildren()) == len(ops[i].keys()))
+ self.assertEqual(operations.find(
+ '{%s}operator' % self.request_builder._adwords_endpoint).text,
+ ops[i]['operator'])
+ self.assertEqual(operations.find(
+ '{%s}Operation.Type' % self.request_builder._adwords_endpoint).text,
+ ops[i]['xsi_type'])
+ operand = (operations.find(
+ '{%s}operand' % self.request_builder._adwords_endpoint))
+ self.assertTrue(len(operand.getchildren()) ==
+ len(ops[i]['operand'].keys()))
+ self.assertEqual(operand.find(
+ '{%s}budgetId' % self.request_builder._adwords_endpoint).text,
+ ops[i]['operand']['budgetId'])
+ self.assertEqual(operand.find(
+ '{%s}name' % self.request_builder._adwords_endpoint).text,
+ ops[i]['operand']['name'])
+ amount = (operand.find(
+ '{%s}amount' % self.request_builder._adwords_endpoint))
+ self.assertTrue(len(amount.getchildren()) ==
+ len(ops[i]['operand']['amount'].keys()))
+ self.assertEqual(amount.find(
+ '{%s}microAmount' % self.request_builder._adwords_endpoint).text,
+ ops[i]['operand']['amount']['microAmount'])
+ self.assertEqual(operand.find(
+ '{%s}deliveryMethod' % self.request_builder._adwords_endpoint).text,
+ ops[i]['operand']['deliveryMethod'])
+
+ def testGetRawOperationsFromValidZeroOperationRequest(self):
+ """Test verifying empty request generated if no operations provided."""
+ operations_amount = 0
+ _, request = self.GenerateValidRequest('BudgetOperation',
+ operations_amount)
+
+ mutate = self.request_builder._GetRawOperationsFromXML(request)
+
+ self.assertEqual(
+ mutate.tag,
+ '{%s}mutate' % self.request_builder._adwords_endpoint)
+ self.assertTrue(len(mutate.getchildren()) == operations_amount)
-class ReportDownloaderTest(unittest.TestCase):
+ def testGetRawOperationsFromInvalidRequest(self):
+ """Test whether an invalid API request raises an Exception."""
+ self.assertRaises(AttributeError,
+ self.request_builder._GetRawOperationsFromXML,
+ self.INVALID_API_REQUEST)
+
+ def testGetRawOperationsFromNotXMLRequest(self):
+ """Test whether non-XML input raises an Exception."""
+ self.assertRaises(AttributeError,
+ self.request_builder._GetRawOperationsFromXML,
+ self.NOT_API_REQUEST)
+
+ def testBuildRequestForSingleUpload(self):
+ """Test whether a single upload request is build correctly."""
+ with mock.patch('googleads.adwords.BatchJobHelper.'
+ '_UploadRequestBuilder.'
+ '_BuildUploadRequestBody') as mock_request_body_builder:
+ mock_request_body_builder.return_value = self.sample_xml
+ req = self.request_builder.BuildUploadRequest(self.upload_url, [[]],
+ is_last=True)
+ self.assertEqual(req.headers, self.single_upload_headers)
+ self.assertEqual(req.get_method(), 'PUT')
+
+ def testBuildRequestForIncrementalUpload(self):
+ """Test whether an incremental upload request is built correctly."""
+ with mock.patch('googleads.adwords.BatchJobHelper.'
+ '_UploadRequestBuilder.'
+ '_BuildUploadRequestBody') as mock_request_body_builder:
+ mock_request_body_builder.return_value = self.sample_xml
+ req = self.request_builder.BuildUploadRequest(
+ self.upload_url, [[]],
+ current_content_length=self.request_builder._BATCH_JOB_INCREMENT)
+ self.assertEqual(req.headers, self.incremental_upload_headers)
+ self.assertEqual(req.get_method(), 'PUT')
+
+ def testBuildUploadRequestBody(self):
+ """Test whether a a complete request body is built correctly."""
+ with mock.patch('googleads.adwords.BatchJobHelper.'
+ '_UploadRequestBuilder.'
+ '_GenerateOperationsXML') as mock_generate_xml:
+ mock_generate_xml.return_value = self.sample_xml
+ with mock.patch('googleads.adwords.BatchJobHelper._'
+ 'UploadRequestBuilder.'
+ '_GetPaddingLength') as mock_get_padding_length:
+ mock_get_padding_length.return_value = 0
+ increment = self.request_builder._BuildUploadRequestBody([[]])
+ self.assertTrue(increment == self.request_body_complete)
+
+ def testBuildUploadRequestBodyWithSuffix(self):
+ """Test whether a request body is built correctly with only the suffix."""
+ with mock.patch('googleads.adwords.BatchJobHelper.'
+ '_UploadRequestBuilder.'
+ '_GenerateOperationsXML') as mock_generate_xml:
+ mock_generate_xml.return_value = self.sample_xml
+ with mock.patch('googleads.adwords.BatchJobHelper.'
+ '_UploadRequestBuilder.'
+ '_GetPaddingLength') as mock_get_padding_length:
+ mock_get_padding_length.return_value = 0
+ increment = self.request_builder._BuildUploadRequestBody(
+ [[]], has_prefix=False)
+ self.assertTrue(increment == self.request_body_end)
+
+ def testBuildUploadRequestBodyWithoutPrefixOrSuffix(self):
+ """Test whether a request body is built correctly without prefix/suffix."""
+ with mock.patch('googleads.adwords.BatchJobHelper.'
+ '_UploadRequestBuilder.'
+ '_GenerateOperationsXML') as mock_generate_xml:
+ mock_generate_xml.return_value = self.sample_xml
+ with mock.patch('googleads.adwords.BatchJobHelper.'
+ '_UploadRequestBuilder.'
+ '_GetPaddingLength') as mock_get_padding_length:
+ mock_get_padding_length.return_value = 0
+ increment = self.request_builder._BuildUploadRequestBody(
+ [[]], has_prefix=False, has_suffix=False)
+ self.assertTrue(increment == self.sample_xml)
+
+ def testBuildUploadRequestBodyWithOnlyPrefix(self):
+ """Test whether a request body is built correctly with only the prefix."""
+ with mock.patch('googleads.adwords.BatchJobHelper.'
+ '_UploadRequestBuilder.'
+ '_GenerateOperationsXML') as mock_generate_xml:
+ mock_generate_xml.return_value = self.sample_xml
+ with mock.patch('googleads.adwords.BatchJobHelper.'
+ '_UploadRequestBuilder.'
+ '_GetPaddingLength') as mock_get_padding_length:
+ mock_get_padding_length.return_value = 0
+ increment = self.request_builder._BuildUploadRequestBody(
+ [[]], has_suffix=False)
+ self.assertTrue(increment == self.request_body_start)
+
+
+class IncrementalUploadHelperTest(testing.CleanUtilityRegistryTestCase):
+
+ """Test suite for the IncrementalUploadHelper."""
+
+ def GetIncrementalUploadHelper(self):
+ with mock.patch('urllib.request.OpenerDirector.open') as mock_open:
+ mock_open.return_value.headers = {'location': self.initialized_url}
+ return self.batch_job_helper.GetIncrementalUploadHelper(self.original_url)
+
+ def setUp(self):
+ """Prepare tests."""
+ self.client = GetAdWordsClient()
+ self.server = 'https://test.com'
+ self.version = 'test_version'
+ self.batch_job_helper = self.client.GetBatchJobHelper(
+ version=self.version, server=self.server)
+ self.original_url = 'https://goo.gl/w8tkpK'
+ self.initialized_url = 'https://goo.gl/Xtaq83'
+ self.incremental_uploader = self.GetIncrementalUploadHelper()
+
+ self.incremental_uploader_dump = (
+ '{current_content_length: 0, is_last: false, '
+ 'server: \'https://test.com\', upload_url: \'https://goo.gl/Xtaq83\','
+ 'version: %s}\n' % self.version)
+
+ def testDump(self):
+ expected = yaml.load(self.incremental_uploader_dump)
+
+ with tempfile.NamedTemporaryFile(delete=False, mode='w') as t:
+ name = t.name
+ self.incremental_uploader.Dump(t)
+
+ with open(name, mode='r') as handler:
+ dump_data = yaml.safe_load(handler)
+
+ self.assertEqual(expected, dump_data)
+
+ def testLoad(self):
+ s = io.StringIO(self.incremental_uploader_dump)
+
+ with mock.patch('urllib.request.OpenerDirector.open') as mock_open:
+ mock_open.return_value.headers = {
+ 'location': self.initialized_url
+ }
+ with mock.patch('googleads.adwords.IncrementalUploadHelper'
+ '._InitializeURL') as mock_init:
+ mock_init.return_value = self.initialized_url
+ restored_uploader = googleads.adwords.IncrementalUploadHelper.Load(
+ s, client=self.client)
+
+ self.assertEquals(restored_uploader._current_content_length,
+ self.incremental_uploader._current_content_length)
+ self.assertEquals(restored_uploader._is_last,
+ self.incremental_uploader._is_last)
+ self.assertEquals(restored_uploader._request_builder._version,
+ self.version)
+ self.assertEquals(restored_uploader._upload_url,
+ self.incremental_uploader._upload_url)
+ self.assertEquals(restored_uploader._request_builder.GetServer(),
+ self.server)
+
+ def testUploadOperations(self):
+ with mock.patch('googleads.adwords.BatchJobHelper.'
+ '_UploadRequestBuilder.'
+ 'BuildUploadRequest') as mock_build_request:
+ mock_request = mock.MagicMock()
+ mock_build_request.return_value = mock_request
+ with mock.patch('urllib.request.OpenerDirector.open') as mock_open:
+ self.incremental_uploader.UploadOperations([[]], True)
+ mock_open.assert_called_with(mock_request)
+
+ def testUploadOperationsWithError(self):
+ error_url = 'https://google.com/'
+ error_code = '404'
+ error_message = 'I AM ERROR'
+ error_headers = {}
+ http_error = HTTPError(
+ error_url, error_code, error_message, error_headers, None)
+
+ with mock.patch('googleads.adwords.BatchJobHelper.'
+ '_UploadRequestBuilder.'
+ 'BuildUploadRequest') as mock_build_request:
+ mock_request = mock.MagicMock()
+ mock_build_request.return_value = mock_request
+ with mock.patch('urllib.request.OpenerDirector.open') as mock_open:
+ mock_open.side_effect = http_error
+ self.assertRaises(
+ HTTPError,
+ self.incremental_uploader.UploadOperations, [[]], True)
+ mock_open.assert_called_with(mock_request)
+
+ def testUploadOperationsAfterFinished(self):
+ with mock.patch('googleads.adwords.BatchJobHelper.'
+ '_UploadRequestBuilder.'
+ 'BuildUploadRequest') as mock_build_request:
+ mock_request = mock.MagicMock()
+ mock_build_request.return_value = mock_request
+ with mock.patch('urllib.request.OpenerDirector.open'):
+ self.incremental_uploader.UploadOperations([[]], True)
+ self.assertRaises(
+ googleads.errors.AdWordsBatchJobServiceInvalidOperationError,
+ self.incremental_uploader.UploadOperations, {})
+
+ def testRequestHasCustomHeaders(self):
+ class MyOpener(object):
+ addheaders = [('a', 'b')]
+ opener = MyOpener()
+
+ with mock.patch('googleads.adwords.build_opener') as mock_build_opener,\
+ mock.patch('googleads.adwords.IncrementalUploadHelper._InitializeURL'):
+ mock_build_opener.return_value = opener
+ self.client.custom_http_headers = {'X-My-Headers': 'abc'}
+
+ self.GetIncrementalUploadHelper()
+
+ self.assertEqual(opener.addheaders, [('a', 'b'), ('X-My-Headers', 'abc')])
+
+
+class ResponseParserTest(testing.CleanUtilityRegistryTestCase):
+ """Test suite for the ResponseParser."""
+
+ def setUp(self):
+ """Prepare tests."""
+ self.client = GetAdWordsClient()
+ self.response_parser = googleads.adwords.BatchJobHelper.GetResponseParser()
+
+ @classmethod
+ def setUpClass(cls):
+ test_dir = os.path.dirname(__file__)
+ with open(os.path.join(
+ test_dir, 'test_data/batch_job_util_response_template.txt')) as handler:
+ cls.API_RESPONSE_XML_TEMPLATE = handler.read()
+
+ def testParseResponse(self):
+ campaign_id = '1'
+ name = 'Test Campaign'
+ status = 'PAUSED'
+ serving_status = 'SUSPENDED'
+ start_date = '20151116'
+ end_date = '20371230'
+ budget_id = '2'
+ budget_name = 'Test Budget'
+ micro_amount = '50000000'
+ delivery_method = 'STANDARD'
+ is_explicitly_shared = 'true'
+ bidding_strategy_type = 'MANUAL_CPC'
+
+ response = (
+ self.response_parser.ParseResponse(
+ self.API_RESPONSE_XML_TEMPLATE %
+ (campaign_id, name, status, serving_status, start_date, end_date,
+ budget_id, budget_name, micro_amount, delivery_method,
+ is_explicitly_shared, bidding_strategy_type))
+ ['mutateResponse']['rval'])
+
+ # Assert that we correct parsed the response (2 results: Budget & Campaign)
+ self.assertTrue(len(response) == 2)
+
+ campaign = response[1]['result']['Campaign']
+ self.assertTrue(campaign['id'] == campaign_id)
+ self.assertTrue(campaign['name'] == name)
+ self.assertTrue(campaign['status'] == status)
+ self.assertTrue(campaign['servingStatus'] == serving_status)
+ self.assertTrue(campaign['startDate'] == start_date)
+ self.assertTrue(campaign['endDate'] == end_date)
+ self.assertTrue(campaign['budget']['name'] == budget_name)
+ self.assertTrue(campaign['budget']['amount']['microAmount'] == micro_amount)
+ self.assertTrue(campaign['budget']['isExplicitlyShared'] ==
+ is_explicitly_shared)
+ self.assertTrue(
+ campaign['biddingStrategyConfiguration']['biddingStrategyType'] ==
+ bidding_strategy_type)
+
+ def testParseUnicodeResponse(self):
+ campaign_id = u'1'
+ name = u'アングリーバード'
+ status = u'PAUSED'
+ serving_status = u'SUSPENDED'
+ start_date = u'20151116'
+ end_date = u'20371230'
+ budget_id = u'2'
+ budget_name = u'Test Budget'
+ micro_amount = u'50000000'
+ delivery_method = u'STANDARD'
+ is_explicitly_shared = u'true'
+ bidding_strategy_type = u'MANUAL_CPC'
+
+ response = (
+ self.response_parser.ParseResponse(
+ self.API_RESPONSE_XML_TEMPLATE %
+ (campaign_id, name, status, serving_status, start_date, end_date,
+ budget_id, budget_name, micro_amount, delivery_method,
+ is_explicitly_shared, bidding_strategy_type))
+ ['mutateResponse']['rval'])
+
+ self.assertTrue(len(response) == 2)
+ campaign = response[1]['result']['Campaign']
+ self.assertTrue(campaign['name'] == name)
+
+
+def GetVersionedXSD(version):
+ report_xsd = os.path.join(
+ TEST_DIR, 'test_data/adwords_report_definition.xsd')
+
+ with open(report_xsd, 'rb') as f:
+ data = f.read()
+ return data.replace(b'{VERSION}', bytes(version, 'utf-8'))
+
+
+class ReportDownloaderZeepTest(testing.CleanUtilityRegistryTestCase):
+
+ def setUp(self):
+ self.version = CURRENT_VERSION
+ self.opener = mock.Mock()
+ self.adwords_client = mock.Mock()
+ self.adwords_client.proxy_config = GetProxyConfig()
+ self.adwords_client.cache = googleads.common.ZeepServiceProxy.NO_CACHE
+ self.adwords_client.custom_http_headers = False
+ self.header_handler = mock.Mock()
+
+ post_body_path = os.path.join(
+ TEST_DIR, 'test_data/adwords_report_post_body_no_formatting.txt')
+ with open(post_body_path, 'r') as f:
+ self.post_body_data = f.read().replace('{VERSION}', self.version)
+
+ class XSDTransport(zeep.transports.Transport):
+
+ def load(self, url):
+ return GetVersionedXSD(CURRENT_VERSION)
+
+ with mock.patch(
+ 'googleads.adwords._AdWordsHeaderHandler') as mock_handler:
+ mock_handler.return_value = self.header_handler
+
+ with mock.patch('googleads.common._ZeepProxyTransport') as mock_transport:
+ mock_transport.return_value = XSDTransport()
+
+ self.report_downloader = googleads.adwords.ReportDownloader(
+ self.adwords_client, self.version
+ )
+ self.report_downloader.url_opener = self.opener
+
+ @mock.patch('googleads.adwords._report_logger')
+ @mock.patch.object(googleads.adwords, 'Request')
+ def testDownloadReportWithZeep(self, mock_request, mock_logger):
+ mock_logger.isEnabledFor.return_value = True
+ output_file = io.StringIO()
+ report_definition = {
+ 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT',
+ 'dateRangeType': 'LAST_7_DAYS',
+ 'reportType': 'CRITERIA_PERFORMANCE_REPORT',
+ 'downloadFormat': 'CSV',
+ 'selector': {
+ 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType',
+ 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost']
+ }
+ }
+
+ with mock.patch.object(self.report_downloader,
+ '_header_handler') as mock_header_handler, \
+ (mock.patch.object(
+ self.report_downloader,
+ '_ExtractRequestSummaryFields')) as mock_extract_request_summary, \
+ (mock.patch.object(
+ self.report_downloader,
+ '_ExtractResponseHeaders')) as mock_extract_response_headers:
+ response_data = u'ABC 广告客户'
+ response_fp = io.BytesIO()
+ response_fp.write(bytes(response_data, 'utf-8'))
+ response_fp.seek(0)
+ mock_response = mock.Mock()
+ mock_response.read.side_effect = response_fp.read
+ mock_response.code = '200'
+ self.opener.open.return_value = mock_response
+
+ self.report_downloader.DownloadReport(report_definition, output_file,
+ skip_report_header=True,
+ use_raw_enum_values=False)
+
+ mock_request.assert_called_once_with(
+ self.report_downloader._end_point,
+ (bytes(self.post_body_data, 'utf-8')),
+ mock_header_handler.GetReportDownloadHeaders.return_value)
+
+ output_file.seek(0)
+ self.assertEqual(output_file.read(), response_data)
+ mock_extract_request_summary.assert_called_once_with(
+ mock_request.return_value)
+ mock_extract_response_headers.assert_called_once_with(
+ mock_response.headers)
+
+class ReportDownloaderTest(testing.CleanUtilityRegistryTestCase):
"""Tests for the googleads.adwords.ReportDownloader class."""
+ def GetReportDownloader(self):
+ with mock.patch(
+ 'googleads.adwords._AdWordsHeaderHandler') as mock_handler, \
+ mock.patch('googleads.adwords.googleads.common'
+ '.GetSchemaHelperForLibrary') as mock_get_schema:
+ mock_handler.return_value = self.header_handler
+ mock_get_schema.return_value = mock.Mock()
+
+ return googleads.adwords.ReportDownloader(
+ self.adwords_client, self.version)
+
def setUp(self):
self.version = CURRENT_VERSION
self.marshaller = mock.Mock()
self.header_handler = mock.Mock()
self.adwords_client = mock.Mock()
+ self.adwords_client.proxy_config = GetProxyConfig()
+ self.adwords_client.cache = googleads.common.ZeepServiceProxy.NO_CACHE
+ self.adwords_client.custom_http_headers = False
self.opener = mock.Mock()
- self.adwords_client.https_proxy = 'my.proxy.gov:443'
- with mock.patch('suds.client.Client'):
- with mock.patch('suds.xsd.doctor'):
- with mock.patch('suds.mx.literal.Literal') as mock_literal:
- with mock.patch(
- 'googleads.adwords._AdWordsHeaderHandler') as mock_handler:
- with mock.patch(
- URL_REQUEST_PATH + '.OpenerDirector') as mock_opener:
- mock_literal.return_value = self.marshaller
- mock_handler.return_value = self.header_handler
- mock_opener.return_value = self.opener
- self.report_downloader = googleads.adwords.ReportDownloader(
- self.adwords_client, self.version)
-
- def testDownloadReport(self):
- output_file = io.StringIO()
- report_definition = {'table': 'campaigns',
- 'downloadFormat': 'CSV'}
- serialized_report = 'nuinbwuign'
- post_body = urllib.urlencode({'__rdxml': serialized_report})
- if not PYTHON2:
- post_body = bytes(post_body, 'utf-8')
+
+ self.report_downloader = self.GetReportDownloader()
+ self.report_downloader.url_opener = self.opener
+
+ test_dir = os.path.dirname(__file__)
+ test_data_path = os.path.join(test_dir, 'test_data/unicode_test_data.txt')
+ with open(test_data_path, encoding='utf-8') as handler:
+ self.budget_template = handler.read()
+
+ def testSetsCustomHeaders(self):
+
+ class MyOpener(object):
+ addheaders = [('a', 'b')]
+ opener = MyOpener()
+ self.adwords_client.custom_http_headers = {'X-My-Header': 'abc'}
+
+ with mock.patch('googleads.adwords.build_opener') as mock_build_opener:
+ mock_build_opener.return_value = opener
+ self.GetReportDownloader()
+
+ self.assertEqual(opener.addheaders, [('a', 'b'), ('X-My-Header', 'abc')])
+
+ @mock.patch('urllib.request.OpenerDirector.open')
+ def testDownloadReportAsString(self, mock_request):
+ serialize_response = mock.Mock()
+ with mock.patch.object(
+ self.report_downloader,
+ '_DownloadReportAsStream') as mock_internal_download, \
+ mock.patch.object(
+ self.report_downloader,
+ '_SerializeReportDefinition') as mock_internal_serialize:
+ mock_internal_serialize.return_value = serialize_response
+
+ self.report_downloader.DownloadReportAsString(
+ 'report_definition',
+ some_arg='abc')
+
+ mock_internal_serialize.assert_called_once_with('report_definition')
+ mock_internal_download.assert_called_once_with(
+ serialize_response,
+ some_arg='abc')
+
+ def testDownloadReportAsStringWithAwql(self):
+ query = 'SELECT Id FROM Campaign WHERE NAME LIKE \'%Test%\''
+ file_format = 'CSV'
+ post_body = urlencode({'__fmt': file_format,
+ '__rdquery': query})
+ post_body = bytes(post_body, 'utf-8')
headers = {'Authorization': 'ya29.something'}
self.header_handler.GetReportDownloadHeaders.return_value = headers
- content = u'CONTENT STRING 广告客户'
- fake_request = io.StringIO() if PYTHON2 else io.BytesIO()
- fake_request.write(content if PYTHON2 else bytes(content, 'utf-8'))
- fake_request.seek(0)
- self.marshaller.process.return_value = serialized_report
-
- with mock.patch('suds.mx.Content') as mock_content:
- with mock.patch(URL_REQUEST_PATH + '.Request') as mock_request:
- self.opener.open.return_value = fake_request
- self.report_downloader.DownloadReport(report_definition, output_file)
- mock_request.assert_called_once_with(
- ('https://adwords.google.com/api/adwords/reportdownload/%s'
- % self.version), post_body, headers)
- self.opener.open.assert_called_once_with(mock_request.return_value)
- self.marshaller.process.assert_called_once_with(
- mock_content.return_value)
- self.assertEqual(content, output_file.getvalue())
- self.header_handler.GetReportDownloadHeaders.assert_called_once_with(
- None, None)
+ report_data = u'CONTENT STRING アングリーバード'
+ report_contents = io.BytesIO()
+ report_contents.write(bytes(report_data, 'utf-8'))
+ report_contents.seek(0)
+ fake_response = mock.Mock()
+ fake_response.read.side_effect = report_contents.read
+ fake_response.msg = 'fake message'
+ fake_response.code = '200'
+
+ with mock.patch.object(googleads.adwords, 'Request') as mock_request:
+ mock_request_instance = mock.Mock()
+ mock_request.return_value = mock_request_instance
+ mock_request_instance.get_full_url.return_value = 'https://google.com/'
+ mock_request_instance.headers = {}
+ self.opener.open.return_value = fake_response
+ s = self.report_downloader.DownloadReportAsStringWithAwql(
+ query, file_format, include_zero_impressions=True,
+ use_raw_enum_values=False)
+ mock_request.assert_called_once_with(
+ ('https://adwords.google.com/api/adwords/reportdownload/%s'
+ % self.version), post_body, headers)
+ self.opener.open.assert_called_once_with(mock_request.return_value)
+ self.assertEqual(report_data, s)
+ self.header_handler.GetReportDownloadHeaders.assert_called_once_with(
+ include_zero_impressions=True, use_raw_enum_values=False)
+
+ def testDownloadReportWithUnicodeReportDataIssue281(self):
+ """This test verifies that issue #281 has been resolved.
+
+ https://github.com/googleads/googleads-python-lib/issues/281
+
+ Intentionally reads in a lot of unicode data with small chunk size to
+ replicate issue where chunked data read in _DownloadReport on Python 3
+ would cause a UnicodeDecodeError if multi-byte character were truncated.
+ """
+ test_dir = os.path.dirname(__file__)
+ googleads.adwords._CHUNK_SIZE = 10 # Small chunk size used to replicate.
+
+ with mock.patch.object(self.report_downloader,
+ '_DownloadReportAsStream') as stream:
+ stream.return_value = open(os.path.join(
+ test_dir, 'test_data/unicode_test_data.txt'), 'rb')
+ report_definition = {'downloadFormat': 'CSV'}
+ s = io.StringIO()
+ self.report_downloader.DownloadReport(report_definition, output=s)
def testDownloadReportCheckFormat_CSVStringSuccess(self):
output_file = io.StringIO()
@@ -258,16 +1724,17 @@ def testDownloadReportCheckFormat_CSVStringSuccess(self):
'unexpectedly!')
def testDownloadReportCheckFormat_GZIPPEDBinaryFileSuccess(self):
- output_file = io.StringIO()
+ output_file = tempfile.TemporaryFile(mode='wb')
try:
- self.report_downloader._DownloadReportCheckFormat('CSV', output_file)
+ self.report_downloader._DownloadReportCheckFormat(
+ 'GZIPPED_CSV', output_file)
except googleads.errors.GoogleAdsValueError:
self.fail('_DownloadReportCheckFormat raised GoogleAdsValueError'
'unexpectedly!')
def testDownloadReportCheckFormat_GZIPPEDBytesIOSuccess(self):
- output_file = tempfile.TemporaryFile(mode='wb')
+ output_file = io.BytesIO()
try:
self.report_downloader._DownloadReportCheckFormat('GZIPPED_CSV',
@@ -278,63 +1745,65 @@ def testDownloadReportCheckFormat_GZIPPEDBytesIOSuccess(self):
def testDownloadReportCheckFormat_GZIPPEDStringFailure(self):
output_file = io.StringIO()
-
self.assertRaises(googleads.errors.GoogleAdsValueError,
self.report_downloader._DownloadReportCheckFormat,
'GZIPPED_CSV', output_file)
def testDownloadReport_failure(self):
output_file = io.StringIO()
- report_definition = {'table': 'campaigns',
- 'downloadFormat': 'CSV'}
- serialized_report = 'hjuibnibguo'
- post_body = urllib.urlencode({'__rdxml': serialized_report})
- if not PYTHON2:
- post_body = bytes(post_body, 'utf-8')
- headers = {'Authorization': 'ya29.something'}
- self.header_handler.GetReportDownloadHeaders.return_value = headers
- content = u'Page not found. :-('
- fake_request = io.StringIO() if PYTHON2 else io.BytesIO()
- fake_request.write(content if PYTHON2 else bytes(content, 'utf-8'))
- fake_request.seek(0)
- error = urllib2.HTTPError('', 400, 'Bad Request', {}, fp=fake_request)
+ report_definition = {
+ 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT',
+ 'dateRangeType': 'LAST_7_DAYS',
+ 'reportType': 'CRITERIA_PERFORMANCE_REPORT',
+ 'downloadFormat': 'CSV',
+ 'selector': {
+ 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType',
+ 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost']
+ }
+ }
- self.marshaller.process.return_value = serialized_report
+ with mock.patch.object(self.report_downloader.url_opener,
+ 'open') as mock_open:
+ response_data = 'bad stuff happened'
+ response_fp = io.BytesIO()
+ response_fp.write(bytes(response_data, 'utf-8'))
+ response_fp.seek(0)
- with mock.patch('suds.mx.Content') as mock_content:
- with mock.patch(URL_REQUEST_PATH + '.Request') as mock_request:
- self.opener.open.side_effect = error
- self.assertRaises(
- googleads.errors.AdWordsReportError,
- self.report_downloader.DownloadReport, report_definition,
- output_file)
-
- mock_request.assert_called_once_with(
- ('https://adwords.google.com/api/adwords/reportdownload/%s'
- % self.version), post_body, headers)
- self.opener.open.assert_called_once_with(mock_request.return_value)
- self.marshaller.process.assert_called_once_with(
- mock_content.return_value)
- self.assertEqual('', output_file.getvalue())
- self.header_handler.GetReportDownloadHeaders.assert_called_once_with(
- None, None)
+ mock_open.side_effect = HTTPError(
+ 'http://abc', '500', 'whoops!', {}, response_fp)
+ with mock.patch.object(self.report_downloader, '_header_handler'):
+ with self.assertRaises(googleads.errors.AdWordsReportError):
+ self.report_downloader.DownloadReport(report_definition, output_file,
+ skip_report_header=True,
+ use_raw_enum_values=False)
def testDownloadReportWithAwql(self):
output_file = io.StringIO()
- query = 'SELECT Id FROM Campaign WHERE NAME LIKE \'%Test%\''
+ query = (googleads.adwords.ReportQueryBuilder()
+ .Select('CampaignId').From('CAMPAIGN_PERFORMANCE_REPORT')
+ .Where('CampaignStatus').EqualTo('ENABLED')
+ .Build())
file_format = 'CSV'
- post_body = urllib.urlencode({'__fmt': file_format, '__rdquery': query})
- if not PYTHON2:
- post_body = bytes(post_body, 'utf-8')
+ post_body = urlencode({'__fmt': file_format,
+ '__rdquery': query})
+ post_body = bytes(post_body, 'utf-8')
headers = {'Authorization': 'ya29.something'}
self.header_handler.GetReportDownloadHeaders.return_value = headers
- content = u'CONTENT STRING'
- fake_request = io.StringIO() if PYTHON2 else io.BytesIO()
- fake_request.write(content if PYTHON2 else bytes(content, 'utf-8'))
- fake_request.seek(0)
+ report_data = u'CONTENT STRING 广告客户'
+ report_contents = io.BytesIO()
+ report_contents.write(bytes(report_data, 'utf-8'))
+ report_contents.seek(0)
+ fake_response = mock.Mock()
+ fake_response.read.side_effect = report_contents.read
+ fake_response.msg = 'fake message'
+ fake_response.code = '200'
- with mock.patch(URL_REQUEST_PATH + '.Request') as mock_request:
- self.opener.open.return_value = fake_request
+ with mock.patch.object(googleads.adwords, 'Request') as mock_request:
+ mock_request_instance = mock.Mock()
+ mock_request.return_value = mock_request_instance
+ mock_request_instance.get_full_url.return_value = 'https://google.com/'
+ mock_request_instance.headers = {}
+ self.opener.open.return_value = fake_response
self.report_downloader.DownloadReportWithAwql(
query, file_format, output_file)
@@ -343,40 +1812,8 @@ def testDownloadReportWithAwql(self):
% self.version), post_body, headers)
self.opener.open.assert_called_once_with(mock_request.return_value)
- self.assertEqual(content, output_file.getvalue())
- self.header_handler.GetReportDownloadHeaders.assert_called_once_with(
- None, None)
-
- def testDownloadReportWithBytesIO(self):
- output_file = io.BytesIO()
- report_definition = {'table': 'campaigns',
- 'downloadFormat': 'GZIPPED_CSV'}
- serialized_report = 'nuinbwuign'
- post_body = urllib.urlencode({'__rdxml': serialized_report})
- if not PYTHON2:
- post_body = bytes(post_body, 'utf-8')
- headers = {'Authorization': 'ya29.something'}
- self.header_handler.GetReportDownloadHeaders.return_value = headers
- content = u'CONTENT STRING 广告客户'
- fake_request = io.BytesIO()
- fake_request.write(content.encode('utf-8') if PYTHON2
- else bytes(content, 'utf-8'))
- fake_request.seek(0)
- self.marshaller.process.return_value = serialized_report
-
- with mock.patch('suds.mx.Content') as mock_content:
- with mock.patch(URL_REQUEST_PATH + '.Request') as mock_request:
- self.opener.open.return_value = fake_request
- self.report_downloader.DownloadReport(report_definition, output_file)
- mock_request.assert_called_once_with(
- ('https://adwords.google.com/api/adwords/reportdownload/%s'
- % self.version), post_body, headers)
- self.opener.open.assert_called_once_with(mock_request.return_value)
- self.marshaller.process.assert_called_once_with(
- mock_content.return_value)
- self.assertEqual(content, output_file.getvalue().decode('utf-8'))
- self.header_handler.GetReportDownloadHeaders.assert_called_once_with(
- None, None)
+ self.assertEqual(report_data, output_file.getvalue())
+ self.header_handler.GetReportDownloadHeaders.assert_called_once_with()
def testExtractError_badRequest(self):
response = mock.Mock()
@@ -384,13 +1821,15 @@ def testExtractError_badRequest(self):
type_ = 'ReportDownloadError.INVALID_REPORT_DEFINITION_XML'
trigger = 'Invalid enumeration.'
field_path = 'Criteria.Type'
- content_template = (
+ error_template = (
''
'%s%s'
'%s')
- content = content_template % (type_, trigger, field_path)
- response.read.return_value = (content if PYTHON2
- else bytes(content, 'utf-8'))
+ response_data = error_template % (type_, trigger, field_path)
+ response_fp = io.BytesIO()
+ response_fp.write(bytes(response_data, 'utf-8'))
+ response_fp.seek(0)
+ response.read.side_effect = response_fp.read
rval = self.report_downloader._ExtractError(response)
self.assertEqual(type_, rval.type)
@@ -398,13 +1837,15 @@ def testExtractError_badRequest(self):
self.assertEqual(field_path, rval.field_path)
self.assertEqual(response.code, rval.code)
self.assertEqual(response, rval.error)
- self.assertEqual(content, rval.content)
+ self.assertEqual(response_data, rval.content)
self.assertIsInstance(rval, googleads.errors.AdWordsReportBadRequestError)
# Check that if the XML fields are empty, this still functions.
- content = content_template % ('', '', '')
- response.read.return_value = (content if PYTHON2
- else bytes(content, 'utf-8'))
+ response_data = error_template % ('', '', '')
+ response_fp = io.BytesIO()
+ response_fp.write(bytes(response_data, 'utf-8'))
+ response_fp.seek(0)
+ response.read.side_effect = response_fp.read
rval = self.report_downloader._ExtractError(response)
self.assertEqual(None, rval.type)
self.assertEqual(None, rval.trigger)
@@ -413,24 +1854,26 @@ def testExtractError_badRequest(self):
def testExtractError_malformedBadRequest(self):
response = mock.Mock()
response.code = 400
- content = (''
- '12345678'
- '')
- response.read.return_value = (content if PYTHON2
- else bytes(content, 'utf-8'))
+ response_data = (''
+ '1234'
+ '5678'
+ '')
+ response_fp = io.BytesIO()
+ response_fp.write(bytes(response_data, 'utf-8'))
+ response_fp.seek(0)
+ response.read.side_effect = response_fp.read
rval = self.report_downloader._ExtractError(response)
self.assertEqual(response.code, rval.code)
self.assertEqual(response, rval.error)
- self.assertEqual(content, rval.content)
+ self.assertEqual(response_data, rval.content)
self.assertIsInstance(rval, googleads.errors.AdWordsReportError)
def testExtractError_notBadRequest(self):
response = mock.Mock()
response.code = 400
content = 'Page not found!'
- response.read.return_value = (content if PYTHON2
- else bytes(content, 'utf-8'))
+ response.read.return_value = (bytes(content, 'utf-8'))
rval = self.report_downloader._ExtractError(response)
self.assertEqual(response.code, rval.code)
@@ -438,6 +1881,471 @@ def testExtractError_notBadRequest(self):
self.assertEqual(content, rval.content)
self.assertIsInstance(rval, googleads.errors.AdWordsReportError)
+ def testSanitizeRequestHeaders(self):
+ redacted_text = 'REDACTED'
+ headers = {
+ 'foo': 'bar',
+ 'Developertoken': 'abc123doremi',
+ 'Authorization': 'Authorization',
+ 'lorem': 'ipsum'
+ }
+
+ sanitized_headers = self.report_downloader._SanitizeRequestHeaders(headers)
+
+ self.assertNotEqual(headers, sanitized_headers)
+ self.assertEqual(sanitized_headers['Developertoken'], redacted_text)
+ self.assertEqual(sanitized_headers['Authorization'], redacted_text)
+
+ def testExtractResponseHeaders(self):
+ headers = '\n\n\nfoo: bar\nlorem: ipsum\ntomayto: tomahto\n'
+ expected_headers = {
+ 'foo': 'bar',
+ 'lorem': 'ipsum',
+ 'tomayto': 'tomahto'
+ }
+
+ dict_headers = self.report_downloader._ExtractResponseHeaders(headers)
+
+ self.assertEqual(dict_headers, expected_headers)
+
+
+class QueryBuilderTest(testing.CleanUtilityRegistryTestCase):
+ """Tests for the googleads.adwords._QueryBuilder class."""
+
+ def testSelect(self):
+ with self.assertRaises(NotImplementedError):
+ googleads.adwords._QueryBuilder().Select()
+
+ def testFailUsingCopyConstructor(self):
+ with self.assertRaises(googleads.errors.GoogleAdsValueError):
+ (googleads.adwords
+ ._QueryBuilder('SELECT Id FROM CAMPAIGN_PERFORMANCE_REPORT'))
+
+
+class ReportQueryBuilderTest(testing.CleanUtilityRegistryTestCase):
+ """Tests for the googleads.adwords.ReportQueryBuilder class."""
+
+ def testCopyConstructor(self):
+ # Test using date range.
+ expected_awql = ('SELECT CampaignId, CampaignName FROM'
+ ' CAMPAIGN_PERFORMANCE_REPORT'
+ ' WHERE CampaignStatus = "ENABLED" DURING YESTERDAY')
+ previous_query_builder = (googleads.adwords.ReportQueryBuilder()
+ .Select('CampaignId', 'CampaignName')
+ .From('CAMPAIGN_PERFORMANCE_REPORT')
+ .Where('CampaignStatus').EqualTo('ENABLED')
+ .During('YESTERDAY'))
+ actual_query = (googleads.adwords.ReportQueryBuilder(previous_query_builder)
+ .Build())
+ self.assertEqual(expected_awql, str(actual_query))
+
+ # Test using start and end dates.
+ expected_awql = ('SELECT CampaignId, CampaignName FROM'
+ ' CAMPAIGN_PERFORMANCE_REPORT'
+ ' WHERE CampaignStatus = "ENABLED"'
+ ' DURING 20170101,20170131')
+ previous_query_builder = (googleads.adwords.ReportQueryBuilder()
+ .Select('CampaignId', 'CampaignName')
+ .From('CAMPAIGN_PERFORMANCE_REPORT')
+ .Where('CampaignStatus').EqualTo('ENABLED')
+ .During(start_date='20170101',
+ end_date='20170131'))
+ actual_query = (googleads.adwords.ReportQueryBuilder(previous_query_builder)
+ .Build())
+ self.assertEqual(expected_awql, str(actual_query))
+
+ def testFailUsingCopyConstructor(self):
+ builder = googleads.adwords._QueryBuilder()
+ builder.select = 'Id'
+ with self.assertRaises(googleads.errors.GoogleAdsValueError):
+ googleads.adwords.ReportQueryBuilder(builder)
+
+ def testBuild(self):
+ expected_awql = ('SELECT CampaignId, CampaignName FROM'
+ ' CAMPAIGN_PERFORMANCE_REPORT')
+ actual_query = (googleads.adwords.ReportQueryBuilder()
+ .Select('CampaignId', 'CampaignName')
+ .From('CAMPAIGN_PERFORMANCE_REPORT')
+ .Build())
+ self.assertEqual(expected_awql, str(actual_query))
+
+ def testBuild_stringWhereValue(self):
+ expected_awql = ('SELECT CampaignId, CampaignName FROM'
+ ' CAMPAIGN_PERFORMANCE_REPORT'
+ ' WHERE CampaignStatus = "ENABLED" DURING YESTERDAY')
+ actual_query = (googleads.adwords.ReportQueryBuilder()
+ .Select('CampaignId', 'CampaignName')
+ .From('CAMPAIGN_PERFORMANCE_REPORT')
+ .Where('CampaignStatus').EqualTo('ENABLED')
+ .During('YESTERDAY')
+ .Build())
+ self.assertEqual(expected_awql, str(actual_query))
+
+ def testBuild_numericWhereValue(self):
+ expected_awql = ('SELECT CampaignId, CampaignName FROM'
+ ' ADGROUP_PERFORMANCE_REPORT'
+ ' WHERE AverageCpm >= 5.6 DURING TODAY')
+ actual_query = (googleads.adwords.ReportQueryBuilder()
+ .Select('CampaignId', 'CampaignName')
+ .From('ADGROUP_PERFORMANCE_REPORT')
+ .Where('AverageCpm').GreaterThanOrEqualTo(5.6)
+ .During('TODAY')
+ .Build())
+ self.assertEqual(expected_awql, str(actual_query))
+
+ def testBuild_multipleStringWhereValues(self):
+ expected_awql = ('SELECT Id, CampaignId, CampaignName FROM'
+ ' AD_PERFORMANCE_REPORT'
+ ' WHERE CampaignName CONTAINS_ALL ["white", "black"]'
+ ' DURING LAST_WEEK')
+ actual_query = (googleads.adwords.ReportQueryBuilder()
+ .Select('Id', 'CampaignId', 'CampaignName')
+ .From('AD_PERFORMANCE_REPORT')
+ .Where('CampaignName').ContainsAll('white', 'black')
+ .During('LAST_WEEK')
+ .Build())
+ self.assertEqual(expected_awql, str(actual_query))
+
+ def testBuild_multipleNumericWhereValues(self):
+ expected_awql = ('SELECT Id, CampaignId, CampaignName FROM'
+ ' AD_PERFORMANCE_REPORT'
+ ' WHERE CampaignId IN [1234, 5678] DURING LAST_WEEK')
+ actual_query = (googleads.adwords.ReportQueryBuilder()
+ .Select('Id', 'CampaignId', 'CampaignName')
+ .From('AD_PERFORMANCE_REPORT')
+ .Where('CampaignId').In(1234, 5678)
+ .During('LAST_WEEK')
+ .Build())
+ self.assertEqual(expected_awql, str(actual_query))
+
+ def testBuild_multipleWhereConditions(self):
+ expected_awql = ('SELECT CampaignId, CampaignName FROM'
+ ' ADGROUP_PERFORMANCE_REPORT'
+ ' WHERE Clicks >= 500 AND CampaignName'
+ ' CONTAINS_IGNORE_CASE "promotion"'
+ ' AND AdGroupName STARTS_WITH "adwords_"'
+ ' AND BiddingStrategyName STARTS_WITH_IGNORE_CASE "europe"'
+ ' AND CustomerDescriptiveName CONTAINS "goog"'
+ ' AND CustomerDescriptiveName DOES_NOT_CONTAIN "asia"'
+ ' AND AccountDescriptiveName DOES_NOT_CONTAIN_IGNORE_CASE'
+ ' "group 3" AND CampaignStatus != "REMOVED"'
+ ' AND AdGroupStatus NOT_IN ["REMOVED", "PAUSED"]'
+ ' AND AdNetworkType1 CONTAINS_ANY ["SEARCH", "DISPLAY"]'
+ ' AND AdNetworkType2 CONTAINS_NONE'
+ ' ["YOUTUBE_SEARCH", "UNKNOWN"] AND AverageCpv > 20.7'
+ ' AND AllConversions < 100.6'
+ ' DURING 20170601,20170630')
+ actual_query = (googleads.adwords.ReportQueryBuilder()
+ .Select('CampaignId', 'CampaignName')
+ .From('ADGROUP_PERFORMANCE_REPORT')
+ .Where('Clicks').GreaterThanOrEqualTo(500)
+ .Where('CampaignName').ContainsIgnoreCase('promotion')
+ .Where('AdGroupName').StartsWith('adwords_')
+ .Where('BiddingStrategyName').StartsWithIgnoreCase('europe')
+ .Where('CustomerDescriptiveName').Contains('goog')
+ .Where('CustomerDescriptiveName').DoesNotContain('asia')
+ .Where('AccountDescriptiveName').DoesNotContainIgnoreCase(
+ 'group 3')
+ .Where('CampaignStatus').NotEqualTo('REMOVED')
+ .Where('AdGroupStatus').NotIn('REMOVED', 'PAUSED')
+ .Where('AdNetworkType1').ContainsAny('SEARCH', 'DISPLAY')
+ .Where('AdNetworkType2').ContainsNone('YOUTUBE_SEARCH',
+ 'UNKNOWN')
+ .Where('AverageCpv').GreaterThan(20.7)
+ .Where('AllConversions').LessThan(100.6)
+ .During(start_date='20170601', end_date='20170630')
+ .Build())
+ self.assertEqual(expected_awql, str(actual_query))
+
+ def testBuild_noWhereClause(self):
+ expected_awql = ('SELECT CampaignId, CampaignName FROM'
+ ' ADGROUP_PERFORMANCE_REPORT DURING TODAY')
+ actual_query = (googleads.adwords.ReportQueryBuilder()
+ .Select('CampaignId', 'CampaignName')
+ .From('ADGROUP_PERFORMANCE_REPORT')
+ .During('TODAY')
+ .Build())
+ self.assertEqual(expected_awql, str(actual_query))
+
+ def testBuild_noDuringClause(self):
+ expected_awql = ('SELECT CampaignId, CampaignName FROM'
+ ' ADGROUP_PERFORMANCE_REPORT'
+ ' WHERE Clicks <= 500')
+ actual_query = (googleads.adwords.ReportQueryBuilder()
+ .Select('CampaignId', 'CampaignName')
+ .From('ADGROUP_PERFORMANCE_REPORT')
+ .Where('Clicks').LessThanOrEqualTo(500)
+ .Build())
+ self.assertEqual(expected_awql, str(actual_query))
+
+ def testBuild_selectIsNone(self):
+ with self.assertRaises(ValueError):
+ googleads.adwords.ReportQueryBuilder().Build()
+
+ def testBuild_fromIsNone(self):
+ with self.assertRaises(ValueError):
+ googleads.adwords.ReportQueryBuilder().Select('Id').Build()
+
+ def testDuring_usingPythonDateTime(self):
+ expected_awql = ('SELECT CampaignId, CampaignName FROM'
+ ' CAMPAIGN_PERFORMANCE_REPORT'
+ ' WHERE CampaignStatus = "ENABLED"'
+ ' DURING 20170501,20170531')
+ start_date = datetime.date(2017, 5, 1)
+ end_date = start_date + datetime.timedelta(days=30)
+ actual_query = (googleads.adwords.ReportQueryBuilder()
+ .Select('CampaignId', 'CampaignName')
+ .From('CAMPAIGN_PERFORMANCE_REPORT')
+ .Where('CampaignStatus').EqualTo('ENABLED')
+ .During(start_date=start_date, end_date=end_date)
+ .Build())
+ self.assertEqual(expected_awql, str(actual_query))
+
+ def testDuring_allParametersNone(self):
+ with self.assertRaises(ValueError):
+ googleads.adwords.ReportQueryBuilder().During()
+
+ def testDuring_allParametersNotNone(self):
+ with self.assertRaises(ValueError):
+ googleads.adwords.ReportQueryBuilder().During('TODAY', '20170101',
+ '20170131')
+
+ def testDuring_startOrEndDateNone(self):
+ with self.assertRaises(ValueError):
+ googleads.adwords.ReportQueryBuilder().During(start_date='20170101')
+ with self.assertRaises(ValueError):
+ googleads.adwords.ReportQueryBuilder().During(end_date='20170131')
+
+
+class ServiceQueryBuilderTest(testing.CleanUtilityRegistryTestCase):
+ """Tests for the googleads.adwords.ServiceQueryBuilder class."""
+
+ def testCopyConstructor(self):
+ awql_regex = (r'SELECT (.*) WHERE Status = "ENABLED"'
+ r' ORDER BY Name ASC LIMIT 0,100')
+ selected_fields = ['Id', 'Name']
+ previous_query_builder = (googleads.adwords.ServiceQueryBuilder()
+ .Select(*selected_fields)
+ .Where('Status').EqualTo('ENABLED')
+ .OrderBy('Name')
+ .Limit(0, 100))
+
+ actual_query = googleads.adwords.ServiceQueryBuilder(
+ previous_query_builder).Build()
+ match = re.match(awql_regex, str(actual_query))
+
+ # The SELECT clause can show fields listed in any orders.
+ self.assertCountEqual(selected_fields,
+ [field.strip() for field in match.group(1).split(',')])
+ self.assertRegexpMatches(str(actual_query), awql_regex)
+
+ def testFailUsingCopyConstructor(self):
+ builder = googleads.adwords._QueryBuilder()
+ builder.select = 'Id'
+ with self.assertRaises(googleads.errors.GoogleAdsValueError):
+ googleads.adwords.ServiceQueryBuilder(builder)
+
+ def testBuild(self):
+ awql_regex = (r'SELECT (.*) LIMIT 0,100')
+ selected_fields = ['Id', 'Name']
+ actual_query = (googleads.adwords.ServiceQueryBuilder()
+ .Select(*selected_fields)
+ .Limit(0, 100)
+ .Build())
+ match = re.match(awql_regex, str(actual_query))
+
+ # The SELECT clause can show fields listed in any orders.
+ self.assertCountEqual(selected_fields,
+ [field.strip() for field in match.group(1).split(',')])
+ self.assertRegexpMatches(str(actual_query), awql_regex)
+
+ def testBuild_duplicateSelectedFieldsRetainOnlyUnique(self):
+ awql_regex = (r'SELECT (.*) LIMIT 0,100')
+ selected_fields = ['Id', 'Name', 'Name']
+ actual_query = (googleads.adwords.ServiceQueryBuilder()
+ .Select(*selected_fields)
+ .Limit(0, 100)
+ .Build())
+ match = re.match(awql_regex, str(actual_query))
+
+ # The SELECT clause retains only unique fields.
+ self.assertCountEqual(set(selected_fields),
+ [field.strip() for field in match.group(1).split(',')])
+ self.assertRegexpMatches(str(actual_query), awql_regex)
+
+ def testBuild_whereConditions(self):
+ awql_regex = (r'SELECT (.*)'
+ r' WHERE Name CONTAINS_IGNORE_CASE "promotion"'
+ r' AND Status NOT_IN \["REMOVED", "PAUSED"\]'
+ r' ORDER BY Name ASC'
+ r' LIMIT 100,100')
+ selected_fields = ['Id', 'Name', 'Status']
+ actual_query = (googleads.adwords.ServiceQueryBuilder()
+ .Select(*selected_fields)
+ .Where('Name').ContainsIgnoreCase('promotion')
+ .Where('Status').NotIn('REMOVED', 'PAUSED')
+ .OrderBy('Name')
+ .Limit(100, 100)
+ .Build())
+ match = re.match(awql_regex, str(actual_query))
+
+ # The SELECT clause can show fields listed in any orders.
+ self.assertCountEqual(selected_fields,
+ [field.strip() for field in match.group(1).split(',')])
+ self.assertRegexpMatches(str(actual_query), awql_regex)
+
+ def testBuild_orderByDesc(self):
+ awql_regex = (r'SELECT (.*)'
+ r' ORDER BY Name DESC'
+ r' LIMIT 100,100')
+ selected_fields = ['Id', 'Name', 'Status']
+ actual_query = (googleads.adwords.ServiceQueryBuilder()
+ .Select(*selected_fields)
+ .OrderBy('Name', ascending=False)
+ .Limit(100, 100)
+ .Build())
+ match = re.match(awql_regex, str(actual_query))
+
+ # The SELECT clause can show fields listed in any orders.
+ self.assertCountEqual(selected_fields,
+ [field.strip() for field in match.group(1).split(',')])
+ self.assertRegexpMatches(str(actual_query), awql_regex)
+
+ def testBuild_selectIsNone(self):
+ with self.assertRaises(ValueError):
+ googleads.adwords.ServiceQueryBuilder().Build()
+
+ def testBuild_limitStartIndexOrPageSizeIsNoneButNotTheOther(self):
+ # A page size is not specified.
+ with self.assertRaises(ValueError):
+ (googleads.adwords.ServiceQueryBuilder()
+ .Select('Id')
+ .OrderBy('Name', ascending=False)
+ .Limit(100, None)
+ .Build())
+ # A start index is not specified.
+ with self.assertRaises(ValueError):
+ (googleads.adwords.ServiceQueryBuilder()
+ .Select('Id')
+ .OrderBy('Name', ascending=False)
+ .Limit(None, 100)
+ .Build())
+
+
+class ServiceQueryTest(testing.CleanUtilityRegistryTestCase):
+ """Tests for the googleads.adwords.ServiceQuery class."""
+
+ def testNextPage(self):
+ selected_fields = ['Id', 'Name']
+ actual_query = (googleads.adwords.ServiceQueryBuilder()
+ .Select(*selected_fields)
+ .Limit(0, 100)
+ .Build())
+ # Do next page and check if the LIMIT clause is modified correctly.
+ awql_regex = (r'SELECT (.*) LIMIT 100,100')
+ actual_query.NextPage()
+ self.assertRegexpMatches(str(actual_query), awql_regex)
+
+ def testNextPageForDataService(self):
+ selected_fields = ['Id', 'Name']
+ actual_query = (
+ googleads.adwords.ServiceQueryBuilder().Select(*selected_fields).Limit(
+ 0, 2).Build())
+ page = {
+ 'totalNumEntries': 3,
+ 'Page.Type': 'CriterionBidLandscapePage',
+ 'entries': [{
+ 'landscapePoints': ['fakePoint1', 'fakePoint2']
+ }, {
+ 'landscapePoints': ['fakePoint3', 'fakePoint4']
+ }]
+ }
+
+ # The LIMIT clause should be incremented by the number of bid landscape
+ # points of the page.
+ awql_regex = (r'SELECT (.*) LIMIT 4,2')
+ actual_query.NextPage(page)
+ self.assertRegexpMatches(str(actual_query), awql_regex)
+
+ def testNextPageFail(self):
+ actual_query = googleads.adwords.ServiceQuery('SELECT Id, Name', None, 100)
+
+ with self.assertRaises(ValueError):
+ actual_query.NextPage()
+
+ def testHasNext(self):
+ selected_fields = ['Id', 'Name']
+ actual_query = (googleads.adwords.ServiceQueryBuilder()
+ .Select(*selected_fields)
+ .Limit(0, 1)
+ .Build())
+ awql_regex = (r'SELECT (.*) LIMIT 0,1')
+ self.assertRegexpMatches(str(actual_query), awql_regex)
+
+ page = {'totalNumEntries': 3}
+
+ self.assertTrue(actual_query.HasNext(page))
+ awql_regex = (r'SELECT (.*) LIMIT 1,1')
+ actual_query.NextPage()
+ self.assertRegexpMatches(str(actual_query), awql_regex)
+
+ self.assertTrue(actual_query.HasNext(page))
+ awql_regex = (r'SELECT (.*) LIMIT 2,1')
+ actual_query.NextPage()
+ self.assertRegexpMatches(str(actual_query), awql_regex)
+
+ self.assertFalse(actual_query.HasNext(page))
+
+ def testHasNextForDataService(self):
+ page = {
+ 'totalNumEntries': 3,
+ 'Page.Type': 'AdGroupBidLandscapePage',
+ 'entries': [{
+ 'landscapePoints': ['fakePoint1', 'fakePoint2']
+ }, {
+ 'landscapePoints': ['fakePoint3', 'fakePoint4']
+ }]
+ }
+ selected_fields = ['Id', 'Name']
+ page_size = 2
+ actual_query = (
+ googleads.adwords.ServiceQueryBuilder().Select(*selected_fields).Limit(
+ 0, page_size).Build())
+ # 2 * 2 landscape points are greater than page_size.
+ self.assertTrue(actual_query.HasNext(page))
+
+ page_size = 10
+ actual_query = (
+ googleads.adwords.ServiceQueryBuilder().Select(*selected_fields).Limit(
+ 0, page_size).Build())
+ # 2 * 2 landscape points are less than page_size.
+ self.assertFalse(actual_query.HasNext(page))
+
+ def testHasNextFail(self):
+ actual_query = googleads.adwords.ServiceQuery('SELECT Id, Name', None, 100)
+
+ page = {'totalNumEntries': 10}
+ with self.assertRaises(ValueError):
+ actual_query.HasNext(page)
+
+ def testPager(self):
+ fake_page = {'totalNumEntries': 3}
+ service = mock.Mock()
+ service.query.return_value = fake_page
+
+ query = (googleads.adwords.ServiceQueryBuilder()
+ .Select('Id', 'Name')
+ .Limit(0, 1)
+ .Build())
+ i = 0
+ for page in query.Pager(service):
+ self.assertEqual(fake_page['totalNumEntries'],
+ page['totalNumEntries'])
+ i += 1
+ # Pager should return the number of page equal to the 'totalNumEntries'
+ # returned by a service.
+ self.assertEqual(fake_page['totalNumEntries'], i)
+
if __name__ == '__main__':
unittest.main()
diff --git a/tests/common_test.py b/tests/common_test.py
old mode 100755
new mode 100644
index 4c2c8c75..38f9e519
--- a/tests/common_test.py
+++ b/tests/common_test.py
@@ -1,5 +1,3 @@
-#!/usr/bin/python
-#
# Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -16,45 +14,98 @@
"""Unit tests to cover the common module."""
-__author__ = 'Joseph DiLallo'
+from contextlib import contextmanager
+import numbers
+import os
+import ssl
import unittest
import warnings
-import fake_filesystem
-import fake_tempfile
+from pyfakefs import fake_filesystem
+from pyfakefs import fake_tempfile
import mock
-import suds
+import requests.exceptions
import yaml
+import zeep.cache
import googleads.common
import googleads.errors
+import googleads.oauth2
+from . import testing
+import zeep.exceptions
+
+TEST_DIR = os.path.dirname(__file__)
+CURRENT_VERSION = 'v202208'
-class CommonTest(unittest.TestCase):
+
+class CommonTest(testing.CleanUtilityRegistryTestCase):
"""Tests for the googleads.common module."""
- # A dictionary with all the required OAuth 2.0 keys
- _OAUTH_DICT = {'client_id': 'a', 'client_secret': 'b', 'refresh_token': 'c'}
+ # Dictionaries with all the required OAuth2 keys
+ _OAUTH_INSTALLED_APP_DICT = {'client_id': 'a', 'client_secret': 'b',
+ 'refresh_token': 'c'}
+ _OAUTH_SERVICE_ACCT_DICT = {
+ 'path_to_private_key_file': '/test/test.json',
+ 'delegated_account': 'delegated_account@example.com'}
def setUp(self):
self.filesystem = fake_filesystem.FakeFilesystem()
self.tempfile = fake_tempfile.FakeTempfileModule(self.filesystem)
self.fake_open = fake_filesystem.FakeFileOpen(self.filesystem)
- self.fake_proxy = mock.Mock()
- self.fake_proxy.return_value = mock.Mock()
- self.fake_proxy.return_value.proxy_host = 'ahost'
- self.fake_proxy.return_value.proxy_port = 'aport'
+ self.uri1 = 'http://h1:1'
+ self.uri1_w_creds = 'http://username:password@h1:1'
+ self.uri2 = 'http://h2:2'
+ self.uplink_uri = 'http://127.0.0.1:999'
+ self.test1_name = 'Test1'
+ self.test2_name = 'Test2'
+ self.test2_version = 'testing'
+ self.fake_version = 'ignored'
+ locale_patcher = mock.patch('googleads.common.locale.getdefaultlocale',
+ return_value=('en_us', 'UTF-8'))
+ self.locale_patcher = locale_patcher.start()
+
+ @googleads.common.RegisterUtility(self.test1_name)
+ class Test1(object):
+
+ def test(self):
+ pass
+
+ @googleads.common.RegisterUtility(self.test2_name,
+ {'test': self.test2_version})
+ class Test2(object):
+
+ def test(self):
+ pass
- def _CreateYamlFile(self, data, insert_oauth2_key=None):
+ self.test1 = Test1
+ self.test2 = Test2
+
+ def tearDown(self):
+ super(CommonTest, self).tearDown()
+ self.locale_patcher.stop()
+
+ def testShouldWarnWithBadEncoding(self):
+ self.locale_patcher.return_value = (None, None)
+ test_major_value = 2
+ test_minor_value = 6
+ test_micro_value = 9
+ with mock.patch('googleads.common._PY_VERSION_MAJOR', test_major_value):
+ with mock.patch('googleads.common._PY_VERSION_MINOR', test_minor_value):
+ with mock.patch('googleads.common._PY_VERSION_MICRO', test_micro_value):
+ with mock.patch('googleads.common._logger') as mock_logger:
+ googleads.common.CommonClient()
+ mock_logger.warn.assert_called_once()
+
+ def _CreateYamlFile(self, data, insert_oauth2_key=None, oauth_dict=None):
"""Return the filename of a yaml file created for testing."""
yaml_file = self.tempfile.NamedTemporaryFile(delete=False)
-
with self.fake_open(yaml_file.name, 'w') as yaml_handle:
for key in data:
if key is insert_oauth2_key:
- data[key].update(self._OAUTH_DICT)
- yaml_handle.write(yaml.dump({key: data[key]}))
+ data[key].update(oauth_dict)
+ yaml_handle.write(yaml.dump(data))
return yaml_file.name
@@ -65,61 +116,19 @@ def testLoadFromStorage_missingFile(self):
googleads.common.LoadFromStorage,
'yaml_filename', 'woo', [], [])
- def testLoadFromStorage_missingOAuthKey(self):
- yaml_fname = self._CreateYamlFile({'woo': {}})
- with mock.patch('googleads.common.open', self.fake_open, create=True):
- self.assertRaises(
- googleads.errors.GoogleAdsValueError,
- googleads.common.LoadFromStorage,
- yaml_fname, 'woo', [], [])
-
- def testLoadFromStorage_passesWithNoRequiredKeys(self):
- yaml_fname = self._CreateYamlFile({'woo': {}}, 'woo')
- with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client:
- with mock.patch('googleads.common.open', self.fake_open, create=True):
- rval = googleads.common.LoadFromStorage(yaml_fname, 'woo', [], [])
- mock_client.assert_called_once_with('a', 'b', 'c', None, True, None)
- self.assertEqual({'oauth2_client': mock_client.return_value,
- 'https_proxy': None}, rval)
-
- def testLoadFromStorage_passesWithProxy(self):
- yaml_fname = self._CreateYamlFile({'adwords': {},
- 'proxy_info': {
- 'host': 'ahost',
- 'port': 'aport'
- }}, 'adwords')
- with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client:
- with mock.patch('googleads.common.open', self.fake_open, create=True):
- with mock.patch('httplib2.ProxyInfo', self.fake_proxy):
- rval = googleads.common.LoadFromStorage(yaml_fname, 'adwords', [], [])
- mock_client.assert_called_once_with('a', 'b', 'c',
- self.fake_proxy.return_value,
- True, None)
- self.assertEqual({'oauth2_client': mock_client.return_value,
- 'https_proxy': 'ahost:aport'}, rval)
-
- def testLoadFromStorage_failsWithMisconfiguredProxy(self):
- yaml_fname = self._CreateYamlFile({'adwords': {},
- 'proxy_info': {'host': 'ahost'}},
- 'adwords')
- with mock.patch('googleads.oauth2.GoogleRefreshTokenClient'):
- with mock.patch('googleads.common.open', self.fake_open, create=True):
- with mock.patch('httplib2.ProxyInfo', self.fake_proxy):
- self.assertRaises(googleads.errors.GoogleAdsValueError,
- googleads.common.LoadFromStorage,
- yaml_fname, 'adwords', [], [])
-
def testLoadFromStorage_missingRequiredKey(self):
with mock.patch('googleads.common.open', self.fake_open, create=True):
# Both keys are missing.
- yaml_fname = self._CreateYamlFile({'two': {}}, 'two')
+ yaml_fname = self._CreateYamlFile({'two': {}}, 'two',
+ self._OAUTH_INSTALLED_APP_DICT)
self.assertRaises(
googleads.errors.GoogleAdsValueError,
googleads.common.LoadFromStorage,
yaml_fname, 'two', ['needed', 'keys'], [])
# One key is missing.
- yaml_fname = self._CreateYamlFile({'three': {'needed': 'd'}}, 'three')
+ yaml_fname = self._CreateYamlFile({'three': {'needed': 'd'}}, 'three',
+ self._OAUTH_INSTALLED_APP_DICT)
self.assertRaises(
googleads.errors.GoogleAdsValueError,
googleads.common.LoadFromStorage,
@@ -127,33 +136,61 @@ def testLoadFromStorage_missingRequiredKey(self):
def testLoadFromStorage(self):
# No optional keys present.
- yaml_fname = self._CreateYamlFile({'one': {'needed': 'd', 'keys': 'e'}},
- 'one')
+ yaml_fname = self._CreateYamlFile(
+ {'one': {'needed': 'd', 'keys': 'e'}}, 'one',
+ self._OAUTH_INSTALLED_APP_DICT)
with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client:
with mock.patch('googleads.common.open', self.fake_open, create=True):
- rval = googleads.common.LoadFromStorage(
- yaml_fname, 'one', ['needed', 'keys'], ['other'])
- mock_client.assert_called_once_with('a', 'b', 'c', None, True, None)
- self.assertEqual({'oauth2_client': mock_client.return_value,
- 'needed': 'd', 'keys': 'e',
- 'https_proxy': None}, rval)
+ with mock.patch('googleads.common.ProxyConfig') as proxy_config:
+ proxy_config.return_value = mock.Mock()
+ rval = googleads.common.LoadFromStorage(
+ yaml_fname, 'one', ['needed', 'keys'], ['other'])
+ proxy_config.assert_called_once_with(
+ http_proxy=None, https_proxy=None, cafile=None,
+ disable_certificate_validation=False)
+ mock_client.assert_called_once_with(
+ 'a', 'b', 'c', proxy_config=proxy_config.return_value)
+ self.assertEqual({'oauth2_client': mock_client.return_value,
+ 'needed': 'd', 'keys': 'e',
+ 'proxy_config': proxy_config.return_value,
+ googleads.common.ENABLE_COMPRESSION_KEY: False,
+ googleads.common.CUSTOM_HEADERS_KEY: None},
+ rval)
+ self.assertTrue(googleads.common._utility_registry._enabled)
- # The optional key is present.
- yaml_fname = self._CreateYamlFile({'one': {'needed': 'd', 'keys': 'e',
- 'other': 'f'}}, 'one')
+ # Optional keys present
+ logging_config = {'foo': 'bar'}
+ yaml_fname = self._CreateYamlFile(
+ {'one': {'needed': 'd', 'keys': 'e', 'other': 'f'},
+ googleads.common._LOGGING_KEY: logging_config,
+ googleads.common.CUSTOM_HEADERS_KEY: {'X-My-Header': 'abc'}},
+ 'one', self._OAUTH_INSTALLED_APP_DICT)
with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client:
with mock.patch('googleads.common.open', self.fake_open, create=True):
- rval = googleads.common.LoadFromStorage(
- yaml_fname, 'one', ['needed', 'keys'], ['other'])
- mock_client.assert_called_once_with('a', 'b', 'c', None, True, None)
- self.assertEqual({'oauth2_client': mock_client.return_value,
- 'needed': 'd', 'keys': 'e', 'other': 'f',
- 'https_proxy': None}, rval)
+ with mock.patch('googleads.common.ProxyConfig') as proxy_config:
+ with mock.patch('logging.config.dictConfig') as mock_dict_config:
+ proxy_config.return_value = mock.Mock()
+ rval = googleads.common.LoadFromStorage(
+ yaml_fname, 'one', ['needed', 'keys'], ['other'])
+ proxy_config.assert_called_once_with(
+ http_proxy=None, https_proxy=None, cafile=None,
+ disable_certificate_validation=False)
+ mock_client.assert_called_once_with(
+ 'a', 'b', 'c', proxy_config=proxy_config.return_value)
+ mock_dict_config.assert_called_once_with(logging_config)
+ self.assertEqual({'oauth2_client': mock_client.return_value,
+ 'needed': 'd', 'keys': 'e', 'other': 'f',
+ 'proxy_config': proxy_config.return_value,
+ googleads.common.ENABLE_COMPRESSION_KEY: False,
+ googleads.common.CUSTOM_HEADERS_KEY: {
+ 'X-My-Header': 'abc'}},
+ rval)
+ self.assertTrue(googleads.common._utility_registry._enabled)
def testLoadFromStorage_relativePath(self):
fake_os = fake_filesystem.FakeOsModule(self.filesystem)
yaml_contents = {'one': {'needed': 'd', 'keys': 'e'}}
- yaml_contents['one'].update(self._OAUTH_DICT)
+ yaml_contents['one'].update(self._OAUTH_INSTALLED_APP_DICT)
self.filesystem.CreateFile('/home/test/yaml/googleads.yaml',
contents=yaml.dump(yaml_contents))
fake_os.chdir('/home/test')
@@ -161,25 +198,417 @@ def testLoadFromStorage_relativePath(self):
with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client:
with mock.patch('googleads.common.os', fake_os):
with mock.patch('googleads.common.open', self.fake_open, create=True):
- rval = googleads.common.LoadFromStorage(
- 'yaml/googleads.yaml', 'one', ['needed', 'keys'], ['other'])
- mock_client.assert_called_once_with('a', 'b', 'c', None, True, None)
+ with mock.patch('googleads.common.ProxyConfig') as proxy_config:
+ proxy_config.return_value = mock.Mock()
+ rval = googleads.common.LoadFromStorage(
+ 'yaml/googleads.yaml', 'one', ['needed', 'keys'], ['other'])
+
+ proxy_config.assert_called_once_with(
+ http_proxy=None, https_proxy=None, cafile=None,
+ disable_certificate_validation=False)
+ mock_client.assert_called_once_with(
+ 'a', 'b', 'c', proxy_config=proxy_config.return_value)
+ self.assertEqual({'oauth2_client': mock_client.return_value,
+ 'proxy_config': proxy_config.return_value,
+ 'needed': 'd', 'keys': 'e',
+ googleads.common.ENABLE_COMPRESSION_KEY: False,
+ googleads.common.CUSTOM_HEADERS_KEY: None}, rval)
+ self.assertTrue(googleads.common._utility_registry._enabled)
+
+ def _CreateYamlDoc(self, data, insert_oauth2_key=None, oauth_dict=None):
+ """Return the yaml doc created for testing."""
+ for key in data:
+ if key is insert_oauth2_key:
+ data[key].update(oauth_dict)
+ return yaml.dump(data)
+
+ def testLoadFromString_deprecatedWarningLoggerByMinorValue(self):
+ test_major_value = 3
+ test_minor_value = 4
+ test_micro_value = 5
+ with mock.patch('googleads.common._PY_VERSION_MAJOR', test_major_value):
+ with mock.patch('googleads.common._PY_VERSION_MINOR', test_minor_value):
+ with mock.patch('googleads.common._PY_VERSION_MICRO', test_micro_value):
+ with mock.patch('googleads.common._logger') as mock_logger:
+ googleads.common.CommonClient()
+ mock_logger.warning.assert_called_once_with(
+ googleads.common._DEPRECATED_VERSION_TEMPLATE,
+ test_major_value, test_minor_value, test_micro_value)
+
+ def testLoadFromString_emptyYamlString(self):
+ yaml_doc = ''
+ with mock.patch('googleads.common.open', self.fake_open, create=True):
+ self.assertRaises(
+ googleads.errors.GoogleAdsValueError,
+ googleads.common.LoadFromString,
+ yaml_doc, 'woo', [], [])
+
+ def testLoadFromString_malformedYamlString(self):
+ yaml_doc = 'woo:::'
+ self.assertRaises(
+ googleads.errors.GoogleAdsValueError,
+ googleads.common.LoadFromString,
+ yaml_doc, 'woo', [], [])
+
+ def testLoadFromString_emptyProductData(self):
+ yaml_doc = self._CreateYamlDoc({'woo': None})
+ self.assertRaises(
+ googleads.errors.GoogleAdsValueError,
+ googleads.common.LoadFromString,
+ yaml_doc, 'woo', [], [])
+
+ def testLoadFromString_missingOAuthKey(self):
+ yaml_doc = self._CreateYamlDoc({'woo': {}})
+ with mock.patch('googleads.common.open', self.fake_open, create=True):
+ self.assertRaises(
+ googleads.errors.GoogleAdsValueError,
+ googleads.common.LoadFromString,
+ yaml_doc, 'woo', [], [])
+
+ def testLoadFromString_missingProductYamlKey(self):
+ yaml_doc = self._CreateYamlDoc({'woo': {}})
+ with mock.patch('googleads.common.open', self.fake_open, create=True):
+ self.assertRaises(
+ googleads.errors.GoogleAdsValueError,
+ googleads.common.LoadFromString,
+ yaml_doc, 'bar', [], [])
+
+ def testLoadFromString_missingRequiredKey(self):
+ yaml_doc = self._CreateYamlDoc({'woo': {}})
+ with mock.patch('googleads.common.open', self.fake_open, create=True):
+ self.assertRaises(
+ googleads.errors.GoogleAdsValueError,
+ googleads.common.LoadFromString,
+ yaml_doc, 'woo', ['bar'], [])
+
+ def testLoadFromString_missingPartialInstalledAppOAuthCredential(self):
+ yaml_doc = self._CreateYamlDoc({'woo': {}}, 'woo', {'client_id': 'abc'})
+ with mock.patch('googleads.common.open', self.fake_open, create=True):
+ self.assertRaises(
+ googleads.errors.GoogleAdsValueError,
+ googleads.common.LoadFromString,
+ yaml_doc, 'woo', [], [])
+
+ def testLoadFromString_passesWithNoRequiredKeys(self):
+ yaml_doc = self._CreateYamlDoc({'woo': {}}, 'woo',
+ self._OAUTH_INSTALLED_APP_DICT)
+ with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client:
+ with mock.patch('googleads.common.open', self.fake_open, create=True):
+ with mock.patch('googleads.common.ProxyConfig') as proxy_config:
+ proxy_config.return_value = mock.Mock()
+ rval = googleads.common.LoadFromString(yaml_doc, 'woo', [], [])
+
+ proxy_config.assert_called_once_with(
+ http_proxy=None, https_proxy=None, cafile=None,
+ disable_certificate_validation=False)
+ mock_client.assert_called_once_with(
+ 'a', 'b', 'c', proxy_config=proxy_config.return_value)
+ self.assertEqual({'oauth2_client': mock_client.return_value,
+ 'proxy_config': proxy_config.return_value,
+ googleads.common.ENABLE_COMPRESSION_KEY: False,
+ googleads.common.CUSTOM_HEADERS_KEY: None}, rval)
+
+ def testLoadFromString_passesWithHTTPAndHTTPSProxy(self):
+ yaml_doc = self._CreateYamlDoc(
+ {'adwords': {},
+ 'proxy_config': {
+ 'http': self.uri1,
+ 'https': self.uri2}},
+ insert_oauth2_key='adwords', oauth_dict=self._OAUTH_INSTALLED_APP_DICT)
+ with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client:
+ with mock.patch('googleads.common.open', self.fake_open, create=True):
+ with mock.patch('googleads.common.ProxyConfig') as proxy_config:
+ proxy_config.return_value = mock.Mock()
+ rval = googleads.common.LoadFromString(
+ yaml_doc, 'adwords', [], [])
+
+ proxy_config.assert_called_once_with(
+ http_proxy=self.uri1, https_proxy=self.uri2, cafile=None,
+ disable_certificate_validation=False)
+ mock_client.assert_called_once_with(
+ 'a', 'b', 'c', proxy_config=proxy_config.return_value)
+ self.assertEqual({'oauth2_client': mock_client.return_value,
+ 'proxy_config': proxy_config.return_value,
+ googleads.common.ENABLE_COMPRESSION_KEY: False,
+ googleads.common.CUSTOM_HEADERS_KEY: None}, rval)
+
+ def testLoadFromString_passesWithHTTPProxy(self):
+ yaml_doc = self._CreateYamlDoc(
+ {'adwords': {},
+ 'proxy_config': {
+ 'http': self.uri1}},
+ insert_oauth2_key='adwords', oauth_dict=self._OAUTH_INSTALLED_APP_DICT)
+ with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client:
+ with mock.patch('googleads.common.open', self.fake_open, create=True):
+ with mock.patch('googleads.common.ProxyConfig') as proxy_config:
+ proxy_config.return_value = mock.Mock()
+ rval = googleads.common.LoadFromString(
+ yaml_doc, 'adwords', [], [])
+ proxy_config.assert_called_once_with(http_proxy=self.uri1,
+ https_proxy=None, cafile=None,
+ disable_certificate_validation=False)
+ mock_client.assert_called_once_with(
+ 'a', 'b', 'c', proxy_config=proxy_config.return_value)
+ self.assertEqual({'oauth2_client': mock_client.return_value,
+ 'proxy_config': proxy_config.return_value,
+ googleads.common.ENABLE_COMPRESSION_KEY: False,
+ googleads.common.CUSTOM_HEADERS_KEY: None}, rval)
+
+ def testLoadFromString_passesWithHTTPProxyLogin(self):
+ yaml_doc = self._CreateYamlDoc(
+ {'adwords': {},
+ 'proxy_config': {
+ 'http': self.uri1_w_creds}},
+ insert_oauth2_key='adwords', oauth_dict=self._OAUTH_INSTALLED_APP_DICT)
+ with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client:
+ with mock.patch('googleads.common.open', self.fake_open, create=True):
+ with mock.patch('googleads.common.ProxyConfig') as proxy_config:
+ proxy_config.return_value = mock.Mock()
+ rval = googleads.common.LoadFromString(yaml_doc, 'adwords', [], [])
+
+ proxy_config.assert_called_once_with(http_proxy=self.uri1_w_creds,
+ https_proxy=None, cafile=None,
+ disable_certificate_validation=False)
+ mock_client.assert_called_once_with(
+ 'a', 'b', 'c', proxy_config=proxy_config.return_value)
+ self.assertEqual({'oauth2_client': mock_client.return_value,
+ 'proxy_config': proxy_config.return_value,
+ googleads.common.ENABLE_COMPRESSION_KEY: False,
+ googleads.common.CUSTOM_HEADERS_KEY: None}, rval)
+
+ def testLoadFromString_passesWithHTTPSProxy(self):
+ yaml_doc = self._CreateYamlDoc(
+ {'adwords': {},
+ 'proxy_config': {
+ 'https': self.uri1}},
+ insert_oauth2_key='adwords', oauth_dict=self._OAUTH_INSTALLED_APP_DICT)
+ with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client:
+ with mock.patch('googleads.common.open', self.fake_open, create=True):
+ with mock.patch('googleads.common.ProxyConfig') as proxy_config:
+ proxy_config.return_value = mock.Mock()
+ rval = googleads.common.LoadFromString(yaml_doc, 'adwords', [], [])
+
+ proxy_config.assert_called_once_with(http_proxy=None,
+ https_proxy=self.uri1,
+ cafile=None,
+ disable_certificate_validation=False)
+ mock_client.assert_called_once_with(
+ 'a', 'b', 'c', proxy_config=proxy_config.return_value)
+ self.assertEqual({'oauth2_client': mock_client.return_value,
+ 'proxy_config': proxy_config.return_value,
+ googleads.common.ENABLE_COMPRESSION_KEY: False,
+ googleads.common.CUSTOM_HEADERS_KEY: None}, rval)
+
+ def testLoadFromString_passesWithHTTPSProxyLogin(self):
+ yaml_doc = self._CreateYamlDoc(
+ {'adwords': {},
+ 'proxy_config': {
+ 'https': self.uri1_w_creds}},
+ insert_oauth2_key='adwords', oauth_dict=self._OAUTH_INSTALLED_APP_DICT)
+ with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client:
+ with mock.patch('googleads.common.open', self.fake_open, create=True):
+ with mock.patch('googleads.common.ProxyConfig') as proxy_config:
+ proxy_config.return_value = mock.Mock()
+ rval = googleads.common.LoadFromString(yaml_doc, 'adwords', [], [])
+
+ proxy_config.assert_called_once_with(http_proxy=None,
+ https_proxy=self.uri1_w_creds,
+ cafile=None,
+ disable_certificate_validation=False)
+ mock_client.assert_called_once_with(
+ 'a', 'b', 'c', proxy_config=proxy_config.return_value)
+ self.assertEqual({'oauth2_client': mock_client.return_value,
+ 'proxy_config': proxy_config.return_value,
+ googleads.common.ENABLE_COMPRESSION_KEY: False,
+ googleads.common.CUSTOM_HEADERS_KEY: None}, rval)
+
+ def testLoadFromString_missingRequiredKeys(self):
+ with mock.patch('googleads.common.open', self.fake_open, create=True):
+ # Both keys are missing.
+ yaml_doc = self._CreateYamlDoc({
+ 'two': {}
+ }, 'two', self._OAUTH_INSTALLED_APP_DICT)
+ self.assertRaises(googleads.errors.GoogleAdsValueError,
+ googleads.common.LoadFromString, yaml_doc, 'two',
+ ['needed', 'keys'], [])
+
+ # One key is missing.
+ yaml_doc = self._CreateYamlDoc({
+ 'three': {
+ 'needed': 'd'
+ }
+ }, 'three', self._OAUTH_INSTALLED_APP_DICT)
+ self.assertRaises(googleads.errors.GoogleAdsValueError,
+ googleads.common.LoadFromString, yaml_doc, 'three',
+ ['needed', 'keys'], [])
+
+ def testLoadFromString_migrateToAdManager(self):
+ with mock.patch('googleads.common.open', self.fake_open, create=True):
+ # Both keys are missing.
+ yaml_doc = self._CreateYamlDoc({
+ 'dfp': {}
+ }, 'dfp', self._OAUTH_INSTALLED_APP_DICT)
+ with self.assertRaises(googleads.errors.GoogleAdsValueError) as ctx:
+ googleads.common.LoadFromString(yaml_doc, 'two', ['ad_manager'], [])
+
+ self.assertIn('Please replace', str(ctx.exception))
+
+ def testLoadFromString(self):
+ # No optional keys present.
+ yaml_doc = self._CreateYamlDoc({
+ 'one': {
+ 'needed': 'd',
+ 'keys': 'e'
+ }
+ }, 'one', self._OAUTH_INSTALLED_APP_DICT)
+ with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client:
+ with mock.patch('googleads.common.open', self.fake_open, create=True):
+ with mock.patch('googleads.common.ProxyConfig') as proxy_config:
+ proxy_config.return_value = mock.Mock()
+ rval = googleads.common.LoadFromString(
+ yaml_doc, 'one', ['needed', 'keys'], ['other'])
+ proxy_config.assert_called_once_with(
+ http_proxy=None, https_proxy=None, cafile=None,
+ disable_certificate_validation=False)
+ mock_client.assert_called_once_with(
+ 'a', 'b', 'c', proxy_config=proxy_config.return_value)
self.assertEqual({'oauth2_client': mock_client.return_value,
'needed': 'd', 'keys': 'e',
- 'https_proxy': None}, rval)
+ 'proxy_config': proxy_config.return_value,
+ googleads.common.ENABLE_COMPRESSION_KEY: False,
+ googleads.common.CUSTOM_HEADERS_KEY: None},
+ rval)
+ self.assertTrue(googleads.common._utility_registry._enabled)
- def testLoadFromStorage_warningWithUnrecognizedKey(self):
- yaml_fname = self._CreateYamlFile(
- {'kval': {'Im': 'here', 'whats': 'this?'}}, 'kval')
+ # The optional key is present.
+ yaml_doc = self._CreateYamlDoc({'one': {'needed': 'd', 'keys': 'e',
+ 'other': 'f'}}, 'one',
+ self._OAUTH_INSTALLED_APP_DICT)
+ with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client:
+ with mock.patch('googleads.common.open', self.fake_open, create=True):
+ with mock.patch('googleads.common.ProxyConfig') as proxy_config:
+ proxy_config.return_value = mock.Mock()
+ rval = googleads.common.LoadFromString(
+ yaml_doc, 'one', ['needed', 'keys'], ['other'])
+ proxy_config.assert_called_once_with(
+ http_proxy=None, https_proxy=None, cafile=None,
+ disable_certificate_validation=False)
+ mock_client.assert_called_once_with(
+ 'a', 'b', 'c', proxy_config=proxy_config.return_value)
+ self.assertEqual({'oauth2_client': mock_client.return_value,
+ 'needed': 'd', 'keys': 'e', 'other': 'f',
+ 'proxy_config': proxy_config.return_value,
+ googleads.common.ENABLE_COMPRESSION_KEY: False,
+ googleads.common.CUSTOM_HEADERS_KEY: None},
+ rval)
+ self.assertTrue(googleads.common._utility_registry._enabled)
+
+ def testLoadFromString_serviceAccount(self):
+ ad_manager_scope = googleads.oauth2.GetAPIScope('ad_manager')
+ # No optional keys present.
+ yaml_doc = self._CreateYamlDoc(
+ {'ad_manager': {'needed': 'd', 'keys': 'e'}},
+ insert_oauth2_key='ad_manager',
+ oauth_dict=self._OAUTH_SERVICE_ACCT_DICT)
+ with mock.patch(
+ 'googleads.oauth2.GoogleServiceAccountClient') as mock_client:
+ with mock.patch('googleads.common.open', self.fake_open, create=True):
+ with mock.patch('googleads.common.ProxyConfig') as proxy_config:
+ proxy_config.return_value = mock.Mock()
+ rval = googleads.common.LoadFromString(
+ yaml_doc, 'ad_manager', ['needed', 'keys'], ['other'])
+
+ proxy_config.assert_called_once_with(
+ http_proxy=None, https_proxy=None, cafile=None,
+ disable_certificate_validation=False)
+ mock_client.assert_called_once_with(
+ '/test/test.json', ad_manager_scope,
+ sub='delegated_account@example.com',
+ proxy_config=proxy_config.return_value)
+ self.assertEqual({'oauth2_client': mock_client.return_value,
+ 'proxy_config': proxy_config.return_value,
+ 'needed': 'd', 'keys': 'e',
+ googleads.common.ENABLE_COMPRESSION_KEY: False,
+ googleads.common.CUSTOM_HEADERS_KEY: None}, rval)
+ self.assertTrue(googleads.common._utility_registry._enabled)
+
+ # The optional key is present.
+ yaml_doc = self._CreateYamlDoc(
+ {'ad_manager': {'needed': 'd', 'keys': 'e', 'other': 'f'}},
+ 'ad_manager', self._OAUTH_SERVICE_ACCT_DICT)
+ with mock.patch(
+ 'googleads.oauth2.GoogleServiceAccountClient') as mock_client:
+ with mock.patch('googleads.common.open', self.fake_open, create=True):
+ with mock.patch('googleads.common.ProxyConfig') as proxy_config:
+ proxy_config.return_value = mock.Mock()
+ rval = googleads.common.LoadFromString(
+ yaml_doc, 'ad_manager', ['needed', 'keys'], ['other'])
+
+ proxy_config.assert_called_once_with(
+ http_proxy=None, https_proxy=None, cafile=None,
+ disable_certificate_validation=False)
+ mock_client.assert_called_once_with(
+ '/test/test.json', ad_manager_scope,
+ sub='delegated_account@example.com',
+ proxy_config=proxy_config.return_value)
+ self.assertEqual({'oauth2_client': mock_client.return_value,
+ 'proxy_config': proxy_config.return_value,
+ 'needed': 'd', 'keys': 'e', 'other': 'f',
+ googleads.common.ENABLE_COMPRESSION_KEY: False,
+ googleads.common.CUSTOM_HEADERS_KEY: None}, rval)
+ self.assertTrue(googleads.common._utility_registry._enabled)
+
+
+ def testLoadFromString_utilityRegistryDisabled(self):
+ yaml_doc = self._CreateYamlDoc(
+ {'one': {'needed': 'd', 'keys': 'e'},
+ 'include_utilities_in_user_agent': False},
+ 'one', self._OAUTH_INSTALLED_APP_DICT)
+
+ with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client:
+ with mock.patch('googleads.common.open', self.fake_open, create=True):
+ with mock.patch('googleads.common.ProxyConfig') as proxy_config:
+ proxy_config.return_value = mock.Mock()
+ rval = googleads.common.LoadFromString(
+ yaml_doc, 'one', ['needed', 'keys'], ['other'])
+ proxy_config.assert_called_once_with(
+ http_proxy=None, https_proxy=None, cafile=None,
+ disable_certificate_validation=False)
+ mock_client.assert_called_once_with(
+ 'a', 'b', 'c', proxy_config=proxy_config.return_value)
+ self.assertEqual({'oauth2_client': mock_client.return_value,
+ 'needed': 'd', 'keys': 'e',
+ 'proxy_config': proxy_config.return_value,
+ googleads.common.ENABLE_COMPRESSION_KEY: False,
+ googleads.common.CUSTOM_HEADERS_KEY: None},
+ rval)
+ self.assertFalse(googleads.common._utility_registry._enabled)
+
+
+ def testLoadFromString_warningWithUnrecognizedKey(self):
+ yaml_doc = self._CreateYamlDoc(
+ {'kval': {'Im': 'here', 'whats': 'this?'}}, 'kval',
+ self._OAUTH_INSTALLED_APP_DICT)
with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client:
with warnings.catch_warnings(record=True) as captured_warnings:
with mock.patch('googleads.common.open', self.fake_open, create=True):
- rval = googleads.common.LoadFromStorage(
- yaml_fname, 'kval', ['Im'], ['other'])
- mock_client.assert_called_once_with('a', 'b', 'c', None, True, None)
- self.assertEqual({'oauth2_client': mock_client.return_value,
- 'Im': 'here', 'https_proxy': None}, rval)
- self.assertEqual(len(captured_warnings), 1)
+ with mock.patch('googleads.common.ProxyConfig') as proxy_config:
+ proxy_config.return_value = mock.Mock()
+ rval = googleads.common.LoadFromString(
+ yaml_doc, 'kval', ['Im'], ['other'])
+ mock_client.assert_called_once_with(
+ 'a', 'b', 'c', proxy_config=proxy_config.return_value)
+ self.assertEqual(
+ {
+ 'oauth2_client': mock_client.return_value,
+ 'Im': 'here',
+ 'proxy_config': proxy_config.return_value,
+ googleads.common.ENABLE_COMPRESSION_KEY: False,
+ googleads.common.CUSTOM_HEADERS_KEY: None
+ }, rval)
+ self.assertTrue(googleads.common._utility_registry._enabled)
+ self.assertEqual(len(captured_warnings), 1)
+
def testGenerateLibSig(self):
my_name = 'Joseph'
@@ -188,113 +617,425 @@ def testGenerateLibSig(self):
googleads.common._PYTHON_VERSION),
googleads.common.GenerateLibSig(my_name))
- def testPackForSuds(self):
- factory = mock.Mock()
-
- # Test that anything other than list, tuple, and dict pass right through.
- self.assertEqual('input', googleads.common._PackForSuds('input', factory))
- self.assertEqual(set([1]),
- googleads.common._PackForSuds(set([1]), factory))
-
- # Test that lists not containing dicts with xsi types return the same
- # values, and test that the input list was not modified.
- input_list = ['1', set([3]), {'moo': 'cow'}]
- self.assertEqual(['1', set([3]), {'moo': 'cow'}],
- googleads.common._PackForSuds(input_list, factory))
- self.assertEqual(['1', set([3]), {'moo': 'cow'}], input_list)
-
- # Test that dicts without xsi types return the same values, and test that
- # the input dict was not modified
- input_dict = {'1': 'moo', frozenset([2]): ['val']}
- self.assertEqual({'1': 'moo', frozenset([2]): ['val']},
- googleads.common._PackForSuds(input_dict, factory))
- self.assertEqual({'1': 'moo', frozenset([2]): ['val']}, input_dict)
-
- # Now it gets interesting... Test that a dictionary with xsi type gets
- # changed into an object. Test that the input dict is unmodified.
- input_dict = {'xsi_type': 'EliteCampaign', 'name': 'Sales', 'id': 123456,
- 'metadata': {'a': 'b'}}
- factory.create.return_value = mock.MagicMock()
- factory.create.return_value.__iter__.return_value = iter(
- [('id', 0), ('name', 1), ('metadata', 2), ('Campaign.Type', 3),
- ('status', 4)])
-
- rval = googleads.common._PackForSuds(input_dict, factory)
- factory.create.assert_called_once_with('EliteCampaign')
- self.assertEqual('Sales', rval.name)
- self.assertEqual(123456, rval.id)
- self.assertEqual({'a': 'b'}, rval.metadata)
- self.assertEqual('EliteCampaign', getattr(rval, 'Campaign.Type'))
- self.assertEqual(None, rval.status)
- self.assertEqual({'xsi_type': 'EliteCampaign', 'name': 'Sales',
- 'id': 123456, 'metadata': {'a': 'b'}}, input_dict)
-
- # Test that this all works recursively. Nest dictionaries in dictionaries in
- # lists in classes.
- factory = mock.Mock()
- factory.create.side_effect = [mock.MagicMock(), mock.MagicMock()]
- input_list = [{'xsi_type': 'EliteCampaign', 'name': 'Sales', 'id': None,
- 'metadata': {'xsi_type': 'metadata', 'a': {'b': 'c'}}},
- {'i do not have': 'a type'}]
- rval = googleads.common._PackForSuds(input_list, factory)
- factory.create.assert_any_call('EliteCampaign')
- factory.create.assert_any_call('metadata')
- self.assertIsInstance(rval, list)
- self.assertEqual('Sales', rval[0].name)
- self.assertIsInstance(rval[0].id, suds.null)
- self.assertEqual({'b': 'c'}, rval[0].metadata.a)
- self.assertEqual({'i do not have': 'a type'}, rval[1])
+ def testGenerateLibSigWithUtilities(self):
+ my_name = 'Mark'
+
+ t1 = self.test1()
+ t2 = self.test2()
+
+ # The order of utilities in the generated library signature is not
+ # guaranteed, so verify that the string contains the same values instead.
+ # Make the first request using both utilities.
+ t1.test()
+ t2.test()
+ expected = set((my_name, googleads.common._COMMON_LIB_SIG,
+ googleads.common._PYTHON_VERSION, self.test1_name,
+ '%s/%s' % (self.test2_name, self.test2_version)))
+ generated = set(googleads.common.GenerateLibSig(my_name)[2:-1].split(', '))
+
+ self.assertEqual(expected, generated)
+
+ # Make another request, this time no utilities.
+ expected = set((my_name, googleads.common._COMMON_LIB_SIG,
+ googleads.common._PYTHON_VERSION))
+ generated = set(googleads.common.GenerateLibSig(my_name)[2:-1].split(', '))
+
+ self.assertEqual(expected, generated)
+
+ # Make another request, this time one utility.
+ t1.test()
+ expected = set((my_name, googleads.common._COMMON_LIB_SIG,
+ googleads.common._PYTHON_VERSION, self.test1_name))
+ generated = set(googleads.common.GenerateLibSig(my_name)[2:-1].split(', '))
+
+ self.assertEqual(expected, generated)
+
+
+ def testGenerateLibSigWithUtilitiesDisabled(self):
+ my_name = 'Mark'
+
+ googleads.common.IncludeUtilitiesInUserAgent(False)
+
+ t1 = self.test1()
+ t1.test()
+ t2 = self.test2()
+ t2.test()
+
self.assertEqual(
- [{'xsi_type': 'EliteCampaign', 'name': 'Sales', 'id': None,
- 'metadata': {'xsi_type': 'metadata', 'a': {'b': 'c'}}},
- {'i do not have': 'a type'}], input_list)
+ ' (%s, %s, %s)' % (my_name, googleads.common._COMMON_LIB_SIG,
+ googleads.common._PYTHON_VERSION),
+ googleads.common.GenerateLibSig(my_name))
- def testPackForSuds_secondNamespace(self):
- factory = mock.Mock()
- factory.create.side_effect = [suds.TypeNotFound(''), mock.MagicMock()]
- input_list = {'xsi_type': 'EliteCampaign', 'name': 'Sales'}
- rval = googleads.common._PackForSuds(input_list, factory)
- factory.create.assert_any_call('EliteCampaign')
- factory.create.assert_any_call('ns0:EliteCampaign')
- self.assertEqual('Sales', rval.name)
+@contextmanager
+def mock_zeep_client():
+ mock_port = mock.MagicMock()
+ mock_port.binding = mock.MagicMock()
+ mock_service = mock.MagicMock()
+ mock_service.ports.itervalues.return_value = iter([mock_port])
+ mock_service.ports.values.return_value = iter([mock_port]) # For py3
-class SudsServiceProxyTest(unittest.TestCase):
- """Tests for the googleads.common.SudsServiceProxy class."""
+ with mock.patch('googleads.common.zeep.Client') as mock_client:
+ mock_services = mock_client.return_value.wsdl.services
+ mock_services.itervalues.return_value = iter([mock_service])
+ mock_services.values.return_value = iter([mock_service]) # For py3
- def testSudsServiceProxy(self):
+ yield mock_client
+
+
+class ZeepServiceProxyTest(unittest.TestCase):
+
+ def setUp(self):
+ super(ZeepServiceProxyTest, self).setUp()
+
+ self.empty_proxy_config = googleads.common.ProxyConfig()
+ self.timeout_100 = 100
+ self.fake_version = 'ignored'
+
+ def testCreateZeepClient(self):
header_handler = mock.Mock()
- port = mock.Mock()
- port.methods = ('SoapMethod',)
- services = mock.Mock()
- services.ports = [port]
- client = mock.Mock()
- client.wsdl.services = [services]
- suds_service_wrapper = googleads.common.SudsServiceProxy(
- client, header_handler)
-
- self.assertEqual(suds_service_wrapper.SoapMethod,
- suds_service_wrapper._method_proxies['SoapMethod'])
- self.assertEqual(suds_service_wrapper.NotSoapMethod,
- client.service.NotSoapMethod)
-
- with mock.patch('googleads.common._PackForSuds') as mock_pack_for_suds:
- mock_pack_for_suds.return_value = 'modified_test'
- suds_service_wrapper.SoapMethod('test')
- mock_pack_for_suds.assert_called_once_with('test', client.factory)
-
- client.service.SoapMethod.assert_called_once_with('modified_test')
- header_handler.SetHeaders.assert_called_once_with(client)
-
-
-class HeaderHandlerTest(unittest.TestCase):
- """Tests for the googleads.common.HeaderHeader class."""
-
- def testSetHeaders(self):
- """For coverage."""
- self.assertRaises(
- NotImplementedError, googleads.common.HeaderHandler().SetHeaders,
- mock.Mock())
+ packer = mock.Mock()
+
+ class MyCache(zeep.cache.Base):
+ pass
+ cache = MyCache()
+
+ with mock_zeep_client() as mock_client, \
+ mock.patch('googleads.common._ZeepAuthHeaderPlugin') as zeep_auth, \
+ mock.patch('googleads.common._ZeepProxyTransport') as zeep_transport, \
+ mock.patch('googleads.util.ZeepLogger') as zeep_logger:
+ zeep_wrapper = googleads.common.ZeepServiceProxy(
+ 'http://abc', header_handler, packer, 'proxy', 'timeout',
+ self.fake_version, cache)
+
+ zeep_auth.assert_called_once_with(header_handler)
+ plugins = [zeep_auth.return_value, zeep_logger.return_value]
+ transport = zeep_transport.return_value
+ zeep_transport.assert_called_once_with('timeout', 'proxy', cache)
+ mock_client.assert_called_once_with(
+ 'http://abc', transport=transport, plugins=plugins)
+ self.assertEqual(zeep_wrapper.zeep_client, mock_client.return_value)
+
+ def testCreateSoapElementForType(self):
+ header_handler = mock.Mock()
+ packer = mock.Mock()
+
+ with mock_zeep_client():
+ zeep_wrapper = googleads.common.ZeepServiceProxy(
+ 'http://abc', header_handler, packer,
+ self.empty_proxy_config, self.timeout_100, self.fake_version)
+
+ type_mock = mock.Mock()
+ zeep_wrapper.zeep_client.get_type.return_value = type_mock
+ result = zeep_wrapper.CreateSoapElementForType('MyType')
+ self.assertEqual(result, type_mock.return_value)
+ zeep_wrapper.zeep_client.get_type.assert_called_once_with('MyType')
+
+ def testWsdlHasMethod(self):
+ header_handler = mock.Mock()
+ packer = mock.Mock()
+
+ with mock_zeep_client():
+ zeep_wrapper = googleads.common.ZeepServiceProxy(
+ 'http://abc', header_handler, packer,
+ self.empty_proxy_config, self.timeout_100, self.fake_version)
+
+ with mock.patch.object(zeep_wrapper, '_method_bindings') as mock_bindings:
+ get_method = mock_bindings.get
+
+ self.assertTrue(zeep_wrapper._WsdlHasMethod('abc'))
+
+ get_method.side_effect = ValueError
+ self.assertFalse(zeep_wrapper._WsdlHasMethod('abc'))
+
+ def testZeepErrorRaisesGoogleError(self):
+ with mock_zeep_client() as mock_client:
+ mock_client.side_effect = requests.exceptions.HTTPError
+
+ with self.assertRaises(googleads.errors.GoogleAdsSoapTransportError):
+ googleads.common.ZeepServiceProxy(
+ 'http://abc', None, None, self.empty_proxy_config, self.timeout_100,
+ self.fake_version)
+
+ @mock.patch('googleads.common._ZeepProxyTransport')
+ def testSchemaHelperRaisesGoogleError(self, mock_transport_class):
+ mock_transport_class.return_value.load.side_effect = (
+ requests.exceptions.HTTPError)
+
+ with self.assertRaises(googleads.errors.GoogleAdsSoapTransportError):
+ googleads.common.ZeepSchemaHelper(None, None, None, 100, None)
+
+ def testGetRequestXML(self):
+ header_handler = mock.Mock()
+ packer = mock.Mock()
+
+ with mock_zeep_client():
+ zeep_wrapper = googleads.common.ZeepServiceProxy(
+ 'http://abc', header_handler, packer,
+ self.empty_proxy_config, self.timeout_100, self.fake_version)
+
+ mock_create = zeep_wrapper.zeep_client.create_message
+
+ with mock.patch.object(
+ zeep_wrapper,
+ '_GetZeepFormattedSOAPHeaders') as mock_get_headers, \
+ mock.patch.object(zeep_wrapper, '_PackArguments') as mock_pack:
+ mock_pack.return_value = [1, 2, 3]
+
+ result = zeep_wrapper.GetRequestXML('someMethod', 'a', 1, 2)
+
+ self.assertEqual(result, mock_create.return_value)
+ mock_pack.assert_called_once_with(
+ 'someMethod', ('a', 1, 2), set_type_attrs=True)
+ mock_create.assert_called_once_with(
+ zeep_wrapper.zeep_client.service, 'someMethod', 1, 2, 3,
+ _soapheaders=mock_get_headers.return_value)
+
+ def testBadCacheType(self):
+ header_handler = mock.Mock()
+ packer = mock.Mock()
+
+ with mock_zeep_client(), \
+ self.assertRaises(googleads.errors.GoogleAdsValueError):
+ googleads.common.ZeepServiceProxy(
+ 'http://abc', header_handler, packer,
+ self.empty_proxy_config, self.timeout_100, self.fake_version,
+ cache='not_a_zeep_cache')
+
+ def testSchemaHelperBadCacheType(self):
+ with self.assertRaises(googleads.errors.GoogleAdsValueError):
+ googleads.common.ZeepSchemaHelper(None, None, None, None, 'not_zeep')
+
+ def testAllowsNoCache(self):
+ header_handler = mock.Mock()
+ packer = mock.Mock()
+
+ with mock_zeep_client(),\
+ mock.patch('googleads.common._ZeepProxyTransport') as zeep_transport:
+ googleads.common.ZeepServiceProxy(
+ 'http://abc', header_handler, packer,
+ self.empty_proxy_config, self.timeout_100, self.fake_version,
+ cache=googleads.common.ZeepServiceProxy.NO_CACHE)
+
+ zeep_transport.assert_called_once_with(
+ self.timeout_100, self.empty_proxy_config,
+ googleads.common.ZeepServiceProxy.NO_CACHE)
+
+ def testFaultWithErrors(self):
+ detail = mock.Mock()
+ fault = zeep.exceptions.Fault('message', detail=detail)
+ header_handler = mock.Mock()
+ packer = mock.Mock()
+
+ with mock_zeep_client():
+ zeep_wrapper = googleads.common.ZeepServiceProxy(
+ 'http://abc', header_handler, packer,
+ googleads.common.ProxyConfig(), 100, self.fake_version)
+
+ zeep_wrapper.zeep_client.service['mymethod'].side_effect = fault
+ zeep_wrapper._GetBindingNamespace = mock.Mock()
+
+ with self.assertRaises(googleads.errors.GoogleAdsServerFault) as e:
+ zeep_wrapper.mymethod()
+
+ self.assertEqual(e.exception.document, detail)
+ self.assertIn('message', str(e.exception))
+
+ def testIsBase64(self):
+ result = googleads.common.ZeepServiceProxy._IsBase64('abcd')
+ self.assertTrue(result)
+
+ def testIsBase64Exception(self):
+ result = googleads.common.ZeepServiceProxy._IsBase64('abc')
+ self.assertFalse(result)
+
+ def testIsBase64DataBad(self):
+ result = googleads.common.ZeepServiceProxy._IsBase64('%%%%')
+ self.assertFalse(result)
+
+
+class TestZeepArgumentPacking(unittest.TestCase):
+
+ def setUp(self):
+ header_handler = mock.Mock()
+ self.fake_version = 'ignored'
+ wsdl_path = os.path.join(
+ TEST_DIR, 'test_data/ad_manager_report_service.xml')
+ self.zeep_client = googleads.common.ZeepServiceProxy(
+ wsdl_path, header_handler, None, googleads.common.ProxyConfig(), 100,
+ self.fake_version)
+
+ def testPackArgumentsPrimitivesOnly(self):
+ result = self.zeep_client._PackArguments('getReportJobStatus', [5])
+ self.assertCountEqual(result, [5])
+
+ def testPackArgumentsWithSimpleDict(self):
+ opts = {
+ 'exportFormat': 'CSV',
+ 'includeReportProperties': False,
+ 'includeTotalsRow': True,
+ 'useGzipCompression': False}
+ result = self.zeep_client._PackArguments(
+ 'getReportDownloadUrlWithOptions', [123, opts])
+ self.assertEqual(result[0], 123)
+ self.assertEqual(result[1].exportFormat, 'CSV')
+ self.assertEqual(result[1].includeTotalsRow, True)
+
+ def testPackArgumentsWithCustomTypeAndList(self):
+ data = {
+ 'reportQuery': {
+ 'adUnitView': 'HIERARCHICAL',
+ 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS'],
+ 'dateRangeType': 'LAST_WEEK',
+ 'dimensions': ['DATE', 'AD_UNIT_NAME'],
+ 'statement': {
+ 'query': 'WHERE PARENT_AD_UNIT_ID = :parentAdUnitId',
+ 'values': [{
+ 'key': 'parentAdUnitId',
+ 'value': {
+ 'value': 606389, 'xsi_type': 'NumberValue'}}]}}}
+ result = self.zeep_client._PackArguments('runReportJob', [data])
+ self.assertEqual(result[0].reportQuery.adUnitView, 'HIERARCHICAL')
+ self.assertEqual(result[0].reportQuery.dimensions[1], 'AD_UNIT_NAME')
+ number_value = result[0].reportQuery.statement.values[0].value
+ number_type = self.zeep_client.zeep_client.get_type('ns0:NumberValue')
+ self.assertEqual(type(number_value), number_type._value_class)
+
+ def testPackArgumentsLooksThroughSoapElements(self):
+ map_type = self.zeep_client.zeep_client.get_type('ns0:String_ValueMapEntry')
+ string_type = self.zeep_client.zeep_client.get_type('ns0:TextValue')
+
+ element = self.zeep_client.zeep_client.get_type('ns0:ReportQuery')()
+ element.statement = self.zeep_client.zeep_client.get_type('ns0:Statement')()
+ element.statement.values = [{
+ 'key': 'Key1',
+ 'value': {
+ 'xsi_type': 'NumberValue',
+ 'value': 10
+ }
+ }, map_type(key='Key2', value=string_type(value='abc'))]
+
+ result = self.zeep_client._PackArguments(
+ 'runReportJob', [{'reportQuery': element}])
+ result_values = result[0].reportQuery.statement.values
+ self.assertIsInstance(result_values[0], zeep.xsd.CompoundValue)
+ self.assertIsInstance(result_values[1], zeep.xsd.CompoundValue)
+
+ def testPackArgumentsWithCustomPacker(self):
+ class CustomPacker(googleads.common.SoapPacker):
+
+ def __init__(self):
+ self._version = CURRENT_VERSION
+
+ @classmethod
+ def Pack(cls, obj, version):
+ if isinstance(obj, numbers.Number):
+ return '50'
+ return obj
+
+ self.zeep_client._packer = CustomPacker
+ result = self.zeep_client._PackArguments('getReportJobStatus', [5])[0]
+ self.assertEqual(result, '50')
+
+ def testPackArgumentsBase64Warning(self):
+ image_type = self.zeep_client.zeep_client.get_type('ns0:Image')
+ b64_type = image_type.elements[0][1]
+ data = 'abcd' # This is valid base64
+
+ with mock.patch('googleads.common._logger'):
+ self.zeep_client._PackArgumentsHelper(b64_type, data, False)
+
+ def testPackArgumentsMultipleSchemas(self):
+ header_handler = mock.Mock()
+
+ wsdl_path = os.path.join(
+ TEST_DIR, 'test_data/traffic_estimator_service.xml')
+ zeep_client = googleads.common.ZeepServiceProxy(
+ wsdl_path, header_handler, None, googleads.common.ProxyConfig(), 100,
+ self.fake_version)
+
+ element = zeep_client.zeep_client.get_type('ns0:Criterion')
+ data = {'xsi_type': 'Location', 'id': '2840'}
+
+ result = zeep_client._PackArgumentsHelper(element, data, False)
+ self.assertEqual(result.id, '2840')
+
+ def testPackArgumentsBadType(self):
+ element = self.zeep_client.zeep_client.get_type('ns0:Image')
+ data = {'xsi_type': 'nope'}
+ with self.assertRaises(zeep.exceptions.LookupError):
+ self.zeep_client._PackArgumentsHelper(element, data, False)
+
+
+class ProxyConfigTest(unittest.TestCase):
+ """Tests for the googleads.common.ProxyConfig class."""
+
+ def setUp(self):
+ self.cafile = os.path.join(os.path.dirname(__file__), 'test_data/test.crt')
+ self.proxy_no_credentials = 'http://host1:port1'
+ self.proxy_with_credentials = 'http://username:password@host2:port2'
+
+ def testBuildOpenerWithConfig(self):
+ proxy_config = googleads.common.ProxyConfig(
+ https_proxy=self.proxy_no_credentials)
+
+ with mock.patch('googleads.common.build_opener') as mck_build_opener, \
+ mock.patch('googleads.common.HTTPSHandler') as mck_https_hndlr, \
+ mock.patch('googleads.common.ProxyHandler') as mck_prxy_hndlr:
+ mck_https_hndlr_instance = mock.Mock()
+ mck_https_hndlr.return_value = mck_https_hndlr_instance
+ mck_prxy_hndlr_instance = mock.Mock()
+ mck_prxy_hndlr.return_value = mck_prxy_hndlr_instance
+ proxy_config.BuildOpener()
+ mck_build_opener.assert_called_once_with(
+ *[mck_https_hndlr_instance, mck_prxy_hndlr_instance])
+
+ def testBuildOpenerWithDefaultConfig(self):
+ proxy_config = googleads.common.ProxyConfig()
+
+ with mock.patch('googleads.common.build_opener') as mck_build_opener, \
+ mock.patch('googleads.common.HTTPSHandler') as mock_https_hndlr:
+ mock_https_hndlr_instance = mock.Mock
+ mock_https_hndlr.return_value = mock_https_hndlr_instance
+ proxy_config.BuildOpener()
+ mck_build_opener.assert_called_once_with(*[mock_https_hndlr_instance])
+
+ def testProxyConfigWithNoProxy(self):
+ proxy_config = googleads.common.ProxyConfig()
+ self.assertEqual(proxy_config.proxies, {})
+ self.assertIsInstance(
+ proxy_config.ssl_context, ssl.SSLContext)
+
+ def testProxyConfigWithHTTPProxy(self):
+ proxy_config = googleads.common.ProxyConfig(
+ http_proxy=self.proxy_no_credentials)
+ self.assertEqual(proxy_config.proxies, {'http': self.proxy_no_credentials})
+ self.assertIsInstance(
+ proxy_config.ssl_context, ssl.SSLContext)
+
+ def testProxyConfigWithHTTPSProxy(self):
+ proxy_config = googleads.common.ProxyConfig(
+ https_proxy=self.proxy_with_credentials,
+ cafile=self.cafile)
+ self.assertEqual(proxy_config.proxies, {
+ 'https': self.proxy_with_credentials})
+ self.assertIsInstance(
+ proxy_config.ssl_context, ssl.SSLContext)
+ self.assertEqual(proxy_config.cafile, self.cafile)
+ self.assertEqual(proxy_config.disable_certificate_validation, False)
+
+ def testProxyConfigWithHTTPAndHTTPSProxy(self):
+ proxy_config = googleads.common.ProxyConfig(
+ http_proxy=self.proxy_with_credentials,
+ https_proxy=self.proxy_no_credentials,
+ disable_certificate_validation=True)
+ self.assertEqual(proxy_config.proxies, {
+ 'http': self.proxy_with_credentials,
+ 'https': self.proxy_no_credentials})
+
+ self.assertIsInstance(proxy_config.ssl_context, ssl.SSLContext)
+ self.assertEqual(proxy_config.cafile, None)
+ self.assertEqual(proxy_config.disable_certificate_validation, True)
if __name__ == '__main__':
diff --git a/tests/dfa_test.py b/tests/dfa_test.py
deleted file mode 100755
index 744bb925..00000000
--- a/tests/dfa_test.py
+++ /dev/null
@@ -1,150 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2013 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Unit tests to cover the dfa module."""
-
-__author__ = 'Joseph DiLallo'
-
-import unittest
-
-import mock
-import suds.transport
-
-import googleads.dfa
-import googleads.common
-import googleads.errors
-
-
-class DfaHeaderHandlerTest(unittest.TestCase):
- """Tests for the googleads.dfa._DfaHeaderHandler class."""
-
- def setUp(self):
- self.dfa_client = mock.Mock()
- self.header_handler = googleads.dfa._DfaHeaderHandler(self.dfa_client)
-
- def testSetHeaders(self):
- suds_client = mock.Mock()
- request_header_element = mock.Mock()
- app_name_element = mock.Mock()
- app_name_element.setText.return_value = app_name_element
- username = 'my username is name'
- app_name = 'application name'
- oauth_header = {'oauth', 'header'}
- self.dfa_client.username = username
- self.dfa_client.application_name = app_name
- self.dfa_client.oauth2_client.CreateHttpHeader.return_value = (
- oauth_header)
- element_mocks = {'RequestHeader': request_header_element,
- 'applicationName': app_name_element}
-
- with mock.patch('suds.wsse') as mock_wsse:
- with mock.patch('suds.sax') as mock_sax:
- mock_sax.element.Element.side_effect = lambda x: element_mocks[x]
-
- self.header_handler.SetHeaders(suds_client)
-
- mock_wsse.Security.assert_called_once_with()
- mock_wsse.UsernameToken.assert_called_once_with(username)
- mock_wsse.Security.return_value.tokens.append.assert_called_once_with(
- mock_wsse.UsernameToken.return_value)
-
- app_name_element.setText.assert_called_once_with(
- ''.join([app_name, googleads.dfa._DfaHeaderHandler._LIB_SIG]))
- request_header_element.append.assert_called_once_with(app_name_element)
-
- suds_client.set_options.assert_any_call(
- wsse=mock_wsse.Security.return_value,
- soapheaders=request_header_element,
- headers=oauth_header)
-
-
-class DfaClientTest(unittest.TestCase):
- """Tests for the googleads.dfa.DfaClient class."""
-
- def setUp(self):
- self.username = 'dfa_user_1'
- self.application_name = 'application name'
- self.oauth2_client = 'unused'
- self.https_proxy = 'myproxy.com:443'
- self.cache = None
- self.dfa_client = googleads.dfa.DfaClient(
- self.username, self.oauth2_client, self.application_name,
- self.https_proxy, self.cache)
-
- def testLoadFromStorage(self):
- with mock.patch('googleads.common.LoadFromStorage') as mock_load:
- mock_load.return_value = {
- 'username': 'abcdEFghIjkLMOpqRs',
- 'oauth2_client': True,
- 'application_name': 'unit testing'
- }
- self.assertIsInstance(googleads.dfa.DfaClient.LoadFromStorage(),
- googleads.dfa.DfaClient)
-
- def testGetService_success(self):
- version = googleads.dfa.DfaClient._SERVICE_MAP.keys()[0]
- service = googleads.dfa.DfaClient._SERVICE_MAP[version][0]
-
- # Use a custom server. Also test what happens if the server ends with a
- # trailing slash
- server = 'https://testing.test.com/'
- https_proxy = {'https': self.https_proxy}
- with mock.patch('suds.client.Client') as mock_client:
- suds_service = self.dfa_client.GetService(service, version, server)
-
- mock_client.assert_called_once_with(
- 'https://testing.test.com/%s/api/dfa-api/%s?wsdl'
- % (version, service), proxy=https_proxy, cache=self.cache,
- timeout=3600)
- self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy)
-
- # Use the default server and https_proxy.
- self.dfa_client.https_proxy = None
- with mock.patch('suds.client.Client') as mock_client:
- suds_service = self.dfa_client.GetService(service, version)
-
- mock_client.assert_called_once_with(
- 'https://advertisersapi.doubleclick.com/%s/api/dfa-api/%s?wsdl'
- % (version, service), proxy=None, cache=self.cache, timeout=3600)
- self.assertFalse(mock_client.return_value.set_options.called)
- self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy)
-
- def testGetService_badService(self):
- version = googleads.dfa.DfaClient._SERVICE_MAP.keys()[0]
- with mock.patch('suds.client.Client') as mock_client:
- mock_client.side_effect = suds.transport.TransportError('', '')
- self.assertRaises(
- googleads.errors.GoogleAdsValueError, self.dfa_client.GetService,
- 'GYIVyievfyiovslf', version)
-
- def testGetService_badVersion(self):
- with mock.patch('suds.client.Client') as mock_client:
- mock_client.side_effect = suds.transport.TransportError('', '')
- self.assertRaises(
- googleads.errors.GoogleAdsValueError, self.dfa_client.GetService,
- 'campaign', '11111')
-
- def testGetService_transportError(self):
- version = googleads.dfa.DfaClient._SERVICE_MAP.keys()[0]
- service = googleads.dfa.DfaClient._SERVICE_MAP[version][0]
- with mock.patch('suds.client.Client') as mock_client:
- mock_client.side_effect = suds.transport.TransportError('', '')
- self.assertRaises(suds.transport.TransportError,
- self.dfa_client.GetService, service, version)
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/tests/dfp_test.py b/tests/dfp_test.py
deleted file mode 100755
index 7b1e89e1..00000000
--- a/tests/dfp_test.py
+++ /dev/null
@@ -1,509 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2013 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Unit tests to cover the dfp module."""
-
-__author__ = 'Joseph DiLallo'
-
-import StringIO
-import sys
-import unittest
-
-import mock
-import suds.transport
-
-import googleads.dfp
-import googleads.common
-import googleads.errors
-
-
-class BaseValue(object):
-
- def __init__(self, original_object):
- self.original_object = original_object
-
- def __getitem__(self, key):
- return self.original_object[key]
-
- def __contains__(self, key):
- if key in self.original_object:
- return True
- return False
-
-
-class TextValue(BaseValue):
-
- def __init__(self, original_object):
- BaseValue.__init__(self, original_object)
-
-
-class NumberValue(BaseValue):
-
- def __init__(self, original_object):
- BaseValue.__init__(self, original_object)
-
-
-class DateValue(BaseValue):
-
- def __init__(self, original_object):
- BaseValue.__init__(self, original_object)
-
-
-class DateTimeValue(BaseValue):
-
- def __init__(self, original_object):
- BaseValue.__init__(self, original_object)
-
-
-class BooleanValue(BaseValue):
-
- def __init__(self, original_object):
- BaseValue.__init__(self, original_object)
-
-
-class SetValue(object):
-
- def __init__(self, original_object):
- packed_objects = [DecideValue(obj_to_pack) for obj_to_pack
- in original_object['values']]
- self.original_object = {'values': packed_objects}
-
- def __getitem__(self, key):
- return self.original_object[key]
-
- def __contains__(self, key):
- if key in self.original_object:
- return True
- return False
-
-
-def DecideValue(original_object):
- class_type = original_object['xsi_type']
- if class_type == 'TextValue':
- return TextValue(original_object)
- elif class_type == 'NumberValue':
- return NumberValue(original_object)
- elif class_type == 'DateValue':
- return DateValue(original_object)
- elif class_type == 'DateTimeValue':
- return DateTimeValue(original_object)
- elif class_type == 'SetValue':
- return SetValue(original_object)
- else:
- return BooleanValue(original_object)
-
-
-class DfpHeaderHandlerTest(unittest.TestCase):
- """Tests for the googleads.dfp._DfpHeaderHandler class."""
-
- def setUp(self):
- self.dfp_client = mock.Mock()
- self.header_handler = googleads.dfp._DfpHeaderHandler(self.dfp_client)
-
- def testSetHeaders(self):
- suds_client = mock.Mock()
- network_code = 'my network code is code'
- app_name = 'application name'
- oauth_header = {'oauth', 'header'}
- self.dfp_client.network_code = network_code
- self.dfp_client.application_name = app_name
- self.dfp_client.oauth2_client.CreateHttpHeader.return_value = oauth_header
-
- self.header_handler.SetHeaders(suds_client)
-
- # Check that the SOAP header has the correct values.
- suds_client.factory.create.assert_called_once_with('SoapRequestHeader')
- soap_header = suds_client.factory.create.return_value
- self.assertEqual(network_code, soap_header.networkCode)
- self.assertEqual(''.join([app_name,
- googleads.dfp._DfpHeaderHandler._LIB_SIG]),
- soap_header.applicationName)
-
- # Check that the suds client has the correct values.
- suds_client.set_options.assert_any_call(soapheaders=soap_header,
- headers=oauth_header)
-
-
-
-class DfpClientTest(unittest.TestCase):
- """Tests for the googleads.dfp.DfpClient class."""
-
- def setUp(self):
- self.network_code = '12345'
- self.application_name = 'application name'
- self.oauth2_client = 'unused'
- self.https_proxy = 'myproxy:443'
- self.cache = None
- self.version = sorted(googleads.dfp._SERVICE_MAP.keys())[-1]
- self.dfp_client = googleads.dfp.DfpClient(
- self.oauth2_client, self.application_name, self.network_code,
- self.https_proxy, self.cache)
-
- def testLoadFromStorage(self):
- with mock.patch('googleads.common.LoadFromStorage') as mock_load:
- mock_load.return_value = {
- 'network_code': 'abcdEFghIjkLMOpqRs',
- 'oauth2_client': True,
- 'application_name': 'unit testing'
- }
- self.assertIsInstance(googleads.dfp.DfpClient.LoadFromStorage(),
- googleads.dfp.DfpClient)
-
- def testInitializeWithDefaultApplicationName(self):
- self.application_name = 'INSERT_APPLICATION_NAME_HERE'
- self.assertRaises(
- googleads.errors.GoogleAdsValueError, googleads.dfp.DfpClient,
- self.oauth2_client, self.application_name, self.network_code,
- self.https_proxy, self.cache,
- 'Application name must be set and not be the default [%s]' %
- googleads.dfp.DEFAULT_APPLICATION_NAME)
-
- def testGetService_success(self):
- service = googleads.dfp._SERVICE_MAP[self.version][0]
-
- # Use a custom server. Also test what happens if the server ends with a
- # trailing slash
- server = 'https://testing.test.com/'
- https_proxy = {'https': self.https_proxy}
- with mock.patch('suds.client.Client') as mock_client:
- suds_service = self.dfp_client.GetService(service, self.version, server)
-
- mock_client.assert_called_once_with(
- 'https://testing.test.com/apis/ads/publisher/%s/%s?wsdl'
- % (self.version, service), proxy=https_proxy, cache=self.cache,
- timeout=3600)
- self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy)
-
- # Use the default server and https proxy.
- self.dfp_client.https_proxy = None
- with mock.patch('suds.client.Client') as mock_client:
- suds_service = self.dfp_client.GetService(service, self.version)
-
- mock_client.assert_called_once_with(
- 'https://ads.google.com/apis/ads/publisher/%s/%s?wsdl'
- % (self.version, service), proxy=None, cache=self.cache,
- timeout=3600)
- self.assertFalse(mock_client.return_value.set_options.called)
- self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy)
-
- def testGetService_badService(self):
- with mock.patch('suds.client.Client') as mock_client:
- mock_client.side_effect = suds.transport.TransportError('', '')
- self.assertRaises(
- googleads.errors.GoogleAdsValueError, self.dfp_client.GetService,
- 'GYIVyievfyiovslf', self.version)
-
- def testGetService_badVersion(self):
- with mock.patch('suds.client.Client') as mock_client:
- mock_client.side_effect = suds.transport.TransportError('', '')
- self.assertRaises(
- googleads.errors.GoogleAdsValueError, self.dfp_client.GetService,
- 'CampaignService', '11111')
-
- def testGetService_transportError(self):
- service = googleads.dfp._SERVICE_MAP[self.version][0]
- with mock.patch('suds.client.Client') as mock_client:
- mock_client.side_effect = suds.transport.TransportError('', '')
- self.assertRaises(suds.transport.TransportError,
- self.dfp_client.GetService, service, self.version)
-
-
-class DataDownloaderTest(unittest.TestCase):
- """Tests for the googleads.dfp.DfpClient class."""
-
- def setUp(self):
- network_code = '12345'
- application_name = 'application name'
- oauth2_client = 'unused'
- self.https_proxy = 'myproxy.com:443'
- dfp_client = googleads.dfp.DfpClient(
- oauth2_client, application_name, network_code, self.https_proxy)
- self.version = sorted(googleads.dfp._SERVICE_MAP.keys())[-1]
- self.report_downloader = dfp_client.GetDataDownloader()
- self.pql_service = mock.Mock()
- self.report_service = mock.Mock()
- self.report_downloader._pql_service = self.pql_service
- self.report_downloader._report_service = self.report_service
- self.generic_header = [{'labelName': 'Some random header...'},
- {'labelName': 'Another header...'}]
-
- row1_field1 = {
- 'value': 'Some random PQL response...',
- 'xsi_type': 'TextValue'
- }
-
- row1_field2 = {
- 'value': {
- 'date': {
- 'year': '1999', 'month': '04', 'day': '03'}
- },
- 'xsi_type': 'DateValue'
- }
-
- row1_field3 = {
- 'value': '123',
- 'xsi_type': 'NumberValue'
- }
-
- row1_field4 = {
- 'value': {
- 'date': {
- 'year': '2012',
- 'month': '11',
- 'day': '05'
- },
- 'hour': '12',
- 'minute': '12',
- 'second': '12',
- 'timeZoneID': 'PST8PDT'},
- 'xsi_type': 'DateTimeValue'
- }
-
- row1_field5 = {
- 'value': None,
- 'xsi_type': 'NumberValue'
- }
-
- row1_field6 = {
- 'values': [{
- 'value': 'Whatcha thinkin about?',
- 'xsi_type': 'TextValue'
- }, {
- 'value': 'Oh nothing, just String stuff...',
- 'xsi_type': 'TextValue'
- }],
- 'xsi_type': 'SetValue'
- }
-
- row2_field1 = {
- 'value': 'A second row of PQL response!',
- 'xsi_type': 'TextValue'
- }
-
- row2_field2 = {
- 'value': {
- 'date': {
- 'year': '2009',
- 'month': '02',
- 'day': '05'
- }
- },
- 'xsi_type': 'DateValue'
- }
-
- row2_field3 = {
- 'value': '345',
- 'xsi_type': 'NumberValue'
- }
-
- row2_field4 = {
- 'value': {
- 'date': {
- 'year': '2013',
- 'month': '01',
- 'day': '03'
- },
- 'hour': '02',
- 'minute': '02',
- 'second': '02',
- 'timeZoneID': 'GMT'
- },
- 'xsi_type': 'DateTimeValue'
- }
-
- row2_field5 = {
- 'value': '123456',
- 'xsi_type': 'NumberValue'
- }
-
- row2_field6 = {
- 'values': [{
- 'value': 'Look at how many commas and "s there are',
- 'xsi_type': 'TextValue'
- }, {
- 'value': 'this,is...how,Christopher Walken, talks',
- 'xsi_type': 'TextValue'
- }],
- 'xsi_type': 'SetValue'
- }
-
- row1 = [row1_field1, row1_field2, row1_field3, row1_field4, row1_field5,
- row1_field6]
- row2 = [row2_field1, row2_field2, row2_field3, row2_field4, row2_field5,
- row2_field6]
-
- self.generic_rval = [{
- 'values': [DecideValue(value) for value in row1]
- }, {
- 'values': [DecideValue(value) for value in row2]
- }]
-
- def testDownloadPqlResultSetToCsv(self):
- csv_file = StringIO.StringIO()
-
- self.pql_service.select.return_value = {'rows': self.generic_rval,
- 'columnTypes': self.generic_header}
-
- self.report_downloader.DownloadPqlResultToCsv(
- 'SELECT Id, Name FROM Line_Item', csv_file)
-
- csv_file.seek(0)
- self.assertEqual(csv_file.readline(),
- ('"Some random header...",'
- '"Another header..."\r\n'))
- self.assertEqual(csv_file.readline(),
- ('"Some random PQL response...",'
- '"1999-04-03",'
- '"123",'
- '"2012-11-05T12:12:12-08:00",'
- '"-","""Whatcha thinkin about?"",""Oh nothing, '
- 'just String stuff..."""\r\n'))
- self.assertEqual(csv_file.readline(),
- ('"A second row of PQL response!",'
- '"2009-02-05",'
- '"345",'
- '"2013-01-03T02:02:02Z",'
- '"123456","""Look at how many commas and """"s there are'
- '"",""this,is...how,Christopher Walken, talks"""\r\n'))
- csv_file.close()
-
- self.pql_service.select.assert_called_once_with(
- {'values': None,
- 'query': ('SELECT Id, Name FROM Line_Item LIMIT 500 OFFSET 0')})
-
- def testDownloadPqlResultToList(self):
- self.pql_service.select.return_value = {'rows': self.generic_rval,
- 'columnTypes': self.generic_header}
-
- result_set = self.report_downloader.DownloadPqlResultToList(
- 'SELECT Id, Name FROM Line_Item')
-
- row1 = [self.report_downloader._ConvertValueForCsv(field)
- for field in self.generic_rval[0]['values']]
- row2 = [self.report_downloader._ConvertValueForCsv(field)
- for field in self.generic_rval[1]['values']]
-
- self.pql_service.select.assert_called_once_with(
- {'values': None,
- 'query': ('SELECT Id, Name FROM Line_Item LIMIT 500 OFFSET 0')})
- self.assertEqual([[self.generic_header[0]['labelName'],
- self.generic_header[1]['labelName']],
- row1, row2], result_set)
-
- def testDownloadPqlResultToList_NoRows(self):
- self.pql_service.select.return_value = {}
-
- result_set = self.report_downloader.DownloadPqlResultToList(
- 'SELECT Id, Name FROM Line_Item')
-
- self.pql_service.select.assert_called_once_with(
- {'values': None,
- 'query': ('SELECT Id, Name FROM Line_Item LIMIT 500 OFFSET 0')})
- self.assertEqual([], result_set)
-
- def testWaitForReport_success(self):
- id_ = '1g684'
- input_ = {'query': 'something', 'id': id_}
- incomplete_response = {'reportJobStatus': 'PROCESSING', 'id': id_}
- complete_response = {'reportJobStatus': 'COMPLETED', 'id': id_}
- self.report_service.getReportJob.side_effect = [incomplete_response,
- complete_response]
- self.report_service.runReportJob.return_value = input_
-
- with mock.patch('time.sleep') as mock_sleep:
- rval = self.report_downloader.WaitForReport(input_)
- mock_sleep.assert_called_once_with(30)
- self.assertEqual(id_, rval)
- self.report_service.getReportJob.assert_any_call(id_)
-
- def testWaitForReport_failure(self):
- self.report_service.getReportJob.return_value = {
- 'reportJobStatus': 'FAILED'}
- self.report_service.runReportJob.return_value = {'id': '782yt97r2'}
-
- self.assertRaises(
- googleads.errors.DfpReportError,
- self.report_downloader.WaitForReport, {'id': 'obj'})
-
- def testDownloadReportToFile(self):
- report_format = 'csv'
- report_job_id = 't68t3278y429'
- report_download_url = 'http://google.com/something'
- report_contents = 'THIS IS YOUR REPORT!'
- fake_request = StringIO.StringIO()
- fake_request.write(report_contents)
- fake_request.seek(0)
- outfile = StringIO.StringIO()
-
- self.report_service.getReportDownloadURL.return_value = report_download_url
-
- with mock.patch('urllib2.urlopen' if sys.version_info[0] == 2
- else 'urllib.request.urlopen') as mock_urlopen:
- mock_urlopen.return_value = fake_request
- self.report_downloader.DownloadReportToFile(
- report_job_id, report_format, outfile)
- mock_urlopen.assert_called_once_with(report_download_url)
- self.assertEqual(report_contents, outfile.getvalue())
-
- def testGetReportService(self):
- self.report_downloader._dfp_client = mock.Mock()
- self.report_downloader._report_service = None
-
- self.report_downloader._GetReportService()
- self.report_downloader._dfp_client.GetService.assert_called_once_with(
- 'ReportService', self.version, 'https://ads.google.com')
-
- def testGetPqlService(self):
- self.report_downloader._dfp_client = mock.Mock()
- self.report_downloader._pql_service = None
-
- self.report_downloader._GetPqlService()
- self.report_downloader._dfp_client.GetService.assert_called_once_with(
- 'PublisherQueryLanguageService', self.version, 'https://ads.google.com')
-
-
-class FilterStatementTest(unittest.TestCase):
- """Tests for the FilterStatement class."""
-
- def testFilterStatement(self):
- values = [{
- 'key': 'test_key',
- 'value': {
- 'xsi_type': 'TextValue',
- 'value': 'test_value'
- }
- }]
- test_statement = googleads.dfp.FilterStatement()
- self.assertEqual(test_statement.ToStatement(),
- {'query': ' LIMIT 500 OFFSET 0', 'values': None})
- test_statement.offset += 30
- self.assertEqual(test_statement.ToStatement(),
- {'query': ' LIMIT 500 OFFSET 30', 'values': None})
- test_statement.offset = 123
- test_statement.limit = 5
- self.assertEqual(test_statement.ToStatement(),
- {'query': ' LIMIT 5 OFFSET 123', 'values': None})
- test_statement = googleads.dfp.FilterStatement(
- 'SELECT Id FROM Line_Item WHERE key = :test_key', limit=300, offset=20,
- values=values)
- self.assertEqual(test_statement.ToStatement(),
- {'query': 'SELECT Id FROM Line_Item WHERE key = '
- ':test_key LIMIT 300 OFFSET 20',
- 'values': values})
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/tests/errors_test.py b/tests/errors_test.py
old mode 100755
new mode 100644
index dd3fe094..5f3c5c9f
--- a/tests/errors_test.py
+++ b/tests/errors_test.py
@@ -1,5 +1,3 @@
-#!/usr/bin/python
-#
# Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -16,7 +14,6 @@
"""Unit tests to cover the errors module."""
-__author__ = 'Joseph DiLallo'
import unittest
diff --git a/tests/oauth2_test.py b/tests/oauth2_test.py
old mode 100755
new mode 100644
index 5f73d9cb..8716b779
--- a/tests/oauth2_test.py
+++ b/tests/oauth2_test.py
@@ -1,5 +1,3 @@
-#!/usr/bin/python
-#
# Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -16,23 +14,19 @@
"""Unit tests to cover the oauth2 module."""
-__author__ = 'Mark Saniscalchi'
import datetime
import unittest
-import httplib2
import mock
-import socks
-
+import googleads.common
import googleads.errors
import googleads.oauth2
-
-import fake_filesystem
-import fake_tempfile
-from oauth2client.client import AccessTokenRefreshError
-from oauth2client.client import OAuth2Credentials
-from oauth2client.client import SignedJwtAssertionCredentials
+from pyfakefs import fake_filesystem
+from pyfakefs import fake_tempfile
+from google.auth.exceptions import RefreshError
+from google.auth.transport import Request
+from google.oauth2.credentials import Credentials
class GetAPIScopeTest(unittest.TestCase):
@@ -40,27 +34,21 @@ class GetAPIScopeTest(unittest.TestCase):
def setUp(self):
self.api_name_adwords = 'adwords'
- self.api_name_dfa = 'dfa'
- self.api_name_dfp = 'dfp'
+ self.api_name_ad_manager = 'ad_manager'
self.scope_adwords = 'https://www.googleapis.com/auth/adwords'
- self.scope_dfa = 'https://www.googleapis.com/auth/dfatrafficking'
- self.scope_dfp = 'https://www.googleapis.com/auth/dfp'
+ self.scope_ad_manager = 'https://www.googleapis.com/auth/dfp'
def testGetAPIScope_adwords(self):
- self.assertEquals(googleads.oauth2.GetAPIScope(self.api_name_adwords),
- self.scope_adwords)
+ self.assertEqual(googleads.oauth2.GetAPIScope(self.api_name_adwords),
+ self.scope_adwords)
def testGetAPIScope_badKey(self):
self.assertRaises(googleads.errors.GoogleAdsValueError,
googleads.oauth2.GetAPIScope, 'fake_api_name')
- def testGetAPIScope_dfa(self):
- self.assertEquals(googleads.oauth2.GetAPIScope(self.api_name_dfa),
- self.scope_dfa)
-
- def testGetAPIScope_dfp(self):
- self.assertEquals(googleads.oauth2.GetAPIScope(self.api_name_dfp),
- self.scope_dfp)
+ def testGetAPIScope_ad_manager(self):
+ self.assertEqual(googleads.oauth2.GetAPIScope(self.api_name_ad_manager),
+ self.scope_ad_manager)
class GoogleOAuth2ClientTest(unittest.TestCase):
@@ -72,11 +60,37 @@ def testCreateHttpHeader(self):
NotImplementedError,
googleads.oauth2.GoogleOAuth2Client().CreateHttpHeader)
+
+class GoogleRefreshableOAuth2ClientTest(unittest.TestCase):
+ """Tests for the googleads.oauth2.GoogleRefreshableOAuth2Client class."""
+
def testRefresh(self):
"""For coverage."""
self.assertRaises(
NotImplementedError,
- googleads.oauth2.GoogleOAuth2Client().Refresh)
+ googleads.oauth2.GoogleRefreshableOAuth2Client().Refresh)
+
+
+class GoogleAccessTokenClientTest(unittest.TestCase):
+ """Tests for the googleads.oauth2.GoogleAccessTokenClient class."""
+
+ def setUp(self):
+ self.access_token = 'a'
+ self.token_expiry = (datetime.datetime.utcnow() +
+ datetime.timedelta(seconds=3600))
+ self.expired_token_expiry = datetime.datetime(1980, 1, 1, 12)
+
+ def testCreateHttpHeader(self):
+ client = googleads.oauth2.GoogleAccessTokenClient(
+ self.access_token, self.token_expiry)
+ expected_header = {'authorization': 'Bearer %s' % self.access_token}
+ self.assertEqual(client.CreateHttpHeader(), expected_header)
+
+ def testCreateHttpHeaderWithExpiredToken(self):
+ expired_client = googleads.oauth2.GoogleAccessTokenClient(
+ self.access_token, self.expired_token_expiry)
+ self.assertRaises(googleads.errors.GoogleAdsError,
+ expired_client.CreateHttpHeader)
class GoogleRefreshTokenClientTest(unittest.TestCase):
@@ -86,68 +100,142 @@ def setUp(self):
self.client_id = 'client_id'
self.client_secret = 'itsasecret'
self.refresh_token = 'refreshing'
- self.proxy_info = httplib2.ProxyInfo(socks.PROXY_TYPE_HTTP, 'myproxy.com',
- 443)
- self.https_proxy = '%s:%s' % (self.proxy_info.proxy_host,
- self.proxy_info.proxy_port)
self.access_token_unrefreshed = 'a'
self.access_token_refreshed = 'b'
- # Mock out httplib2.Http for testing.
- self.http = mock.Mock(spec=httplib2.Http)
- self.opener = self.http.return_value = mock.Mock()
- self.opener.proxy_info = self.proxy_info
- self.opener.ca_certs = None
- self.opener.disable_ssl_certificate_valiation = True
-
- # Mock out oauth2client.client.OAuth2Credentials for testing
- self.oauth2_credentials = mock.Mock(spec=OAuth2Credentials)
- self.mock_oauth2_credentials = self.oauth2_credentials.return_value = (
- mock.Mock())
- self.mock_oauth2_credentials.access_token = self.access_token_unrefreshed
- self.mock_oauth2_credentials.token_expiry = datetime.datetime(1980, 1, 1,
- 12)
-
- def apply(headers):
- headers['Authorization'] = ('Bearer %s'
- % self.mock_oauth2_credentials.access_token)
-
- def refresh(mock_http):
- self.mock_oauth2_credentials.access_token = self.access_token_refreshed
- self.mock_oauth2_credentials.token_expiry = datetime.datetime.utcnow()
-
- self.mock_oauth2_credentials.apply = mock.Mock(side_effect=apply)
- self.mock_oauth2_credentials.refresh = mock.Mock(side_effect=refresh)
- with mock.patch('oauth2client.client.OAuth2Credentials',
- self.oauth2_credentials):
- self.googleads_client = googleads.oauth2.GoogleRefreshTokenClient(
+ # Mock out google.auth.transport.Request for testing.
+ self.mock_req = mock.Mock(spec=Request)
+ self.mock_req.return_value = mock.Mock()
+ self.mock_req_instance = self.mock_req.return_value
+
+ # Mock out google.oauth2.credentials.Credentials for testing
+ self.mock_credentials = mock.Mock(spec=Credentials)
+ self.mock_credentials.return_value = mock.Mock()
+ self.mock_credentials_instance = self.mock_credentials.return_value
+ self.mock_credentials_instance.token = self.access_token_unrefreshed
+ self.mock_credentials_instance.expiry = datetime.datetime(1980, 1, 1, 12)
+ self.mock_credentials_instance.expired = True
+
+ def apply(headers, token=None):
+ headers['authorization'] = ('Bearer %s'
+ % self.mock_credentials_instance.token)
+
+ def refresh(request):
+ self.mock_credentials_instance.token = self.access_token_refreshed
+ self.mock_credentials_instance.expiry = datetime.datetime.utcnow()
+
+ self.mock_credentials_instance.apply = mock.Mock(side_effect=apply)
+ self.mock_credentials_instance.refresh = mock.Mock(side_effect=refresh)
+ with mock.patch('google.oauth2.credentials.Credentials',
+ self.mock_credentials):
+ self.refresh_client = googleads.oauth2.GoogleRefreshTokenClient(
self.client_id, self.client_secret, self.refresh_token,
- self.proxy_info)
+ access_token=self.access_token_unrefreshed,
+ token_expiry=self.mock_credentials_instance.expiry)
def testCreateHttpHeader_noRefresh(self):
- header = {'Authorization': 'Bearer %s' % self.access_token_unrefreshed}
- self.mock_oauth2_credentials.token_expiry = None
- self.assertEqual(header, self.googleads_client.CreateHttpHeader())
+ header = {'authorization': 'Bearer %s' % self.access_token_unrefreshed}
+ self.mock_credentials_instance.expiry = (
+ datetime.datetime.utcnow() + datetime.timedelta(hours=1))
+ self.mock_credentials_instance.expired = False
+ self.assertEqual(header, self.refresh_client.CreateHttpHeader())
def testCreateHttpHeader_refresh(self):
- header = {u'Authorization': 'Bearer %s' % self.access_token_refreshed}
-
- with mock.patch('httplib2.Http', self.http):
- self.assertEqual(header, self.googleads_client.CreateHttpHeader())
- self.http.assert_called_once_with(
- ca_certs=None, proxy_info=self.proxy_info,
- disable_ssl_certificate_validation=False)
- self.mock_oauth2_credentials.refresh.assert_called_once_with(
- self.opener)
+ expected_header = {u'authorization': 'Bearer %s'
+ % self.access_token_refreshed}
+
+ with mock.patch('requests.Session') as mock_session:
+ mock_session_instance = mock.MagicMock()
+ mock_session.return_value = mock_session_instance
+ mock_session_instance.__enter__.return_value = mock_session_instance
+ mock_session_instance.__exit__.return_value = None
+ with mock.patch('google.auth.transport.requests.Request', self.mock_req):
+ header = self.refresh_client.CreateHttpHeader()
+ self.assertEqual(mock_session_instance.proxies, {})
+ self.assertEqual(mock_session_instance.verify, True)
+ self.assertIsNone(mock_session_instance.cert)
+ self.mock_req.assert_called_once_with(session=mock_session_instance)
+ self.assertEqual(expected_header, header)
+ self.mock_credentials_instance.refresh.assert_called_once_with(
+ self.mock_req_instance)
+
+ def testCreateHttpHeader_refreshWithConfiguredProxyConfig(self):
+ https_proxy = 'http://myproxy.com:443'
+ expected_proxies = {'https': https_proxy}
+ proxy_config = googleads.common.ProxyConfig(https_proxy=https_proxy)
+ self.refresh_client.proxy_config = proxy_config
+
+ expected_header = {u'authorization': 'Bearer %s'
+ % self.access_token_refreshed}
+
+ with mock.patch('requests.Session') as mock_session:
+ mock_session_instance = mock.MagicMock()
+ mock_session.return_value = mock_session_instance
+ mock_session_instance.__enter__.return_value = mock_session_instance
+ mock_session_instance.__exit__.return_value = None
+ with mock.patch('google.auth.transport.requests.Request', self.mock_req):
+ header = self.refresh_client.CreateHttpHeader()
+ self.assertEqual(mock_session_instance.proxies, expected_proxies)
+ self.assertEqual(mock_session_instance.verify,
+ not proxy_config.disable_certificate_validation)
+ self.assertEqual(mock_session_instance.cert,
+ proxy_config.cafile)
+ self.mock_req.assert_called_once_with(session=mock_session_instance)
+ self.assertEqual(expected_header, header)
+ self.mock_credentials_instance.refresh.assert_called_once_with(
+ self.mock_req_instance)
def testCreateHttpHeader_refreshFails(self):
- self.mock_oauth2_credentials.refresh.side_effect = AccessTokenRefreshError(
+ self.mock_credentials_instance.refresh.side_effect = RefreshError(
'Invalid response 400')
- with mock.patch('httplib2.Http', self.http):
- self.assertRaises(AccessTokenRefreshError,
- self.googleads_client.CreateHttpHeader)
- self.assertFalse(self.mock_oauth2_credentials.apply.called)
+ with mock.patch('google.auth.transport.requests.Request', self.mock_req):
+ self.assertRaises(RefreshError,
+ self.refresh_client.CreateHttpHeader)
+ self.assertFalse(self.mock_credentials_instance.apply.called)
+
+
+class GoogleCredentialsClientTest(unittest.TestCase):
+ """Tests for the googleads.oauth2.GoogleCredentialsClient class."""
+
+ def setUp(self):
+ self.access_token = 'a'
+
+ # Mock out google.auth.transport.Request for testing.
+ self.mock_req = mock.Mock(spec=Request)
+ self.mock_req.return_value = mock.Mock()
+ self.mock_req_instance = self.mock_req.return_value
+
+ # Mock out google.oauth2.credentials.Credentials for testing
+ self.mock_credentials = mock.Mock(spec=Credentials)
+ self.mock_credentials.expiry = None
+
+ def apply(headers, token=None):
+ headers['authorization'] = ('Bearer %s' % self.access_token)
+
+ self.mock_credentials.apply = mock.Mock(side_effect=apply)
+
+ self.client = googleads.oauth2.GoogleCredentialsClient(
+ self.mock_credentials)
+
+ def testRefresh(self):
+ with mock.patch('google.auth.transport.requests.Request', self.mock_req):
+ self.client.Refresh()
+ self.mock_req.assert_called_once()
+
+ def testCreateHttpHeader_credentialsExpired(self):
+ self.mock_credentials.expiry = object()
+ self.mock_credentials.expired = True
+ with mock.patch('google.auth.transport.requests.Request', self.mock_req):
+ self.client.CreateHttpHeader()
+ self.mock_req.assert_called_once()
+
+ def testCreateHttpHeader_applyCredentialsToken(self):
+ expected_header = {u'authorization': 'Bearer %s' % self.access_token}
+
+ with mock.patch('google.auth.transport.requests.Request', self.mock_req):
+ header = self.client.CreateHttpHeader()
+ self.assertEqual(header, expected_header)
class GoogleServiceAccountTest(unittest.TestCase):
@@ -155,85 +243,128 @@ class GoogleServiceAccountTest(unittest.TestCase):
def setUp(self):
self.scope = 'scope'
- self.service_account_email = 'email@email.com'
- self.private_key_password = 'notasecret'
- self.proxy_info = httplib2.ProxyInfo(socks.PROXY_TYPE_HTTP, 'myproxy.com',
- 443)
- self.https_proxy = '%s:%s' % (self.proxy_info.proxy_host,
- self.proxy_info.proxy_port)
- self.access_token_unrefreshed = 'a'
- self.access_token_refreshed = 'b'
+ self.private_key = b'IT\'S A SECRET TO EVERYBODY.'
+ self.delegated_account = 'delegated_account@delegated.com'
# Mock out filesystem and file for testing.
filesystem = fake_filesystem.FakeFilesystem()
tempfile = fake_tempfile.FakeTempfileModule(filesystem)
- fake_open = fake_filesystem.FakeFileOpen(filesystem)
- key_file_path = tempfile.NamedTemporaryFile(delete=False).name
-
- with fake_open(key_file_path, 'w') as file_handle:
- file_handle.write('IT\'S A SECRET TO EVERYBODY.')
-
- # Mock out httplib2.Http for testing.
- self.http = mock.Mock(spec=httplib2.Http)
- self.opener = self.http.return_value = mock.Mock()
- self.opener.proxy_info = self.proxy_info
- self.opener.ca_certs = None
- self.opener.disable_ssl_certificate_valiation = True
-
- # Mock out oauth2client.client.OAuth2Credentials for testing
- self.oauth2_credentials = mock.Mock(spec=SignedJwtAssertionCredentials)
- self.mock_oauth2_credentials = self.oauth2_credentials.return_value = (
- mock.Mock())
- self.mock_oauth2_credentials.access_token = 'x'
- self.mock_oauth2_credentials.token_expiry = datetime.datetime(1980, 1, 1,
- 12)
-
- def apply(headers):
- headers['Authorization'] = ('Bearer %s'
- % self.mock_oauth2_credentials.access_token)
-
- def refresh(mock_http):
- self.mock_oauth2_credentials.access_token = (
+ self.fake_open = fake_filesystem.FakeFileOpen(filesystem)
+ self.key_file_path = tempfile.NamedTemporaryFile(delete=False).name
+ self.cert_file_path = tempfile.NamedTemporaryFile(
+ delete=False, prefix='cert_', suffix='.pem').name
+
+ with self.fake_open(self.key_file_path, 'wb') as file_handle:
+ file_handle.write(self.private_key)
+
+ self.access_token_unrefreshed = 'a'
+ self.access_token_refreshed = 'b'
+
+ # Mock out google.auth.transport.Request for testing.
+ self.mock_req = mock.Mock(spec=Request)
+ self.mock_req.return_value = mock.Mock()
+ self.mock_req_instance = self.mock_req.return_value
+
+ # Mock out service account credentials for testing.
+ self.mock_credentials = mock.Mock()
+ self.mock_credentials.from_service_account_file.return_value = mock.Mock()
+ self.mock_credentials_instance = (
+ self.mock_credentials.from_service_account_file.return_value
+ )
+ self.mock_credentials_instance.token = 'x'
+ self.mock_credentials_instance.expiry = datetime.datetime(
+ 1980, 1, 1, 12)
+ self.mock_credentials_instance.expired = True
+
+ def apply(headers, token=None):
+ headers['authorization'] = ('Bearer %s'
+ % self.mock_credentials_instance.token)
+
+ def refresh(request):
+ self.mock_credentials_instance.token = (
self.access_token_unrefreshed if
- self.mock_oauth2_credentials.access_token is 'x'
+ self.mock_credentials_instance.token == 'x'
else self.access_token_refreshed)
- self.mock_oauth2_credentials.token_expiry = datetime.datetime.utcnow()
-
- self.mock_oauth2_credentials.apply = mock.Mock(side_effect=apply)
- self.mock_oauth2_credentials.refresh = mock.Mock(side_effect=refresh)
- with mock.patch('__builtin__.open', fake_open):
- with mock.patch('oauth2client.client.SignedJwtAssertionCredentials',
- self.oauth2_credentials):
- self.googleads_client = googleads.oauth2.GoogleServiceAccountClient(
- self.scope, self.service_account_email, key_file_path,
- self.private_key_password, proxy_info=self.proxy_info)
+ self.mock_credentials_instance.token_expiry = datetime.datetime.utcnow()
+
+ self.mock_credentials_instance.apply = mock.Mock(side_effect=apply)
+ self.mock_credentials_instance.refresh = mock.Mock(side_effect=refresh)
+ with mock.patch('builtins.open', self.fake_open):
+ with mock.patch('google.oauth2.service_account.Credentials',
+ self.mock_credentials):
+ self.sa_client = googleads.oauth2.GoogleServiceAccountClient(
+ self.key_file_path, self.scope)
# Undo the call count for the auto-refresh
- self.mock_oauth2_credentials.refresh.reset_mock()
+ self.mock_credentials_instance.refresh.reset_mock()
+
+ def testCreateDelegatedGoogleServiceAccountClient(self):
+ with mock.patch('google.oauth2.service_account.Credentials') as mock_cred:
+ # Create a GoogleServiceAccountClient and verify that the delegated
+ # service account Credentials were correctly instantiated.
+ googleads.oauth2.GoogleServiceAccountClient(
+ self.key_file_path, self.scope, sub=self.delegated_account)
+ mock_cred.from_service_account_file.assert_called_once_with(
+ self.key_file_path, scopes=[self.scope],
+ subject=self.delegated_account)
def testCreateHttpHeader_noRefresh(self):
- header = {'Authorization': 'Bearer %s' % self.access_token_unrefreshed}
- self.mock_oauth2_credentials.token_expiry = None
- self.assertEqual(header, self.googleads_client.CreateHttpHeader())
+ header = {'authorization': 'Bearer %s' % self.access_token_unrefreshed}
+ self.mock_credentials_instance.expiry = (
+ datetime.datetime.utcnow() + datetime.timedelta(hours=1))
+ self.mock_credentials_instance.expired = False
+ self.assertEqual(header, self.sa_client.CreateHttpHeader())
def testCreateHttpHeader_refresh(self):
- header = {u'Authorization': 'Bearer %s' % self.access_token_refreshed}
-
- with mock.patch('httplib2.Http', self.http):
- self.assertEqual(header, self.googleads_client.CreateHttpHeader())
- self.http.assert_called_once_with(
- ca_certs=None, proxy_info=self.proxy_info,
- disable_ssl_certificate_validation=False)
- self.mock_oauth2_credentials.refresh.assert_called_once_with(
- self.opener)
+ expected_header = {'authorization': 'Bearer %s'
+ % self.access_token_refreshed}
+ with mock.patch('requests.Session') as mock_session:
+ mock_session_instance = mock.MagicMock()
+ mock_session.return_value = mock_session_instance
+ mock_session_instance.__enter__.return_value = mock_session_instance
+ mock_session_instance.__exit__.return_value = None
+ with mock.patch('google.auth.transport.requests.Request', self.mock_req):
+ header = self.sa_client.CreateHttpHeader()
+ self.assertEqual(mock_session_instance.proxies, {})
+ self.assertEqual(mock_session_instance.verify, True)
+ self.assertIsNone(mock_session_instance.cert)
+ self.mock_req.assert_called_once_with(session=mock_session_instance)
+ self.assertEqual(expected_header, header)
+ self.mock_credentials_instance.refresh.assert_called_once_with(
+ self.mock_req_instance)
+
+ def testCreateHttpHeader_refreshWithConfiguredProxyConfig(self):
+ https_proxy = 'http://myproxy.com:443'
+ proxy_config = googleads.common.ProxyConfig(https_proxy=https_proxy)
+ expected_proxies = {'https': https_proxy}
+ self.sa_client.proxy_config = proxy_config
+
+ expected_header = {'authorization': 'Bearer %s'
+ % self.access_token_refreshed}
+
+ with mock.patch('requests.Session') as mock_session:
+ mock_session_instance = mock.MagicMock()
+ mock_session.return_value = mock_session_instance
+ mock_session_instance.__enter__.return_value = mock_session_instance
+ mock_session_instance.__exit__.return_value = None
+ with mock.patch('google.auth.transport.requests.Request', self.mock_req):
+ header = self.sa_client.CreateHttpHeader()
+ self.assertEqual(mock_session_instance.proxies, expected_proxies)
+ self.assertEqual(mock_session_instance.verify,
+ not proxy_config.disable_certificate_validation)
+ self.assertEqual(mock_session_instance.cert,
+ proxy_config.cafile)
+ self.mock_req.assert_called_once_with(session=mock_session_instance)
+ self.assertEqual(expected_header, header)
+ self.mock_credentials_instance.refresh.assert_called_once_with(
+ self.mock_req_instance)
def testCreateHttpHeader_refreshFails(self):
- self.mock_oauth2_credentials.refresh.side_effect = AccessTokenRefreshError(
+ self.mock_credentials_instance.refresh.side_effect = RefreshError(
'Invalid response 400')
- with mock.patch('httplib2.Http', self.http):
- self.assertRaises(AccessTokenRefreshError,
- self.googleads_client.CreateHttpHeader)
- self.assertFalse(self.mock_oauth2_credentials.apply.called)
+ with mock.patch('google.auth.transport.requests.Request', self.mock_req):
+ self.assertRaises(RefreshError, self.sa_client.CreateHttpHeader)
+ self.assertFalse(self.mock_credentials_instance.apply.called)
if __name__ == '__main__':
diff --git a/tests/test_data/ad_manager_report_service.xml b/tests/test_data/ad_manager_report_service.xml
new file mode 100644
index 00000000..ff84c1a0
--- /dev/null
+++ b/tests/test_data/ad_manager_report_service.xml
@@ -0,0 +1,9326 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Encapsulates an Image media. For {@code SET},{@code REMOVE} operations in MediaService, use {@code mediaId}.
+
+
+
+
+
+
+
+ Raw image data.
+
+
+
+
+
+
+
+
+
+ Contains an object value.
+ <p>
+ <b>This object is experimental!
+ <code>ObjectValue</code> is an experimental, innovative, and rapidly
+ changing new feature for DFP. Unfortunately, being on the bleeding edge means that we may make
+ backwards-incompatible changes to
+ <code>ObjectValue</code>. We will inform the community when this feature
+ is no longer experimental.</b>
+
+
+
+
+
+
+
+
+
+
+
+ The API error base class that provides details about an error that occurred
+ while processing a service request.
+
+ <p>The OGNL field path is provided for parsers to identify the request data
+ element that may have caused the error.</p>
+
+
+
+
+
+
+ The OGNL field path to identify cause of error.
+
+
+
+
+
+
+ A parsed copy of the field path. For example, the field path "operations[1].operand"
+ corresponds to this list: {FieldPathElement(field = "operations", index = 1),
+ FieldPathElement(field = "operand", index = null)}.
+
+
+
+
+
+
+ The data that caused the error.
+
+
+
+
+
+
+ A simple string representation of the error and reason.
+
+
+
+
+
+
+
+
+ Exception class for holding a list of service errors.
+
+
+
+
+
+
+
+
+ List of errors.
+
+
+
+
+
+
+
+
+
+
+ Errors related to the usage of API versions.
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Base class for exceptions.
+
+
+
+
+
+
+ Error message.
+
+
+
+
+
+
+
+
+ An error for an exception that occurred when authenticating.
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Contains a boolean value.
+
+
+
+
+
+
+
+
+ The boolean value.
+
+
+
+
+
+
+
+
+
+
+ Error for the size of the collection being too large
+
+
+
+
+
+
+
+
+
+
+
+
+
+ A place for common errors that can be used across services.
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Errors related to currency codes.
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Represents a date.
+
+
+
+
+
+
+ Year (e.g., 2009)
+
+
+
+
+
+
+ Month (1..12)
+
+
+
+
+
+
+ Day (1..31)
+
+
+
+
+
+
+
+
+ Represents a date combined with the time of day.
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Contains a date-time value.
+
+
+
+
+
+
+
+
+ The {@code DateTime} value.
+
+
+
+
+
+
+
+
+
+
+ Contains a date value.
+
+
+
+
+
+
+
+
+ The {@code Date} value.
+
+
+
+
+
+
+
+
+
+
+ Errors related to feature management. If you attempt using a feature that is not available to
+ the current network you'll receive a FeatureError with the missing feature as the trigger.
+
+
+
+
+
+
+
+
+
+
+
+
+
+ A segment of a field path. Each dot in a field path defines a new segment.
+
+
+
+
+
+
+ The name of a field in lower camelcase. (e.g. "biddingStrategy")
+
+
+
+
+
+
+ For list fields, this is a 0-indexed position in the list. Null for non-list fields.
+
+
+
+
+
+
+
+
+ Indicates that a server-side error has occured. {@code InternalApiError}s
+ are generally not the result of an invalid request or message sent by the
+ client.
+
+
+
+
+
+
+
+
+ The error reason represented by an enum.
+
+
+
+
+
+
+
+
+
+
+ Caused by supplying a null value for an attribute that cannot be null.
+
+
+
+
+
+
+
+
+ The error reason represented by an enum.
+
+
+
+
+
+
+
+
+
+
+ Contains a numeric value.
+
+
+
+
+
+
+
+
+ The numeric value represented as a string.
+
+
+
+
+
+
+
+
+
+
+ Lists errors related to parsing.
+
+
+
+
+
+
+
+
+ The error reason represented by an enum.
+
+
+
+
+
+
+
+
+
+
+ Errors related to incorrect permission.
+
+
+
+
+
+
+
+
+
+
+
+
+
+ An error that occurs while executing a PQL query contained in
+ a {@link Statement} object.
+
+
+
+
+
+
+
+
+ The error reason represented by an enum.
+
+
+
+
+
+
+
+
+
+
+ An error that occurs while parsing a PQL query contained in a
+ {@link Statement} object.
+
+
+
+
+
+
+
+
+ The error reason represented by an enum.
+
+
+
+
+
+
+
+
+
+
+ Describes a client-side error on which a user is attempting
+ to perform an action to which they have no quota remaining.
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Represents the options for an API report download request.
+ See {@link ReportService#getReportDownloadUrlWithOptions}.
+
+
+
+
+
+
+ The {@link ExportFormat} used to generate the report.
+ Default value is {@link ExportFormat#CSV_DUMP}.
+
+
+
+
+
+
+ Whether or not to include the report properties (e.g. network, user, date generated...)
+ in the generated report.
+ Default is false.
+
+
+
+
+
+
+ Whether or not to include the totals row.
+ Default is true for all formats except {@link ExportFormat#CSV_DUMP}.
+
+
+
+
+
+
+ Whether or not to compress the report file to a gzip file.
+ Default is true.
+ <p>
+ Regardless of value, gzip http compression is available from the URL by normal means.
+
+
+
+
+
+
+
+
+ An error for an exception that occurred while running the report.
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Represents a report job that will be run to retrieve performance and
+ statistics information about ad campaigns, networks, inventory and sales.
+
+
+
+
+
+
+ The unique ID of the {@code ReportJob}. This value is read-only and is
+ assigned by Google.
+
+
+
+
+
+
+ Holds the filtering criteria.
+
+
+
+
+
+
+
+
+ A {@code ReportQuery} object allows you to specify the selection criteria for
+ generating a report. Only reports with at least one {@link Column} are supported.
+
+
+
+
+
+
+ The list of break-down types being requested in the report.
+ The generated report will contain the dimensions in the same order as requested.
+ This field is required.
+
+
+
+
+
+
+ The ad unit view for the report. Defaults to {@link AdUnitView#TOP_LEVEL}.
+
+
+
+
+
+
+ The list of trafficking statistics and revenue information being requested
+ in the report. The generated report will contain the columns in the same
+ order as requested. This field is required.
+
+
+
+
+
+
+ The list of break-down attributes being requested in this report. Some
+ {@link DimensionAttribute} values can only be used with certain
+ {@link Dimension} values that must be included in the {@link #dimensions}
+ attribute. The generated report will contain the attributes in the same
+ order as requested.
+
+
+
+
+
+
+ The list of {@link CustomField#id} being requested in this report.
+ To add a {@link CustomField} to the report, you must include
+ its corresponding {@link Dimension}, determined by the {@link CustomField#entityType},
+ as a {@link #dimensions dimension}.
+
+ <table>
+ <tr>
+ <th scope="col" colspan="2">{@link CustomFieldEntityType#entityType}</th>
+ </tr>
+ <tr>
+ <td>{@link CustomFieldEntityType#LINE_ITEM}</td><td>{@link Dimension#LINE_ITEM_NAME}</td>
+ </tr>
+ <tr>
+ <td>{@link CustomFieldEntityType#ORDER}</td><td>{@link Dimension#ORDER_NAME}</td>
+ </tr>
+ <tr>
+ <td>{@link CustomFieldEntityType#CREATIVE}</td><td>{@link Dimension#CREATIVE_NAME}</td>
+ </tr>
+ <tr>
+ <td>{@link CustomFieldEntityType#PRODUCT_TEMPLATE}</td>
+ <td>{@link Dimension#PRODUCT_TEMPLATE_NAME}</td>
+ </tr>
+ <tr>
+ <td>{@link CustomFieldEntityType#PRODUCT}</td><td>{@link Dimension#PRODUCT_NAME}</td>
+ </tr>
+ <tr>
+ <td>{@link CustomFieldEntityType#PROPOSAL}</td><td>{@link Dimension#PROPOSAL_NAME}</td>
+ </tr>
+ <tr>
+ <td>{@link CustomFieldEntityType#PROPOSAL_LINE_ITEM}</td>
+ <td>{@link Dimension#PROPOSAL_LINE_ITEM_NAME}</td>
+ </tr>
+ </table>
+
+
+
+
+
+
+ The list of content metadata hierarchy custom targeting key {@link CustomTargetingKey#id IDs}
+ being requested in this report. Each of these IDs must have been defined in the
+ {@link ContentMetadataKeyHierarchy content metadata key hierarchy}. This will include
+ dimensions in the form of {@code CONTENT_HIERARCHY_CUSTOM_TARGETING_KEY[id]_ID} and
+ {@code CONTENT_HIERARCHY_CUSTOM_TARGETING_KEY[id]_VALUE} where where {@code ID} is the ID of
+ the {@link CustomTargetingValue#id custom targeting value} and {@code VALUE} is the
+ {@link CustomTargetingValue#name name}.
+ <p>
+ To add {@link CustomTargetingKey#id IDs}, you must include {@link Dimension#CONTENT_HIERARCHY}
+ in {@link #dimensions}, and specify a non-empty list of custom targeting key IDs. The order of
+ content hierarchy columns in the report correspond to the place of
+ {@link Dimension#CONTENT_HIERARCHY} in {@link #dimensions}. For example, if {@link #dimensions}
+ contains the following dimensions in the order: {@link Dimension#ADVERTISER_NAME},
+ {@link Dimension#CONTENT_HIERARCHY} and {@link Dimension#COUNTRY_NAME}, and
+ {@link #contentMetadataKeyHierarchyCustomTargetingKeyIds} contains the following IDs in the
+ order: 1001 and 1002. The order of dimensions in the report will be:
+ Dimension.ADVERTISER_NAME,
+ Dimension.CONTENT_HIERARCHY_CUSTOM_TARGETING_KEY[1001]_VALUE,
+ Dimension.CONTENT_HIERARCHY_CUSTOM_TARGETING_KEY[1002]_VALUE,
+ Dimension.COUNTRY_NAME,
+ Dimension.ADVERTISER_ID,
+ Dimension.CONTENT_HIERARCHY_CUSTOM_TARGETING_KEY[1001]_ID,
+ Dimension.CONTENT_HIERARCHY_CUSTOM_TARGETING_KEY[1002]_ID,
+ Dimension.COUNTRY_CRITERIA_ID
+
+
+
+
+
+
+ The start date from which the reporting information is gathered. The
+ {@code ReportQuery#dateRangeType} field must be set to
+ {@link DateRangeType#CUSTOM_DATE} in order to use this.
+
+
+
+
+
+
+ The end date upto which the reporting information is gathered. The
+ {@code ReportQuery#dateRangeType} field must be set to
+ {@link DateRangeType#CUSTOM_DATE} in order to use this.
+
+
+
+
+
+
+ The period of time for which the reporting data is being generated. In
+ order to define custom time periods, set this to
+ {@link DateRangeType#CUSTOM_DATE}. If set to {@link DateRangeType#CUSTOM_DATE}, then
+ {@link ReportQuery#startDate} and {@link ReportQuery#endDate} will be used.
+
+
+
+
+
+
+ Specifies a filter to use for reporting on data. This filter will be used
+ in conjunction (joined with an AND statement) with the date range selected
+ through {@link #dateRangeType}, {@link #startDate}, and {@link #endDate}
+ and the dimension filters selected through {@link #dimensionFilters}.
+
+ The syntax currently allowed for {@link Statement#query} is<br>
+ <code> [WHERE <condition> {AND <condition> ...}]<code><br>
+ <p><condition></code><br>
+ <code>:= <property> = <value></code><br>
+ <code><condition></code><br>
+ <code>:= <property> = <bind variable></code><br>
+ <code><condition> := <property> IN <list></code><br>
+ <code><bind variable> := :<name></code><br>
+ </code> where property is the enumeration name of a {@link Dimension} that
+ can be filtered.
+ <p>
+ For example, the statement "WHERE LINE_ITEM_ID IN (34344, 23235)" can be used
+ to generate a report for a specific set of line items
+ <p>
+ Filtering on IDs is highly recommended over filtering on names, especially
+ for geographical entities. When filtering on names, matching is case
+ sensitive.
+
+
+
+
+
+
+ Whether report includes rows with all zero metric values. This field is only eligible
+ for sales reports. This field is optional and defaults to {@code false}.
+
+
+
+
+
+
+ The currency for Ad Exchange revenue metrics. This field is only valid for Ad Exchange metrics,
+ and an exception will be thrown if this field is used with non-Ad Exchange metrics. Defaults to
+ the network currency if left {@code null}. The supported currency codes can be found in
+ <a href="https://support.google.com/adxseller/answer/6019533"> this Help Center article.</a>
+
+
+
+
+
+
+ Gets the {@link TimeZoneType} for this report, which determines the time zone used for the
+ report's date range. Defaults to {@link TimeZoneType.PUBLISHER}.
+
+
+
+
+
+
+
+
+ A list of all errors to be used for validating sizes of collections.
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Errors due to missing required field.
+
+
+
+
+
+
+
+
+ The error reason represented by an enum.
+
+
+
+
+
+
+
+
+
+
+ A saved {@link ReportQuery} representing the selection criteria for running a report.
+
+
+
+
+
+
+ The ID of the saved query.
+
+
+
+
+
+
+ The name of the saved query.
+
+
+
+
+
+
+ The {@link ReportQuery} representing the selection criteria for the saved query.
+ This will be non-null if and only if {@link SavedQuery#isCompatibleWithApiVersion} is
+ {@code true}.
+
+
+
+
+
+
+ Whether or not the saved query is compatible with the current API version.
+ This will be {@code true} if and only if {@link SavedQuery#reportQuery} is non-null.
+ A saved query will be incompatible with the API if it uses columns, dimensions, or other
+ reporting features from the UI that are not available in the {@link ReportQuery} entity.
+
+
+
+
+
+
+
+
+ A page of {@link SavedQuery} objects.
+
+
+
+
+
+
+ The size of the total result set to which this page belongs.
+
+
+
+
+
+
+ The absolute index in the total result set on which this page begins.
+
+
+
+
+
+
+ The collection of saved queries contained within this page.
+
+
+
+
+
+
+
+
+ Errors related to the server.
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Contains a set of {@link Value Values}. May not contain duplicates.
+
+
+
+
+
+
+
+
+ The values. They must all be the same type of {@code Value} and not contain duplicates.
+
+
+
+
+
+
+
+
+
+
+ Represents the SOAP request header used by API requests.
+
+
+
+
+
+
+ The network code to use in the context of a request.
+
+
+
+
+
+
+ The name of client library application.
+
+
+
+
+
+
+
+
+ Represents the SOAP request header used by API responses.
+
+
+
+
+
+
+
+
+
+
+ Captures the {@code WHERE}, {@code ORDER BY} and {@code LIMIT} clauses of a
+ PQL query. Statements are typically used to retrieve objects of a predefined
+ domain type, which makes SELECT clause unnecessary.
+ <p>
+ An example query text might be {@code "WHERE status = 'ACTIVE' ORDER BY id
+ LIMIT 30"}.
+ </p>
+ <p>
+ Statements support bind variables. These are substitutes for literals
+ and can be thought of as input parameters to a PQL query.
+ </p>
+ <p>
+ An example of such a query might be {@code "WHERE id = :idValue"}.
+ </p>
+ <p>
+ Statements also support use of the LIKE keyword. This provides partial and
+ wildcard string matching.
+ </p>
+ <p>
+ An example of such a query might be {@code "WHERE name LIKE 'startswith%'"}.
+ </p>
+ The value for the variable idValue must then be set with an object of type
+ {@link Value}, e.g., {@link NumberValue}, {@link TextValue} or
+ {@link BooleanValue}.
+
+
+
+
+
+
+ Holds the query in PQL syntax. The syntax is:<br>
+ <code>[WHERE <condition> {[AND | OR] <condition> ...}]</code><br>
+ <code>[ORDER BY <property> [ASC | DESC]]</code><br>
+ <code>[LIMIT {[<offset>,] <count>} | {<count> OFFSET <offset>}]</code><br>
+ <p>
+ <code><condition></code><br>
+
+ <code>:= <property> {< | <= | > | >= | = | != } <value></code><br>
+ <code><condition></code><br>
+
+ <code>:= <property> {< | <= | > | >= | = | != } <bind variable></code><br>
+ <code><condition> := <property> IN <list></code><br>
+ <code><condition> := <property> IS NULL</code><br>
+ <code><condition> := <property> LIKE <wildcard%match></code><br>
+ <code><bind variable> := :<name></code><br>
+ </p>
+
+
+
+
+
+
+ Holds keys and values for bind variables and their values. The key is the
+ name of the bind variable. The value is the literal value of the variable.
+ <p>
+ In the example {@code "WHERE status = :bindStatus ORDER BY id LIMIT 30"},
+ the bind variable, represented by {@code :bindStatus} is named {@code
+ bindStatus}, which would also be the parameter map key. The bind variable's
+ value would be represented by a parameter map value of type
+ {@link TextValue}. The final result, for example, would be an entry of
+ {@code "bindStatus" => StringParam("ACTIVE")}.
+ </p>
+
+
+
+
+
+
+
+
+ An error that occurs while parsing {@link Statement} objects.
+
+
+
+
+
+
+
+
+ The error reason represented by an enum.
+
+
+
+
+
+
+
+
+
+
+ A list of error code for reporting invalid content of input strings.
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Errors for Strings which do not meet given length constraints.
+
+
+
+
+
+
+
+
+
+
+
+
+
+ This represents an entry in a map with a key of type String
+ and value of type Value.
+
+
+
+
+
+
+
+
+
+
+ Contains a string value.
+
+
+
+
+
+
+
+
+ The string value.
+
+
+
+
+
+
+
+
+
+
+ {@code Value} represents a value.
+
+
+
+
+
+
+
+ A view for an ad unit report.
+
+
+
+
+
+
+ Only the top level ad units. Metrics include events for their
+ descendants that are not filtered out.
+
+
+
+
+
+
+ All the ad units. Metrics do not include events for the descendants.
+
+
+
+
+
+
+ Use the ad unit hierarchy. There will be as many ad unit columns as
+ levels of ad units in the generated report:
+ <ul>
+ <li>
+ The column {@link Dimension#AD_UNIT_NAME} is replaced with columns
+ "Ad unit 1", "Ad unit 2", ... "Ad unit n".
+ If level is not applicable to a row, "N/A" is returned as the value.
+ </li>
+ <li>
+ The column {@link Dimension#AD_UNIT_ID} is replaced with columns
+ "Ad unit ID 1", "Ad unit ID 2", ... "Ad unit ID n".
+ If level is not applicable to a row, "N/A" is returned as the value.
+ </li>
+ </ul>
+ <p>
+ Metrics do not include events for the descendants.
+
+
+
+
+
+
+
+
+
+
+ Indicates that the operation is not allowed in the version the request
+ was made in.
+
+
+
+
+
+
+ The value returned if the actual value is not exposed by the requested API version.
+
+
+
+
+
+
+
+
+
+
+ The SOAP message contains a request header with an ambiguous definition
+ of the authentication header fields. This means either the {@code
+ authToken} and {@code oAuthToken} fields were both null or both were
+ specified. Exactly one value should be specified with each request.
+
+
+
+
+
+
+ The login provided is invalid.
+
+
+
+
+
+
+ Tried to authenticate with provided information, but failed.
+
+
+
+
+
+
+ The OAuth provided is invalid.
+
+
+
+
+
+
+ The specified service to use was not recognized.
+
+
+
+
+
+
+ The SOAP message is missing a request header with an {@code authToken}
+ and optional {@code networkCode}.
+
+
+
+
+
+
+ The HTTP request is missing a request header with an {@code authToken}
+
+
+
+
+
+
+ The request is missing an {@code authToken}
+
+
+
+
+
+
+ The customer is not whitelisted for API access.
+
+
+
+
+
+
+ The user is not associated with any network.
+
+
+
+
+
+
+ No network for the given {@code networkCode} was found.
+
+
+
+
+
+
+ The user has access to more than one network, but did not provide a
+ {@code networkCode}.
+
+
+
+
+
+
+ An error happened on the server side during connection to authentication
+ service.
+
+
+
+
+
+
+ The user tried to create a test network using an account that already is
+ associated with a network.
+
+
+
+
+
+
+ The account is blocked and under investigation by the collections team. Please contact
+ Google for more information.
+
+
+
+
+
+
+ The value returned if the actual value is not exposed by the requested API version.
+
+
+
+
+
+
+
+
+
+
+
+ The value returned if the actual value is not exposed by the requested API version.
+
+
+
+
+
+
+
+
+ {@code Column} provides all the trafficking statistics and revenue
+ information available for the chosen {@link Dimension} objects.
+ <p>
+ Columns with {@code INVENTORY_LEVEL} should not be used with dimensions
+ relating to line items, orders, companies and creatives,
+ such as {@link Dimension#LINE_ITEM_NAME}.
+ Columns with {@code LINE_ITEM_LEVEL} can only be used if you have line item-level
+ dynamic allocation enabled on your network.
+
+
+
+
+
+
+ The number of impressions delivered by the ad server.
+ <p>Corresponds to "Ad server impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ The number of downloaded impressions delivered by the ad server.
+ <p>Corresponds to "Ad server downloaded impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ The number of impressions delivered by the ad server by explicit custom criteria targeting.
+ <p>Corresponds to "Ad server targeted impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The number of clicks delivered by the ad server.
+ <p>Corresponds to "Ad server clicks" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ The number of clicks delivered by the ad server by explicit custom criteria targeting.
+ <p>Corresponds to "Ad server targeted clicks" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The CTR for an ad delivered by the ad server.
+ <p>Corresponds to "Ad server CTR" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ The CPM and CPC revenue earned, calculated in publisher currency,
+ for the ads delivered by the ad server.
+ <p>Corresponds to "Ad server CPM and CPC revenue" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ The CPD revenue earned, calculated in publisher currency,
+ for the ads delivered by the ad server.
+ <p>Corresponds to "Ad server CPD revenue" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The CPA revenue earned, calculated in publisher currency, for the ads delivered by the
+ ad server.
+ <p>Corresponds to "CPA revenue" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The CPM, CPC and CPD revenue earned, calculated in publisher currency,
+ for the ads delivered by the ad server.
+ <p>Can correspond to any of the following in the DFP UI: Ad server CPM, CPC, CPD, and vCPM revenue, Ad server CPM, CPC and CPD revenue. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The average estimated cost-per-thousand-impressions earned from the CPM and CPC ads
+ delivered by the ad server.
+ <p>Corresponds to "Ad server average eCPM" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ The average estimated cost-per-thousand-impressions earned from the CPM, CPC and CPD ads
+ delivered by the ad server.
+
+
+
+
+
+
+ The ratio of the number of impressions delivered to the total impressions
+ delivered when no {@link LineItem} reservation could be found by the ad server
+ for inventory-level dynamic allocation.
+ For premium networks, this includes line item-level dynamic allocation as well.
+ Represented as a percentage.
+ <p>Corresponds to "Ad server impressions (%)" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The ratio of the number of impressions delivered to the total impressions
+ delivered by the ad server for line item-level dynamic allocation.
+ Represented as a percentage.
+ <p>Corresponds to "Ad server impressions (%)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The ratio of the number of clicks delivered to the total clicks delivered
+ when no {@link LineItem} reservation could be found by the ad server for
+ inventory-level dynamic allocation.
+ For premium networks, this includes line item-level dynamic allocation as well.
+ Represented as a percentage.
+ <p>Corresponds to "Ad server clicks (%)" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The ratio of the number of clicks delivered to the total clicks delivered
+ by the ad server for line item-level dynamic allocation.
+ Represented as a percentage.
+ <p>Corresponds to "Ad server clicks (%)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The ratio of revenue generated by ad server to the total CPM and CPC revenue earned
+ by ads delivered when no {@link LineItem} reservation could be found by
+ the ad server for inventory-level dynamic allocation.
+ For premium networks, this includes line item-level dynamic allocation as well.
+ Represented as a percentage.
+ <p>Corresponds to "Ad server revenue (%)" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The ratio of revenue generated by ad server to the total CPM, CPC and CPD revenue earned
+ by ads delivered when no {@link LineItem} reservation could be found by
+ the ad server for inventory-level dynamic allocation.
+ For premium networks, this includes line item-level dynamic allocation as well.
+ Represented as a percentage.
+
+
+
+
+
+
+ The ratio of revenue generated by ad server to the total CPM and CPC revenue earned by
+ the ads delivered for line item-level dynamic allocation.
+ Represented as a percentage.
+ <p>Corresponds to "Ad server revenue (%)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The ratio of revenue generated by ad server to the total CPM, CPC and CPD revenue earned by
+ the ads delivered for line item-level dynamic allocation.
+ Represented as a percentage.
+
+
+
+
+
+
+ The number of times that the code for an ad is served by the ad server.
+ <p>Corresponds to "Ad server code served count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ The number of downloaded impressions delivered by the ad server including impressions
+ recognized as spam.
+ <p>Corresponds to "Ad server unfiltered downloaded impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The number of clicks delivered by the ad server including clicks recognized as spam.
+ <p>Corresponds to "Ad server unfiltered clicks" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The number of impressions a dynamic allocation ad delivered when no {@link LineItem}
+ reservation could be found by the ad server for inventory-level dynamic allocation.
+ For premium networks, this includes line item-level dynamic allocation as well.
+ <p>Can correspond to any of the following in the DFP UI: AdSense / Ad Exchange impressions, AdSense impressions. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The number of impressions an AdSense ad delivered for line item-level dynamic allocation.
+ <p>Corresponds to "AdSense impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The number of impressions an AdSense ad delivered for line item-level dynamic allocation by
+ explicit custom criteria targeting.
+ <p>Corresponds to "AdSense targeted impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The number of clicks a dynamic allocation ad delivered when no {@link LineItem}
+ reservation could be found by the ad server for inventory-level dynamic allocation.
+ For premium networks, this includes line item-level dynamic allocation as well.
+ <p>Can correspond to any of the following in the DFP UI: AdSense / Ad Exchange clicks, AdSense clicks. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The number of clicks an AdSense ad delivered for line item-level dynamic allocation.
+ <p>Corresponds to "AdSense clicks" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The number of clicks an AdSense ad delivered for line item-level dynamic allocation by
+ explicit custom criteria targeting.
+ <p>Corresponds to "AdSense targeted clicks" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The ratio of clicks a dynamic allocation ad delivered to the number of impressions it
+ delivered when no {@link LineItem} reservation could be found by the ad server for
+ inventory-level dynamic allocation.
+ For premium networks, this includes line item-level dynamic allocation as well.
+ <p>Can correspond to any of the following in the DFP UI: AdSense / Ad Exchange CTR, AdSense CTR. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The ratio of clicks an AdSense reservation ad delivered to the number of
+ impressions it delivered, including line item-level dynamic allocation.
+ <p>Corresponds to "AdSense CTR" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ Revenue generated from ads delivered for dynamic allocation when no {@link LineItem}
+ reservation could be found by the ad server for inventory-level dynamic allocation.
+ For premium networks, this includes line item-level dynamic allocation as well.
+ <p>Can correspond to any of the following in the DFP UI: AdSense / Ad Exchange revenue, AdSense revenue. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ Revenue generated from AdSense ads delivered for line item-level dynamic allocation.
+ <p>Corresponds to "AdSense revenue" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The average estimated cost-per-thousand-impressions earned from dynamic allocation
+ ads delivered when no {@link LineItem} reservation could be found by
+ the ad server for inventory-level dynamic allocation.
+ For premium networks, this includes line item-level dynamic allocation as well.
+ <p>Can correspond to any of the following in the DFP UI: AdSense / Ad Exchange average eCPM, AdSense average eCPM. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The average estimated cost-per-thousand-impressions earned from the ads
+ delivered by AdSense for line item-level dynamic allocation.
+ <p>Corresponds to "AdSense average eCPM" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The ratio of the number of impressions delivered by dynamic allocation ads
+ to the total impressions delivered when no {@link LineItem} reservation could
+ be found by the ad server for inventory-level dynamic allocation.
+ For premium networks, this includes line item-level dynamic allocation as well.
+ Represented as a percentage.
+ <p>Can correspond to any of the following in the DFP UI: AdSense / Ad Exchange impressions (%), AdSense impressions (%). Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The ratio of the number of impressions delivered by AdSense reservation
+ ads to the total impressions delivered for line item-level dynamic allocation.
+ Represented as a percentage.
+ <p>Corresponds to "AdSense impressions (%)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The ratio of the number of clicks delivered by dynamic allocation ads
+ to the total clicks delivered when no {@link LineItem} reservation could be
+ found by the ad server for inventory-level dynamic allocation.
+ For premium networks, this includes line item-level dynamic allocation as well.
+ Represented as a percentage.
+ <p>Can correspond to any of the following in the DFP UI: AdSense / Ad Exchange clicks (%), AdSense clicks (%). Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The ratio of the number of clicks delivered by AdSense reservation ads to
+ the total clicks delivered for line item-level dynamic allocation.
+ Represented as a percentage.
+ <p>Corresponds to "AdSense clicks (%)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The ratio of revenue to the total revenue earned from the dynamic allocation
+ CPM and CPC ads delivered when no {@link LineItem} reservation could be found
+ by the ad server for inventory-level dynamic allocation.
+ For premium networks, this includes line item-level dynamic allocation as well.
+ Represented as a percentage.
+ <p>Can correspond to any of the following in the DFP UI: AdSense / Ad Exchange revenue (%), AdSense revenue (%). Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The ratio of revenue to the total revenue earned from the dynamic allocation
+ CPM, CPC and CPD ads delivered when no {@link LineItem} reservation could be found
+ by the ad server for inventory-level dynamic allocation.
+ For premium networks, this includes line item-level dynamic allocation as well.
+ Represented as a percentage.
+
+
+
+
+
+
+ The ratio of revenue to the total revenue earned from the CPM and CPC ads
+ delivered by AdSense for line item-level dynamic allocation.
+ Represented as a percentage.
+ <p>Corresponds to "AdSense revenue (%)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The ratio of revenue to the total revenue earned from the CPM, CPC and CPD ads
+ delivered by AdSense for line item-level dynamic allocation.
+ Represented as a percentage.
+
+
+
+
+
+
+ The number of impressions an Ad Exchange ad delivered for line item-level dynamic allocation.
+ <p>Corresponds to "Ad Exchange impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ Ad Impressions on mapped Ad Exchange properties. When multiple text ads fill a single display
+ slot it is only counted once, when the top text ad is recognized. In these cases, the Ad
+ Impression is attributed to the top text ad.
+ <p>Corresponds to "Ad impressions" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Number of requests where a buyer was matched with the Ad request, for mapped Ad Exchange
+ properties.
+ <p>Corresponds to "Matched requests" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Ad revenue per 1000 ad impressions, for mapped Ad Exchange properties.
+ <p>Corresponds to "Ad eCPM" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ The number of clicks delivered by mapped Ad Exchange properties.
+ <p>Corresponds to "Clicks" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ The estimated net revenue generated by mapped Ad Exchange properties.
+ <p>Corresponds to "Estimated revenue" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ The coverage reported by mapped Ad Exchange properties.
+ <p>Corresponds to "Coverage" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ The matched queries click-through rate delivered by mapped Ad Exchange properties.
+ <p>Corresponds to "CTR" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ The total lift generated by mapped Ad Exchange properties.
+ <p>Corresponds to "Lift" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ The cost-per-click generated by mapped Ad Exchange properties.
+ <p>Corresponds to "CPC" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ The number of ad requests issued by mapped Ad Exchange properties.
+ <p>Corresponds to "Ad requests" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ The average estimated cost-per-thousand-ad requests earned by mapped Ad Exchange properties.
+ <p>Corresponds to "Ad request eCPM" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ The click-through rate of ad requests issued by mapped Ad Exchange properties.
+ <p>Corresponds to "Ad request CTR" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ The click-through rate of impressions issued by mapped Ad Exchange properties.
+ <p>Corresponds to "Ad CTR" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ The video drop off rate for mapped Ad Exchange properties.
+ <p>Corresponds to "Video drop-off rate" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ The video abandonment rate for mapped Ad Exchange properties.
+ <p>Corresponds to "Video abandonment rate" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ The average estimated cost-per-thousand-impressions generated by mapped Ad Exchange properties.
+ <p>Corresponds to "Matched eCPM" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ The estimated percentage of impressions generated by mapped Ad Exchange properties that are
+ eligible for Active View measurement.
+ <p>Corresponds to "Active view measurable" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ The percentage of viewable impressions out of all measurable impressions generated by mapped
+ Ad Exchange properties.
+ <p>Corresponds to "Active view viewable" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ The average time (in seconds) that an individual ad impression generated by mapped Ad Exchange
+ properties was viewable.
+ <p>Corresponds to "Average viewable time (secs)" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Total number of impressions generated by mapped Ad Exchange properties that were eligible to
+ measure viewability.
+ <p>Corresponds to "Active view enabled impressions" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Total number of eligible impressions generated by mapped Ad Exchange properties that were
+ measurable by Active View.
+ <p>Corresponds to "Active view measured impressions" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Total number of Active View measurable impressions generated by mapped Ad Exchange properties
+ that were viewable.
+ <p>Corresponds to "Active view viewed impressions" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Number of responses that shows that a buyer is bidding, for mapped Ad Exchange properties.
+ <p>Corresponds to "Deals bid responses" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Deal ad requests for mapped Ad Exchange properties which were ?matched? with demand from the
+ buyer associated with the Deal. Each ?Deals matched request? represents one opportunity for the
+ Deal Buyer to serve their ad in the context of the Deal.
+ <p>Corresponds to "Deals matched requests" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Total ad requests associated with a given Deal, for mapped Ad Exchange properties.
+ <p>Corresponds to "Deals ad requests" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Deals matched requests divided by Deals ad requests, for mapped Ad Exchange properties.
+ <p>Corresponds to "Deals match rate" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ A count of how many users watch the first 25% of a video ad, for mapped Ad Exchange properties.
+
+
+
+
+
+
+ A count of how many users watch the first 75% of a video ad, for mapped Ad Exchange properties.
+
+
+
+
+
+
+ Percentage of times a user clicked Skip, for mapped Ad Exchange properties.
+ <p>Corresponds to "TrueView skip rate" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Number of times a video ad has been viewed to completion or watched to 30 seconds, whichever
+ happens first, for mapped Ad Exchange properties.
+ <p>Corresponds to "TrueView views" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ TrueView views divided by TrueView impressions, for mapped Ad Exchange properties.
+ <p>Corresponds to "TrueView VTR" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ The third-party fill rate by Ad Exchange properties linked to DFP.
+
+ <p><b>This experimental column only works with Ad Exchange web properties linked with an active
+ status.</b>
+
+ <p>This field is deprecated and will be removed in v201805.
+ <p>Corresponds to "Mediation fill rate" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ Impressions generated for mediation requests. This includes third-party network and
+ Ad Exchange impressions for mediation.
+
+ <p>This field is deprecated and will be removed in v201805.
+ <p>Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ Estimated revenue generated for mediation requests. This combines estimated revenue from
+ third-parties along with Ad Exchange.
+
+ <p>This field is deprecated and will be removed in v201805.
+ <p>Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The average estimated cost-per-thousand-impressions earned from mediation ads.
+
+ <p>This field is deprecated and will be removed in v201805.
+ <p>Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ Mediation third-party average cost-per-thousand-impressions.
+ <p>Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ Mediation fill rate indicating how often a network fills an ad request.
+
+ <p>This field is deprecated and will be removed in v201805.
+ <p>Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ Mediation passbacks recorded when a network does not fill an ad request.
+
+ <p>This field is deprecated and will be removed in v201805.
+ <p>Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The number of impressions an Ad Exchange ad delivered for line item-level dynamic allocation
+ by explicit custom criteria targeting.
+ <p>Corresponds to "Ad Exchange targeted impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The number of clicks an Ad Exchange ad delivered for line item-level dynamic allocation.
+ <p>Corresponds to "Ad Exchange clicks" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The number of clicks an Ad Exchange ad delivered for line item-level dynamic allocation by
+ explicit custom criteria targeting.
+ <p>Corresponds to "Ad Exchange targeted clicks" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The ratio of clicks an Ad Exchange ad delivered to the number of
+ impressions it delivered for line item-level dynamic allocation.
+ <p>Corresponds to "Ad Exchange CTR" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The ratio of the number of impressions delivered to the total impressions delivered
+ by Ad Exchange for line item-level dynamic allocation.
+ Represented as a percentage.
+ <p>Corresponds to "Ad Exchange impressions (%)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The ratio of the number of clicks delivered to the total clicks delivered
+ by Ad Exchange for line item-level dynamic allocation.
+ Represented as a percentage.
+ <p>Corresponds to "Ad Exchange clicks (%)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ Revenue generated from Ad Exchange ads delivered for line item-level dynamic allocation.
+ Represented in publisher currency and time zone.
+ <p>Corresponds to "Ad Exchange revenue" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The ratio of revenue generated by Ad Exchange to the total revenue earned
+ by CPM and CPC ads delivered for line item-level dynamic allocation.
+ Represented as a percentage.
+ <p>Corresponds to "Ad Exchange revenue (%)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The ratio of revenue generated by Ad Exchange to the total revenue earned
+ by CPM, CPC and CPD ads delivered for line item-level dynamic allocation.
+ Represented as a percentage.
+
+
+
+
+
+
+ The average estimated cost-per-thousand-impressions earned from the
+ delivery of Ad Exchange ads for line item-level dynamic allocation.
+ <p>Corresponds to "Ad Exchange average eCPM" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The total number of impressions delivered by the ad servers
+ including inventory-level dynamic allocation.
+ <p>Corresponds to "Total impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The total number of impressions delivered including line item-level dynamic allocation.
+ <p>Corresponds to "Total impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO.</p>
+
+
+
+
+
+
+ The total number of impressions delivered including line item-level dynamic allocation by
+ explicit custom criteria targeting.
+ <p>Corresponds to "Total targeted impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The total number of clicks delivered by the ad servers
+ including inventory-level dynamic allocation.
+ <p>Corresponds to "Total clicks" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The total number of clicks delivered including line item-level dynamic allocation.
+ <p>Corresponds to "Total clicks" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO.</p>
+
+
+
+
+
+
+ The total number of clicks delivered including line item-level dynamic allocation by
+ explicit custom criteria targeting
+ <p>Corresponds to "Total targeted clicks" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The ratio of total clicks on ads delivered by the ad servers to the total number
+ of impressions delivered for an ad including inventory-level dynamic allocation.
+ <p>Corresponds to "Total CTR" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The ratio of total clicks on ads delivered by the ad servers to the total number
+ of impressions delivered for an ad including line item-level dynamic allocation.
+ <p>Corresponds to "Total CTR" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO.</p>
+
+
+
+
+
+
+ The total CPM and CPC revenue generated by the ad servers
+ including inventory-level dynamic allocation.
+ <p>Corresponds to "Total CPM and CPC revenue" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The total CPM, CPC and CPD revenue generated by the ad servers
+ including inventory-level dynamic allocation.
+
+
+
+
+
+
+ The total CPM and CPC revenue generated by the ad servers
+ including line item-level dynamic allocation.
+ <p>Corresponds to "Total CPM and CPC revenue" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO.</p>
+
+
+
+
+
+
+ The total CPM, CPC and CPD revenue generated by the ad servers
+ including line item-level dynamic allocation.
+ <p>Can correspond to any of the following in the DFP UI: Total CPM, CPC, CPD, and vCPM revenue, Total CPM, CPC and CPD revenue. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO.</p>
+
+
+
+
+
+
+ Estimated cost-per-thousand-impressions (eCPM) of CPM and CPC ads delivered by the
+ ad servers including inventory-level dynamic allocation.
+ <p>Corresponds to "Total average eCPM" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ Estimated cost-per-thousand-impressions (eCPM) of CPM, CPC and CPD ads delivered by the
+ ad servers including inventory-level dynamic allocation.
+
+
+
+
+
+
+ Estimated cost-per-thousand-impressions (eCPM) of CPM and CPC ads delivered by the
+ ad servers including line item-level dynamic allocation.
+ <p>Corresponds to "Total average eCPM" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO.</p>
+
+
+
+
+
+
+ Estimated cost-per-thousand-impressions (eCPM) of CPM, CPC and CPD ads delivered by the
+ ad servers including line item-level dynamic allocation.
+
+
+
+
+
+
+ The total number of times that the code for an ad is served by the ad server including
+ inventory-level dynamic allocation.
+ <p>Corresponds to "Total code served count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO.</p>
+
+
+
+
+
+
+ The total number of missed impressions due to the ad servers' inability to
+ find ads to serve, including inventory-level dynamic allocation.
+ <p>Corresponds to "Unfilled impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ The number of control (unoptimized) impressions delivered for an ad for
+ which the optimization feature has been enabled.
+ <p>Corresponds to "Control impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ Number of clicks resulting from the delivery of control (unoptimized)
+ impressions for an ad for which the optimization feature has been enabled.
+ <p>Corresponds to "Control clicks" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The CTR for control (unoptimized) impressions for an order for which the
+ optimization feature has been enabled.
+ <p>Corresponds to "Control CTR" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ Number of optimized impressions delivered for an ad for which the
+ optimization feature has been enabled.
+ <p>Corresponds to "Optimized impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ Number of clicks resulting from the delivery of optimized impressions for
+ an ad for which the optimization feature has been enabled.
+ <p>Corresponds to "Optimized clicks" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ Number of non-optimized impressions delivered for an ad for which the
+ optimization feature has been enabled.
+ <p>Corresponds to "Non-optimized impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ Number of clicks resulting from the delivery of non-optimized impressions for
+ an ad for which the optimization feature has been enabled.
+ <p>Corresponds to "Non-optimized clicks" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ Number of extra clicks resulting from the delivery of optimized impressions
+ for an ad for which the optimization feature has been enabled.
+ <p>Corresponds to "Extra clicks" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The CTR for optimized impressions for an ad for which the optimization
+ feature has been enabled.
+ <p>Corresponds to "Optimized CTR" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The percentage by which optimized CTRs are greater than the unoptimized
+ CTRs. This is calculated as (({@link Column#OPTIMIZATION_OPTIMIZED_CTR}/
+ {@link Column#OPTIMIZATION_CONTROL_CTR}) - 1) * 100 for an ad for which the
+ optimization feature has been enabled.
+ <p>Corresponds to "Lift" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The line item coverage measures how often the traffic was sent for
+ optimization.
+ <p>Corresponds to "Percent optimized" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The number of impressions that were behind schedule at the time of their delivery.
+ <p>Corresponds to "Impressions that are behind schedule" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The number of impressions that did not have any clicks recorded in the recent past.
+ <p>Corresponds to "Impressions with no clicks recorded" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The number of impressions that were delivered as sponsorship items.
+ <p>Corresponds to "Sponsorship impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The number of impressions that were set to deliver as fast as possible.
+ <p>Corresponds to "Impressions serving as fast as possible" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The number of impressions that have no absolute lifetime delivery goals.
+ <p>Corresponds to "Impressions with no lifetime goal" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ Total revenue resulting from the delivery of control (unoptimized)
+ impressions for an ad for which the optimization feature has been enabled.
+ <p>Corresponds to "Control revenue" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ Total revenue resulting from the delivery of optimized impressions for
+ an ad for which the optimization feature has been enabled.
+ <p>Corresponds to "Optimized revenue" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ Estimated cost-per-thousand-impressions (eCPM) of control (unoptimized)
+ impressions for an ad for which the optimization feature has been enabled.
+ <p>Corresponds to "Control eCPM" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ Estimated cost-per-thousand-impressions (eCPM) of optimized
+ impressions for an ad for which the optimization feature has been enabled.
+ <p>Corresponds to "Optimized eCPM" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ Freed-up impressions as a result of optimization.
+ <p>Corresponds to "Freed-up impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ Relative change in eCPM as a result of optimization.
+ <p>Corresponds to "eCPM lift" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The average number of ads displayed to each unique visitor.
+ <p>Corresponds to "Average impressions / visitor" in the DFP UI. Compatible with the REACH report type.</p>
+
+
+
+
+
+
+ The average revenue earned per unique visitor.
+ <p>Corresponds to "Average revenue / visitor" in the DFP UI. Compatible with the REACH report type.</p>
+
+
+
+
+
+
+ The number of unique visitors.
+ <p>Corresponds to "Unique visitors" in the DFP UI. Compatible with the REACH report type.</p>
+
+
+
+
+
+
+ The number of people in the given demographic bucket.
+ <p>Corresponds to "Population" in the DFP UI. Compatible with the REACH report type.</p>
+
+
+
+
+
+
+ The number of unique users reached in the given demographic bucket.
+ <p>Corresponds to "Unique viewers" in the DFP UI. Compatible with the REACH report type.</p>
+
+
+
+
+
+
+ Percentage of the number of unique users reached in the given demographic bucket (out of the
+ number of unique users reached in all demographics).
+ <p>Corresponds to "% Composition unique viewers" in the DFP UI. Compatible with the REACH report type.</p>
+
+
+
+
+
+
+ The number of impressions in the given demographic bucket.
+ <p>Corresponds to "Impressions" in the DFP UI. Compatible with the REACH report type.</p>
+
+
+
+
+
+
+ Percentage of the number of impressions in the given demographic bucket (out of the number of
+ impressions in all demographics).
+ <p>Corresponds to "% Composition impressions" in the DFP UI. Compatible with the REACH report type.</p>
+
+
+
+
+
+
+ The audience reach calculated as {@link #GRP_UNIQUE_AUDIENCE} / {@link #GRP_POPULATION}.
+ <p>Corresponds to "% Population reach" in the DFP UI. Compatible with the REACH report type.</p>
+
+
+
+
+
+
+ The audience average frequency calculated as {@link #GRP_AUDIENCE_IMPRESSIONS} / {@link
+ #GRP_UNIQUE_AUDIENCE}.
+ <p>Corresponds to "Average frequency" in the DFP UI. Compatible with the REACH report type.</p>
+
+
+
+
+
+
+ The gross rating points (GRP) calculated as {@link #GRP_AUDIENCE_REACH} * {@link
+ #GRP_AUDIENCE_AVERAGE_FREQUENCY} * 100.
+ <p>Corresponds to "Target rating points" in the DFP UI. Compatible with the REACH report type.</p>
+
+
+
+
+
+
+ The number of impressions for a particular SDK mediation creative.
+ <p>Corresponds to "SDK mediation creative impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The number of clicks for a particular SDK mediation creative.
+ <p>Corresponds to "SDK mediation creative clicks" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The number of forecasted impressions for future sell-through reports.
+
+ <p>This metric is available for the next 90 days with a daily break down and for the next 12
+ months with a monthly break down.
+ <p>Corresponds to "Forecasted impressions" in the DFP UI. Compatible with the SELL_THROUGH report type.</p>
+
+
+
+
+
+
+ The number of available impressions for future sell-through reports.
+
+ <p>This metric is available for the next 90 days with a daily break down
+ and for the next 12 months with a monthly break down.
+ <p>Corresponds to "Available impressions" in the DFP UI. Compatible with the SELL_THROUGH report type.</p>
+
+
+
+
+
+
+ The number of reserved impressions for future sell-through reports.
+
+ <p>This metric is available for the next 90 days with a daily break down
+ and for the next 12 months with a monthly break down.
+ <p>Corresponds to "Reserved impressions" in the DFP UI. Compatible with the SELL_THROUGH report type.</p>
+
+
+
+
+
+
+ The sell-through rate for impressions for future sell-through reports.
+
+ <p>This metric is available for the next 90 days with a daily break down
+ and for the next 12 months with a monthly break down.
+ <p>Corresponds to "Sell-through rate" in the DFP UI. Compatible with the SELL_THROUGH report type.</p>
+
+
+
+
+
+
+ The total number of times a backup image is served in place of a rich media ad.
+ <p>Corresponds to "Backup image impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The amount of time(seconds) that each rich media ad is displayed to users.
+ <p>Corresponds to "Total display time" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The average amount of time(seconds) that each rich media ad is displayed to users.
+ <p>Corresponds to "Average display time" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The number of times an expanding ad was expanded.
+ <p>Corresponds to "Total expansions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The average amount of time(seconds) that an expanding ad is viewed in an expanded state.
+ <p>Corresponds to "Average expanding time" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The average amount of time(seconds) that a user interacts with a rich media ad.
+ <p>Corresponds to "Interaction time" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The number of times that a user interacts with a rich media ad.
+ <p>Corresponds to "Total interactions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The ratio of rich media ad interactions to the number of times the ad was displayed.
+ Represented as a percentage.
+ <p>Corresponds to "Interaction rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The average amount of time(seconds) that a user interacts with a rich media ad.
+ <p>Corresponds to "Average interaction time" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The number of impressions where a user interacted with a rich media ad.
+ <p>Corresponds to "Interactive impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The number of times that a user manually closes a floating, expanding,
+ in-page with overlay, or in-page with floating ad.
+ <p>Corresponds to "Manual closes" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ A metric that measures an impression only once when a user opens an ad in full screen mode.
+ <p>Corresponds to "Full-screen impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The number of times a user clicked on the graphical controls of a video player.
+ <p>Corresponds to "Total video interactions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The ratio of video interactions to video plays.
+ Represented as a percentage.
+ <p>Corresponds to "Video interaction rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The number of times a rich media video was muted.
+ <p>Corresponds to "Mute" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The number of times a rich media video was paused.
+ <p>Corresponds to "Pause" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The number of times a rich media video was played.
+ <p>Corresponds to "Plays" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The number of times a rich media video was played upto midpoint.
+ <p>Corresponds to "Midpoint" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The number of times a rich media video was fully played.
+ <p>Corresponds to "Complete" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The number of times a rich media video was restarted.
+ <p>Corresponds to "Replays" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The number of times a rich media video was stopped.
+ <p>Corresponds to "Stops" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The number of times a rich media video was unmuted.
+ <p>Corresponds to "Unmute" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The average amount of time(seconds) that a rich media video was viewed per view.
+ <p>Corresponds to "Average view time" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The percentage of a video watched by a user.
+ <p>Corresponds to "View rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The amount of time (seconds) that a user interacts with a rich media ad.
+ <p>Corresponds to "Custom event - time" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ The number of times a user views and interacts with a specified part of a rich media ad.
+ <p>Corresponds to "Custom event - count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ The number of impressions where the video was played.
+ <p>Corresponds to "Start" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ The number of times the video played to 25% of its length.
+ <p>Corresponds to "First quartile" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ The number of times the video reached its midpoint during play.
+ <p>Corresponds to "Midpoint" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ The number of times the video played to 75% of its length.
+ <p>Corresponds to "Third quartile" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ The number of times the video played to completion.
+ <p>Corresponds to "Complete" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Average percentage of the video watched by users.
+ <p>Corresponds to "Average view rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Average time(seconds) users watched the video.
+ <p>Corresponds to "Average view time" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Percentage of times the video played to the end.
+ <p>Corresponds to "Completion rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ The number of times an error occurred, such as a VAST redirect error, a video playback error,
+ or an invalid response error.
+ <p>Corresponds to "Total error count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Duration of the video creative.
+ <p>Corresponds to "Video length" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ The number of times a skip button is shown in video.
+ <p>Corresponds to "Skip button shown" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ The number of engaged views i.e. ad is viewed to completion
+ or for 30s, whichever comes first.
+ <p>Corresponds to "Engaged view" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ View-through rate represented as a percentage.
+ <p>Corresponds to "View-through rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Number of times that the publisher specified a video ad played automatically.
+ <p>Corresponds to "Auto-plays" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Number of times that the publisher specified a video ad was clicked to play.
+ <p>Corresponds to "Click-to-plays" in the DFP UI. Compatible with any of the following report types: HISTORICAL, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Error rate is the percentage of video error count from (error count + total impressions).
+ <p>Corresponds to "Total error rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Number of VAST video errors of type 100.
+ <p>Corresponds to "VAST error 100 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Number of VAST video errors of type 101.
+ <p>Corresponds to "VAST error 101 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Number of VAST video errors of type 102.
+ <p>Corresponds to "VAST error 102 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Number of VAST video errors of type 200.
+ <p>Corresponds to "VAST error 200 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Number of VAST video errors of type 201.
+ <p>Corresponds to "VAST error 201 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Number of VAST video errors of type 202.
+ <p>Corresponds to "VAST error 202 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Number of VAST video errors of type 203.
+ <p>Corresponds to "VAST error 203 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Number of VAST video errors of type 300.
+ <p>Corresponds to "VAST error 300 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Number of VAST video errors of type 301.
+ <p>Corresponds to "VAST error 301 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Number of VAST video errors of type 302.
+ <p>Corresponds to "VAST error 302 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Number of VAST video errors of type 303.
+ <p>Corresponds to "VAST error 303 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Number of VAST video errors of type 400.
+ <p>Corresponds to "VAST error 400 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Number of VAST video errors of type 401.
+ <p>Corresponds to "VAST error 401 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Number of VAST video errors of type 402.
+ <p>Corresponds to "VAST error 402 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Number of VAST video errors of type 403.
+ <p>Corresponds to "VAST error 403 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Number of VAST video errors of type 405.
+ <p>Corresponds to "VAST error 405 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Number of VAST video errors of type 500.
+ <p>Corresponds to "VAST error 500 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Number of VAST video errors of type 501.
+ <p>Corresponds to "VAST error 501 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Number of VAST video errors of type 502.
+ <p>Corresponds to "VAST error 502 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Number of VAST video errors of type 503.
+ <p>Corresponds to "VAST error 503 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Number of VAST video errors of type 600.
+ <p>Corresponds to "VAST error 600 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Number of VAST video errors of type 601.
+ <p>Corresponds to "VAST error 601 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Number of VAST video errors of type 602.
+ <p>Corresponds to "VAST error 602 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Number of VAST video errors of type 603.
+ <p>Corresponds to "VAST error 603 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Number of VAST video errors of type 604.
+ <p>Corresponds to "VAST error 604 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Number of VAST video errors of type 900.
+ <p>Corresponds to "VAST error 900 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Number of VAST video errors of type 901.
+ <p>Corresponds to "VAST error 901 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Video interaction event: The number of times user paused ad clip.
+ <p>Corresponds to "Pause" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Video interaction event: The number of times the user unpaused the video.
+ <p>Corresponds to "Resume" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Video interaction event: The number of times a user rewinds the video.
+ <p>Corresponds to "Rewind" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Video interaction event: The number of times video player was in mute state during play
+ of ad clip.
+ <p>Corresponds to "Mute" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Video interaction event: The number of times a user unmutes the video.
+ <p>Corresponds to "Unmute" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Video interaction event: The number of times a user collapses a video,
+ either to its original size or to a different size.
+ <p>Corresponds to "Collapse" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Video interaction event: The number of times a user expands a video.
+ <p>Corresponds to "Expand" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Video interaction event: The number of times ad clip played in full screen mode.
+ <p>Corresponds to "Full screen" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Video interaction event: The number of user interactions with a video, on average,
+ such as pause, full screen, mute, etc.
+ <p>Corresponds to "Average interaction rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Video interaction event: The number of times a skippable video is skipped.
+ <p>Corresponds to "Video skipped" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ The number of control starts.
+ <p>Corresponds to "Control starts" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The number of optimized starts.
+ <p>Corresponds to "Optimized starts" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The number of control completes.
+ <p>Corresponds to "Control completes" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The number of optimized completes.
+ <p>Corresponds to "Optimized completes" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The rate of control completions.
+ <p>Corresponds to "Control completion rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The rate of optimized completions.
+ <p>Corresponds to "Optimized completion rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The percentage by which optimized completion rate is greater than the unoptimized completion
+ rate. This is calculated as (( {@link Column#VIDEO_OPTIMIZATION_OPTIMIZED_COMPLETION_RATE}/
+ {@link Column#VIDEO_OPTIMIZATION_CONTROL_COMPLETION_RATE}) - 1) * 100 for an ad for which the
+ optimization feature has been enabled.
+ <p>Corresponds to "Completion rate lift" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The number of control skip buttons shown.
+ <p>Corresponds to "Control skip button shown" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The number of optimized skip buttons shown.
+ <p>Corresponds to "Optimized skip button shown" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The number of control engaged views.
+ <p>Corresponds to "Control engaged view" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The number of optimized engaged views.
+ <p>Corresponds to "Optimized engaged view" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The control view-through rate.
+ <p>Corresponds to "Control view-through rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The optimized view-through rate.
+ <p>Corresponds to "Optimized view-through rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The percentage by which optimized view-through rate is greater than the unoptimized
+ view-through rate. This is calculated as (( {@link
+ Column#VIDEO_OPTIMIZATION_OPTIMIZED_VIEW_THROUGH_RATE}/ {@link
+ Column#VIDEO_OPTIMIZATION_CONTROL_VIEW_THROUGH_RATE}) - 1) * 100 for an ad for which the
+ optimization feature has been enabled.
+ <p>Corresponds to "View-through rate lift" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The total number of impressions viewed on the user's screen.
+ <p>Corresponds to "Total Active View viewable impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, DFP_HISTORICAL_DATA_STUDIO.</p>
+
+
+
+
+
+
+ The total number of impressions that were sampled and measured by active view.
+ <p>Corresponds to "Total Active View measurable impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, DFP_HISTORICAL_DATA_STUDIO.</p>
+
+
+
+
+
+
+ The percentage of total impressions viewed on the user's screen (out of the total impressions
+ measurable by active view).
+
+
+
+
+
+
+ Total number of impressions that were eligible to measure viewability.
+ <p>Corresponds to "Total Active View eligible impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, DFP_HISTORICAL_DATA_STUDIO.</p>
+
+
+
+
+
+
+ The percentage of total impressions that were measurable by active view (out of all the total
+ impressions sampled for active view).
+ <p>Corresponds to "Total Active View % measurable impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, DFP_HISTORICAL_DATA_STUDIO.</p>
+
+
+
+
+
+
+ Active View total average time in seconds that specific impressions are reported as being
+ viewable.
+ <p>Corresponds to "Total Active View Average Viewable Time (seconds)" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The number of impressions delivered by the ad server viewed on the user's screen.
+ <p>Corresponds to "Ad server Active View viewable impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The number of impressions delivered by the ad server that were sampled, and measurable by
+ active view.
+ <p>Corresponds to "Ad server Active View measurable impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The percentage of impressions delivered by the ad server viewed on the user's screen (out of
+ the ad server impressions measurable by active view).
+ <p>Corresponds to "Ad server Active View % viewable impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ Total number of impressions delivered by the ad server that were eligible to measure
+ viewability.
+ <p>Corresponds to "Ad server Active View eligible impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The percentage of impressions delivered by the ad server that were measurable by active view (
+ out of all the ad server impressions sampled for active view).
+ <p>Corresponds to "Ad server Active View % measurable impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ Active View ad server revenue.
+ <p>Corresponds to "Ad Server Active View Revenue" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ Active View ad server average time in seconds that specific impressions are reported as being
+ viewable.
+ <p>Corresponds to "Ad Server Active View Average Viewable Time (seconds)" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The number of impressions delivered by AdSense viewed on the user's screen,
+ <p>Corresponds to "AdSense Active View viewable impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The number of impressions delivered by AdSense that were sampled, and measurable by active
+ view.
+ <p>Corresponds to "AdSense Active View measurable impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The percentage of impressions delivered by AdSense viewed on the user's screen (out of AdSense
+ impressions measurable by active view).
+ <p>Corresponds to "AdSense Active View % viewable impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ Total number of impressions delivered by AdSense that were eligible to measure viewability.
+ <p>Corresponds to "AdSense Active View eligible impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The percentage of impressions delivered by AdSense that were measurable by active view ( out of
+ all AdSense impressions sampled for active view).
+ <p>Corresponds to "AdSense Active View % measurable impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ Active View AdSense revenue.
+ <p>Corresponds to "AdSense Active View Revenue" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ Active View AdSense average time in seconds that specific impressions are reported as being
+ viewable.
+ <p>Corresponds to "AdSense Active View Average Viewable Time (seconds)" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The number of impressions delivered by Ad Exchange viewed on the user's screen,
+ <p>Corresponds to "Ad Exchange Active View viewable impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The number of impressions delivered by Ad Exchange that were sampled, and measurable by active
+ view.
+ <p>Corresponds to "Ad Exchange Active View measurable impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The percentage of impressions delivered by Ad Exchange viewed on the user's screen (out of Ad
+ Exchange impressions measurable by active view).
+ <p>Corresponds to "Ad Exchange Active View % viewable impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ Total number of impressions delivered by Ad Exchange that were eligible to measure viewability.
+ <p>Corresponds to "Ad Exchange Active View eligible impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The percentage of impressions delivered by Ad Exchange that were measurable by active view (
+ out of all Ad Exchange impressions sampled for active view).
+ <p>Corresponds to "Ad Exchange Active View % measurable impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ Active View AdExchange revenue.
+ <p>Corresponds to "Ad Exchange Active View Revenue" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ Active View AdExchange average time in seconds that specific impressions are reported as being
+ viewable.
+ <p>Corresponds to "Ad Exchange Active View Average Viewable Time (seconds)" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ Active View total revenue.
+ <p>Corresponds to "Total Active View Revenue" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ Cost for audience extension
+ ie. cost the publisher had to pay in order to buy the inventory.
+
+ <p>This field is deprecated and will be removed in v201805.
+ <p>Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ Number of view-through conversions.
+
+
+
+
+
+
+ Number of view-through conversions per thousand impressions.
+ <p>Corresponds to "Conversions per thousand impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ Number of click-through conversions.
+ <p>Corresponds to "Click-through conversions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO.</p>
+
+
+
+
+
+
+ Number of click-through conversions per click.
+ <p>Corresponds to "Conversions per click" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ Revenue for view-through conversions.
+ <p>Corresponds to "Advertiser view-through sales" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO.</p>
+
+
+
+
+
+
+ Revenue for click-through conversions.
+ <p>Corresponds to "Advertiser click-through sales" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO.</p>
+
+
+
+
+
+
+ Total number of conversions.
+ <p>Corresponds to "Total conversions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO.</p>
+
+
+
+
+
+
+ Total revenue for conversions.
+ <p>Corresponds to "Total advertiser sales" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO.</p>
+
+
+
+
+
+
+ The number of impressions sent to Ad Exchange / AdSense, regardless of whether they
+ won or lost (total number of dynamic allocation impressions).
+ <p>Corresponds to "Impressions competing" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The number of unfilled queries that attempted dynamic allocation by Ad Exchange / AdSense.
+ <p>Corresponds to "Unfilled competing impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The number of Ad Exchange / AdSense and DFP impressions.
+ <p>Corresponds to "Eligible impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The difference between eligible impressions and competing impressions in dynamic allocation.
+
+
+
+
+
+
+ The percentage of eligible impressions that are not competing in dynamic allocation.
+ <p>Corresponds to "Impressions not competing (%)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The percent of eligible impressions participating in dynamic allocation.
+
+
+
+
+
+
+ The percent of total dynamic allocation queries that won.
+ <p>Corresponds to "Dynamic allocation match rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The contracted net revenue of the {@link ProposalLineItem}.
+ <p>Corresponds to "Contracted revenue (net)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The contracted net revenue in the local currency of the {@link ProposalLineItem}.
+
+ See {@link #CONTRACTED_REVENUE_CONTRACTED_NET_REVENUE}
+ <p>Can correspond to any of the following in the DFP UI: Contracted revenue (local), Contracted revenue (net) (local). Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The contracted gross revenue of the {@link ProposalLineItem}, including agency commission.
+ <p>Corresponds to "Contracted revenue (gross)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The contracted gross revenue in the local currency of the {@link ProposalLineItem}, including
+ agency commission.
+
+ See {@link #CONTRACTED_REVENUE_CONTRACTED_GROSS_REVENUE}
+ <p>Corresponds to "Contracted revenue (gross) (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The value added tax on contracted net revenue of the {@link ProposalLineItem} or
+ {@link Proposal}.
+ <p>Corresponds to "Contracted VAT" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The value added tax on contracted net revenue in the local currency of the
+ {@link ProposalLineItem} or {@link Proposal}.
+
+ See {@link #CONTRACTED_REVENUE_CONTRACTED_VAT}
+ <p>Corresponds to "Contracted VAT (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The contracted agency commission of the {@link ProposalLineItem} or {@link Proposal}.
+ <p>Corresponds to "Contracted agency commission" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The contracted agency commission in the local currency of the {@link ProposalLineItem} or
+ {@link Proposal}.
+
+ See {@link #CONTRACTED_REVENUE_CONTRACTED_AGENCY_COMMISSION}
+ <p>Corresponds to "Contracted agency commission (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The contracted impressions of the {@link ProposalLineItem}.
+ <p>Corresponds to "Contracted impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The contracted clicks of the {@link ProposalLineItem}.
+ <p>Corresponds to "Contracted clicks" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The contracted volume of the {@link ProposalLineItem}. Volume represents impressions for
+ rate type CPM, clicks for CPC, and days for CPD.
+ <p>Corresponds to "Contracted volume" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The budget of the {@link Proposal}.
+ <p>Corresponds to "Budget" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The remaining budget of the {@link Proposal}. It is calculated by subtracting the contracted
+ net revenue from the budget.
+ <p>Corresponds to "Remaining budget" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The buffered impressions of the {@link ProposalLineItem}.
+ <p>Corresponds to "Buffered impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The buffered clicks of the {@link ProposalLineItem}.
+ <p>Corresponds to "Buffered clicks" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The scheduled impressions of a {@link ProposalLineItem}. It is the sum of
+ {@link #SALES_CONTRACT_CONTRACTED_IMPRESSIONS} and
+ {@link #SALES_CONTRACT_BUFFERED_IMPRESSIONS}.
+ <p>Corresponds to "Scheduled impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The scheduled clicks of a {@link ProposalLineItem}. It is the sum of
+ {@link #SALES_CONTRACT_CONTRACTED_CLICKS} and {@link #SALES_CONTRACT_BUFFERED_CLICKS}.
+ <p>Corresponds to "Scheduled clicks" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The scheduled volume of a {@link ProposalLineItem}. It is the sum of
+ {@link #SALES_CONTRACT_CONTRACTED_VOLUME} and buffered volume.
+ <p>Corresponds to "Scheduled volume" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The scheduled net revenue of a {@link ProposalLineItem}.
+ <p>Corresponds to "Scheduled revenue (net)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The scheduled net revenue in the local currency of a {@link ProposalLineItem}.
+ <p>Corresponds to "Scheduled revenue (net) (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The scheduled gross revenue of a {@link ProposalLineItem}.
+ <p>Corresponds to "Scheduled revenue (gross)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The scheduled gross revenue in the local currency of a {@link ProposalLineItem}.
+ <p>Corresponds to "Scheduled revenue (gross) (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The total budget of the {@link Proposal}. It differs from {@link #SALES_CONTRACT_BUDGET} since
+ it always contains the total budget, not the prorated budget.
+ <p>Corresponds to "Total budget" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The total remaining budget of the {@link Proposal}. It differs from {@link
+ #SALES_CONTRACT_REMAINING_BUDGET} since it always contains the total remaining budget, not the
+ prorated remaining budget.
+ <p>Corresponds to "Total remaining budget" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The total contracted volume of the {@link ProposalLineItem}. It differs from {@link
+ #SALES_CONTRACT_CONTRACTED_VOLUME} that the volume is not prorated with regard to the date
+ range.
+ <p>Corresponds to "Total contracted volume" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The total contracted net revenue of the {@link ProposalLineItem}. It differs from {@link
+ #CONTRACTED_REVENUE_CONTRACTED_NET_REVENUE} that the revenue is not prorated with regard to the
+ date range.
+ <p>Corresponds to "Total contracted revenue (net)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The total contracted net revenue in the local currency of the {@link ProposalLineItem}. It
+ differs from {@link #CONTRACTED_REVENUE_LOCAL_CONTRACTED_NET_REVENUE} that the revenue is not
+ prorated with regard to the date range.
+
+ <p>See {@link #SALES_TOTAL_TOTAL_CONTRACTED_NET_REVENUE}
+ <p>Corresponds to "Total contracted revenue (net) (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The total contracted gross revenue of the {@link ProposalLineItem}. It differs from {@link
+ #CONTRACTED_REVENUE_CONTRACTED_GROSS_REVENUE} that the revenue is not prorated with regard to
+ the date range.
+ <p>Corresponds to "Total contracted revenue (gross)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The total contracted gross revenue in the local currency of the {@link ProposalLineItem}. It
+ differs from {@link #CONTRACTED_REVENUE_LOCAL_CONTRACTED_GROSS_REVENUE} that the revenue is not
+ prorated with regard to the date range.
+
+ <p>See {@link #SALES_TOTAL_TOTAL_CONTRACTED_GROSS_REVENUE}
+ <p>Corresponds to "Total contracted revenue (gross) (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The total contracted agency commission of the {@link ProposalLineItem}. It differs from {@link
+ #CONTRACTED_REVENUE_CONTRACTED_AGENCY_COMMISSION} that the revenue is not prorated with regard
+ to the date range.
+ <p>Corresponds to "Total contracted agency commission" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The total contracted agency commission in the local currency of the {@link ProposalLineItem}.
+ It differs from {@link #CONTRACTED_REVENUE_LOCAL_CONTRACTED_AGENCY_COMMISSION} that the revenue
+ is not prorated with regard to the date range.
+
+ <p>See {@link #SALES_TOTAL_TOTAL_CONTRACTED_AGENCY_COMMISSION}
+ <p>Corresponds to "Total contracted agency commission (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The total net revenue plus its value added tax of the {@link ProposalLineItem}. The revenue is
+ not prorated with regard to the date range.
+ <p>Corresponds to "Total contracted revenue with VAT (net)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The total net revenue plus its value added tax in the local currency of the {@link
+ ProposalLineItem}. The revenue is not prorated with regard to the date range.
+
+ <p>See {@link #SALES_TOTAL_TOTAL_CONTRACTED_WITH_VAT}
+ <p>Corresponds to "Total contracted revenue with VAT (net) (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The total scheduled volume of the {@link ProposalLineItem}. It differs from {@link
+ #SCHEDULED_SCHEDULED_VOLUME} that the volume is not prorated with regard to the date range.
+ <p>Corresponds to "Total scheduled volume" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The total scheduled net revenue of the {@link ProposalLineItem}. It differs from {@link
+ #SCHEDULED_SCHEDULED_NET_REVENUE} that the revenue is not prorated with regard to the date
+ range.
+ <p>Corresponds to "Total scheduled revenue (net)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The total scheduled net revenue in the local currency of the {@link ProposalLineItem}. It
+ differs from {@link #SCHEDULED_LOCAL_SCHEDULED_NET_REVENUE} that the revenue is not prorated
+ with regard to the date range.
+
+ <p>See {@link #SALES_TOTAL_TOTAL_SCHEDULED_NET_REVENUE}
+ <p>Corresponds to "Total scheduled revenue (net) (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The total scheduled gross revenue of the {@link ProposalLineItem}. It differs from {@link
+ #SCHEDULED_SCHEDULED_GROSS_REVENUE} that the revenue is not prorated with regard to the date
+ range.
+ <p>Corresponds to "Total scheduled revenue (gross)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The total scheduled gross revenue in the local currency of the {@link ProposalLineItem}. It
+ differs from {@link #SCHEDULED_LOCAL_SCHEDULED_GROSS_REVENUE} that the revenue is not prorated
+ with regard to the date range.
+
+ <p>See {@link #SALES_TOTAL_TOTAL_SCHEDULED_GROSS_REVENUE}
+ <p>Corresponds to "Total scheduled revenue (gross) (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The unreconciled net revenue of the {@link ProposalLineItem}. It is the portion of {@link
+ #UNIFIED_REVENUE_UNIFIED_NET_REVENUE} coming from unreconciled DFP volume.
+ <p>Corresponds to "Unreconciled revenue (net)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The unreconciled net revenue of the {@link ProposalLineItem} in local currency. It is the
+ portion of {@link #UNIFIED_REVENUE_LOCAL_UNIFIED_NET_REVENUE} coming from unreconciled DFP
+ volume.
+
+ <p>See {@link #UNIFIED_REVENUE_UNRECONCILED_NET_REVENUE}
+ <p>Corresponds to "Unreconciled revenue (net) (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The unreconciled gross revenue of the {@link ProposalLineItem}. It is the portion of {@link
+ #UNIFIED_REVENUE_UNIFIED_GROSS_REVENUE} coming from unreconciled DFP volume.
+ <p>Corresponds to "Unreconciled revenue (gross)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The unreconciled gross revenue of the {@link ProposalLineItem} in local currency. It is the
+ portion of {@link #UNIFIED_REVENUE_LOCAL_UNIFIED_GROSS_REVENUE} coming from unreconciled DFP
+ volume.
+
+ <p>See {@link #UNIFIED_REVENUE_UNRECONCILED_GROSS_REVENUE}
+ <p>Corresponds to "Unreconciled revenue (gross) (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The forecasted net revenue of the {@link ProposalLineItem}. It is the portion of {@link
+ #UNIFIED_REVENUE_UNIFIED_NET_REVENUE} coming from forecasted DFP volume.
+ <p>Corresponds to "Forecasted revenue (net)" in the DFP UI. Compatible with the SALES report type.</p>
+
+
+
+
+
+
+ The forecasted net revenue of the {@link ProposalLineItem} in local currency. It is the portion
+ of {@link #UNIFIED_REVENUE_LOCAL_UNIFIED_NET_REVENUE} coming from forecasted DFP volume.
+
+ <p>See {@link #UNIFIED_REVENUE_FORECASTED_NET_REVENUE}
+ <p>Corresponds to "Forecasted revenue (net) (local)" in the DFP UI. Compatible with the SALES report type.</p>
+
+
+
+
+
+
+ The forecasted gross revenue of the {@link ProposalLineItem}. It is the portion of {@link
+ #UNIFIED_REVENUE_UNIFIED_GROSS_REVENUE} coming from forecasted DFP volume.
+ <p>Corresponds to "Forecasted revenue (gross)" in the DFP UI. Compatible with the SALES report type.</p>
+
+
+
+
+
+
+ The forecasted gross revenue of the {@link ProposalLineItem} in local currency. It is the
+ portion of {@link #UNIFIED_REVENUE_LOCAL_UNIFIED_GROSS_REVENUE} coming from forecasted DFP
+ volume.
+
+ <p>See {@link #UNIFIED_REVENUE_FORECASTED_GROSS_REVENUE}
+ <p>Corresponds to "Forecasted revenue (gross) (local)" in the DFP UI. Compatible with the SALES report type.</p>
+
+
+
+
+
+
+ The unified net revenue of the {@link ProposalLineItem}. It is a combination of {@link
+ #UNIFIED_REVENUE_UNRECONCILED_NET_REVENUE}, {@link #BILLING_BILLABLE_NET_REVENUE}, and {@link
+ #UNIFIED_REVENUE_FORECASTED_NET_REVENUE} when query date range spans historical delivery and
+ forecasted delivery.
+ <p>Corresponds to "Unified revenue (net)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The unified net revenue of the {@link ProposalLineItem} in local currency. It is a
+ combination of {@link #UNIFIED_REVENUE_LOCAL_UNRECONCILED_NET_REVENUE},
+ {@link #BILLING_LOCAL_BILLABLE_NET_REVENUE},
+ and {@link #UNIFIED_REVENUE_LOCAL_FORECASTED_NET_REVENUE} when query date range spans
+ historical delivery and forecasted delivery.
+
+ See {@link #UNIFIED_REVENUE_UNIFIED_NET_REVENUE}
+ <p>Corresponds to "Unified revenue (net) (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The unified net revenue of the {@link ProposalLineItem}. It is a combination of
+ {@link #UNIFIED_REVENUE_UNRECONCILED_GROSS_REVENUE}, {@link #BILLING_BILLABLE_GROSS_REVENUE},
+ and {@link #UNIFIED_REVENUE_FORECASTED_GROSS_REVENUE} when query date range spans historical
+ delivery and forecasted delivery.
+ <p>Corresponds to "Unified revenue (gross)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The unified gross revenue of the {@link ProposalLineItem} in local currency. It is a
+ combination of {@link #UNIFIED_REVENUE_LOCAL_UNRECONCILED_GROSS_REVENUE},
+ {@link #BILLING_LOCAL_BILLABLE_GROSS_REVENUE}, and
+ {@link #UNIFIED_REVENUE_LOCAL_FORECASTED_GROSS_REVENUE} when query date range spans historical
+ delivery and forecasted delivery.
+
+ See {@link #UNIFIED_REVENUE_UNIFIED_GROSS_REVENUE}
+ <p>Corresponds to "Unified revenue (gross) (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The unified agency commission of the {@link ProposalLineItem}. It is a combination of the
+ unreconciled agency commission, the {@link #BILLING_BILLABLE_AGENCY_COMMISSION},
+ and the forecasted agency commission when query date range spans historical delivery and
+ forecasted delivery.
+ <p>Corresponds to "Unified agency commission" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The unified agency commission of the {@link ProposalLineItem} in local currency. It is a
+ combination of the unreconciled agency commission, the
+ {@link #BILLING_BILLABLE_AGENCY_COMMISSION}, and the forecasted agency commission when query
+ date range spans historical delivery and forecasted delivery.
+
+ See {@link #UNIFIED_REVENUE_UNIFIED_AGENCY_COMMISSION}
+ <p>Corresponds to "Unified agency commission (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The unreconciled volume of the {@link ProposalLineItem} for each cycle. Volume represents
+ impressions for rate type CPM, clicks for CPC and days for CPD. This fact can only be run
+ in proposal or proposal line item time zone.
+ <p>Corresponds to "Unreconciled volume" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The forecasted volume of the {@link ProposalLineItem} for each cycle. Volume represents
+ impressions for rate type CPM, clicks for CPC and days for CPD. This fact can only be run
+ in proposal or proposal line item time zone.
+ <p>Corresponds to "Forecasted volume" in the DFP UI. Compatible with the SALES report type.</p>
+
+
+
+
+
+
+ The unified volume of the {@link ProposalLineItem} for each cycle. Volume represents
+ impressions for rate type CPM, clicks for CPC and days for CPD. This fact can only be run
+ in proposal or proposal line item time zone.
+ <p>Corresponds to "Unified volume" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The expected revenue of the {@link ProposalLineItem}. It is equivalent to
+ {@link #UNIFIED_REVENUE_UNIFIED_NET_REVENUE} when the {@link ProposalLineItem} is sold and
+ {@link #SALES_PIPELINE_PIPELINE_NET_REVENUE} otherwise.
+ <p>Corresponds to "Expected revenue (net)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The expected revenue of the {@link ProposalLineItem} in local currency. It is equivalent to
+ {@link #UNIFIED_REVENUE_LOCAL_UNIFIED_NET_REVENUE} when the {@link ProposalLineItem} is sold
+ and {@link #SALES_PIPELINE_LOCAL_PIPELINE_NET_REVENUE} otherwise.
+
+ <p>See {@link #EXPECTED_REVENUE_EXPECTED_NET_REVENUE}
+ <p>Corresponds to "Expected revenue (net) (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The expected gross revenue of the {@link ProposalLineItem}. It is equivalent to {@link
+ #UNIFIED_REVENUE_UNIFIED_GROSS_REVENUE} when the {@link ProposalLineItem} is sold and {@link
+ #SALES_PIPELINE_PIPELINE_GROSS_REVENUE} otherwise.
+ <p>Corresponds to "Expected revenue (gross)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The expected gross revenue of the {@link ProposalLineItem} in local currency. It is equivalent
+ to {@link #UNIFIED_REVENUE_LOCAL_UNIFIED_GROSS_REVENUE} when the {@link ProposalLineItem} is
+ sold and {@link #SALES_PIPELINE_LOCAL_PIPELINE_GROSS_REVENUE} otherwise.
+
+ <p>See {@link #EXPECTED_REVENUE_EXPECTED_GROSS_REVENUE}
+ <p>Corresponds to "Expected revenue (gross) (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The pipeline net revenue of the {@link ProposalLineItem}. There is no revenue for sold {@link
+ ProposalLineItem proposal line items}. For unsold {@link ProposalLineItem proposal line items},
+ it is calculated by multiplying {@link Proposal#probabilityOfClose} by the contracted revenue
+ when inventory is not reserved; otherwise it is calcualted by multiplying {@link
+ Proposal#probabilityOfClose} by the forecasted revenue.
+ <p>Corresponds to "Pipeline revenue (net)" in the DFP UI. Compatible with the SALES report type.</p>
+
+
+
+
+
+
+ The pipeline net revenue in the local currency of the {@link ProposalLineItem}. There is no
+ revenue for sold {@link ProposalLineItem proposal line items}. For unsold
+ {@link ProposalLineItem proposal line items}, it is calculated by multiplying
+ {@link Proposal#probabilityOfClose} by the contracted revenue when inventory is not reserved;
+ otherwise it is calcualted by multiplying {@link Proposal#probabilityOfClose} by the forecasted
+ revenue.
+
+ See {@link #SALES_PIPELINE_PIPELINE_NET_REVENUE}
+ <p>Corresponds to "Pipeline revenue (net) (local)" in the DFP UI. Compatible with the SALES report type.</p>
+
+
+
+
+
+
+ The pipeline gross revenue of the {@link ProposalLineItem}. There is no revenue for sold
+ {@link ProposalLineItem proposal line items}. For unsold
+ {@link ProposalLineItem proposal line items}, it is calculated by multiplying
+ {@link Proposal#probabilityOfClose} by the contracted revenue including agency commission when
+ inventory is not reserved; otherwise it is calcualted by multiplying
+ {@link Proposal#probabilityOfClose} by the forecasted revenue including agency commission.
+ <p>Corresponds to "Pipeline revenue (gross)" in the DFP UI. Compatible with the SALES report type.</p>
+
+
+
+
+
+
+ The pipeline gross revenue in the local currency of the {@link ProposalLineItem}. There is no
+ revenue for sold {@link ProposalLineItem proposal line items}. For unsold
+ {@link ProposalLineItem proposal line items}, it is calculated by multiplying
+ {@link Proposal#probabilityOfClose} by the contracted revenue including agency commission when
+ inventory is not reserved; otherwise it is calcualted by multiplying
+ {@link Proposal#probabilityOfClose} by the forecasted revenue including agency commission.
+
+ See {@link #SALES_PIPELINE_PIPELINE_GROSS_REVENUE}
+ <p>Corresponds to "Pipeline revenue (gross) (local)" in the DFP UI. Compatible with the SALES report type.</p>
+
+
+
+
+
+
+ The pipeline agency commission of the {@link ProposalLineItem}. There is no revenue for sold
+ {@link ProposalLineItem proposal line items}. For unsold
+ {@link ProposalLineItem proposal line items}, it is calculated against gross pipeline revenue.
+ <p>Corresponds to "Pipeline agency commission" in the DFP UI. Compatible with the SALES report type.</p>
+
+
+
+
+
+
+ The pipeline agency commission in the local currency of the {@link ProposalLineItem}. There is
+ no revenue for sold {@link ProposalLineItem proposal line items}. For unsold
+ {@link ProposalLineItem proposal line items}, it is calculated against gross pipeline revenue
+ in local currency of the {@link ProposalLineItem}.
+
+ See {@link #SALES_PIPELINE_PIPELINE_AGENCY_COMMISSION}
+ <p>Corresponds to "Pipeline agency commission (local)" in the DFP UI. Compatible with the SALES report type.</p>
+
+
+
+
+
+
+ The DFP volume of the {@link ProposalLineItem}, which is used for reconciliation. Volume
+ represents impressions for rate type CPM, clicks for CPC and days for CPD.
+ <p>Corresponds to "DFP volume" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The third party volume of the {@link ProposalLineItem}, which is used for reconciliation.
+ Volume represents impressions for rate type CPM, clicks for CPC and days for CPD.
+ <p>Corresponds to "Third-party volume" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The reconciled volume of the {@link ProposalLineItem}, which is used for reconciliation. Volume
+ represents impressions for rate type CPM, clicks for CPC and days for CPD.
+ <p>Corresponds to "Reconciled volume" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The discrepancy percentage between DFP volume and third party volume.
+ <p>Corresponds to "Discrepancy (%)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The reconciled revenue of the {@link LineItem}.
+ <p>Corresponds to "Reconciled revenue" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The discrepancy between DFP impressions and third party impressions.
+ <p>Corresponds to "Impression discrepancy" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The discrepancy between DFP clicks and third party clicks.
+ <p>Corresponds to "Click discrepancy" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The discrepancy between DFP revenue and third party revenue.
+ <p>Corresponds to "Revenue discrepancy" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The billable net revenue of the {@link ProposalLineItem}. It is calculated from reconciled
+ volume and rate, with cap applied.
+ <p>Corresponds to "Billable revenue (net)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The billable net revenue in the local currency of the {@link ProposalLineItem}. It is
+ calculated from reconciled volume and rate, with cap applied.
+
+ See {@link #BILLING_BILLABLE_NET_REVENUE}
+ <p>Corresponds to "Billable revenue (net) (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The billable gross revenue of the {@link ProposalLineItem}. It is calculated from reconciled
+ volume and rate, with cap applied, and including agency commission.
+ <p>Corresponds to "Billable revenue (gross)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The billable gross revenue in the local currency of the {@link ProposalLineItem}. It is
+ calculated from reconciled volume and rate, with cap applied, and including agency commission.
+
+ See {@link #BILLING_BILLABLE_GROSS_REVENUE}
+ <p>Corresponds to "Billable revenue (gross) (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The billable net revenue of the {@link ProposalLineItem} before manual adjustment. It is
+ calculated from reconciled volume and rate, with cap applied, before manual adjustment.
+ <p>Corresponds to "Billable revenue before manual adjustment (net)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The billable net revenue in local currency of the {@link ProposalLineItem} before manual
+ adjustment. It is calculated from reconciled volume and rate, with cap applied, before manual
+ adjustment.
+
+ <p>See {@link #BILLING_BILLABLE_NET_REVENUE_BEFORE_MANUAL_ADJUSTMENT}
+ <p>Corresponds to "Billable revenue before manual adjustment (net) (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The billable gross revenue of the {@link ProposalLineItem} before manual adjustment. It is
+ calculated from reconciled volume and rate, with cap applied, before manual adjustment.
+ <p>Corresponds to "Billable revenue before manual adjustment (gross)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The billable net revenue in local currency of the {@link ProposalLineItem} before manual
+ adjustment. It is calculated from reconciled volume and rate, with cap applied, before manual
+ adjustment.
+
+ <p>See {@link #BILLING_BILLABLE_GROSS_REVENUE_BEFORE_MANUAL_ADJUSTMENT}
+ <p>Corresponds to "Billable revenue before manual adjustment (gross) (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The value added tax on billable net revenue of the {@link ProposalLineItem} or {@link
+ Proposal}.
+ <p>Corresponds to "Billable VAT" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The value added tax on billable net revenue in the local currency of the
+ {@link ProposalLineItem} or {@link Proposal}.
+
+ See {@link #BILLING_BILLABLE_VAT}
+ <p>Corresponds to "Billable VAT (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The billable agency commission of the {@link ProposalLineItem} or {@link Proposal}.
+ <p>Corresponds to "Billable agency commission" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The billable agency commission in the local currency of the {@link ProposalLineItem} or
+ {@link Proposal}.
+
+ See {@link #BILLING_BILLABLE_AGENCY_COMMISSION}
+ <p>Corresponds to "Billable agency commission (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The cap quantity of the {@link ProposalLineItem} for each cycle. Quantity represents
+ impressions for rate type CPM, clicks for CPC and days for CPD.
+ <p>Corresponds to "Cap quantity" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The billable volume of the {@link ProposalLineItem} for each cycle. Billable volumes are
+ calculated by applying cap quantity to reconciled volumes. Volume represents impressions for
+ rate type CPM, clicks for CPC and days for CPD.
+ <p>Corresponds to "Billable volume" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The delivery rollover volume of the {@link ProposalLineItem} from previous cycle. Volume
+ represents impressions for rate type CPM, clicks for CPC and days for CPD.
+ <p>Corresponds to "Delivery rollover" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The CPM calcuated by {@link #BILLING_BILLABLE_NET_REVENUE} and {@link #AD_SERVER_IMPRESSIONS}.
+ <p>Corresponds to "Realized CPM" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The rate calcuated by {@link #BILLING_BILLABLE_NET_REVENUE} and DFP volume.
+ <p>Corresponds to "Realized rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The contracted net overall discount of the {@link ProposalLineItem}.
+ <p>Corresponds to "Contracted overall discount (net)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The billable net overall discount of the {@link ProposalLineItem}.
+ <p>Corresponds to "Billable overall discount (net)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The contracted non-billable (net) of the {@link ProposalLineItem}.
+ The non-billable means revenue that marked as make good, added value or barter.
+ <p>Corresponds to "Contracted non-billable (net)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p>
+
+
+
+
+
+
+ The number of invoiced impressions.
+ <p>Corresponds to "Invoiced impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ The number of invoiced unfilled impressions.
+ <p>Corresponds to "Invoiced unfilled impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ The total number of impressions tracked for Nielsen Digital Ad Ratings measurement.
+ <p>Corresponds to "Impressions" in the DFP UI. Compatible with the REACH report type.</p>
+
+
+
+
+
+
+ The total number of impressions for in-target demographic tracked for Nielsen Digital Ad
+ Ratings measurement.
+ <p>Corresponds to "In-target impressions" in the DFP UI. Compatible with the REACH report type.</p>
+
+
+
+
+
+
+ The population in the demographic.
+ <p>Corresponds to "Population base" in the DFP UI. Compatible with the REACH report type.</p>
+
+
+
+
+
+
+ The total population for all in-target demographics.
+ <p>Compatible with the REACH report type.</p>
+
+
+
+
+
+
+ The total number of different people within the selected demographic who were reached.
+ <p>Corresponds to "Unique audience" in the DFP UI. Compatible with the REACH report type.</p>
+
+
+
+
+
+
+ The total number of different people within all in-target demographics who were reached.
+ <p>Compatible with the REACH report type.</p>
+
+
+
+
+
+
+ The unique audience reached as a percentage of the population base.
+ <p>Corresponds to "% audience reach" in the DFP UI. Compatible with the REACH report type.</p>
+
+
+
+
+
+
+ The unique audience reached as a percentage of the population base for all in-target
+ demographics.
+ <p>Compatible with the REACH report type.</p>
+
+
+
+
+
+
+ The average number of times that a person within the target audience sees an advertisement.
+ <p>Corresponds to "Average frequency" in the DFP UI. Compatible with the REACH report type.</p>
+
+
+
+
+
+
+ The average number of times that a person within the target audience sees an advertisement
+ for all in-target demographics.
+ <p>Compatible with the REACH report type.</p>
+
+
+
+
+
+
+ The unit of audience volume, which is based on the percentage of the reached target audience
+ population multiplied by the average frequency.
+ <p>Corresponds to "Gross rating points" in the DFP UI. Compatible with the REACH report type.</p>
+
+
+
+
+
+
+ The unit of audience volume, which is based on the percentage of the reached target audience
+ population multiplied by the average frequency, for all in-target demographics.
+ <p>Compatible with the REACH report type.</p>
+
+
+
+
+
+
+ The share of impressions that reached the target demographic.
+ <p>Corresponds to "% impression share" in the DFP UI. Compatible with the REACH report type.</p>
+
+
+
+
+
+
+ The share of impressions that reached all in-target demographics.
+ <p>Corresponds to "In-target % impression share" in the DFP UI. Compatible with the REACH report type.</p>
+
+
+
+
+
+
+ The share of the total population represented by the population base.
+ <p>Corresponds to "% population share" in the DFP UI. Compatible with the REACH report type.</p>
+
+
+
+
+
+
+ The share of the total population for all in-target demographics represented by the
+ population base.
+ <p>Compatible with the REACH report type.</p>
+
+
+
+
+
+
+ The share of the unique audience in the demographic.
+ <p>Corresponds to "% audience share" in the DFP UI. Compatible with the REACH report type.</p>
+
+
+
+
+
+
+ The share of the unique audience for all in-target demographics.
+ <p>Compatible with the REACH report type.</p>
+
+
+
+
+
+
+ The relative unique audience in the demographic compared with its share of the overall
+ population.
+ <p>Corresponds to "Audience index" in the DFP UI. Compatible with the REACH report type.</p>
+
+
+
+
+
+
+ The relative unique audience for all in-target demographics compared with its share of the
+ overall population.
+ <p>Compatible with the REACH report type.</p>
+
+
+
+
+
+
+ The relative impressions per person in the demographic compared with the impressions per person
+ for the overall population.
+ <p>Corresponds to "Impressions index" in the DFP UI. Compatible with the REACH report type.</p>
+
+
+
+
+
+
+ The relative impressions per person for all in-target demographics compared with the
+ impressions per person for the overall population.
+ <p>Compatible with the REACH report type.</p>
+
+
+
+
+
+
+ The host impressions in the partner management.
+ <p>Corresponds to "Host impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The host clicks in the partner management.
+ <p>Corresponds to "Host clicks" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The host CTR in the partner management.
+ <p>Corresponds to "Host CTR" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The unfilled impressions in the partner management.
+ <p>Corresponds to "Unfilled impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, PARTNER_FINANCE.</p>
+
+
+
+
+
+
+ The partner impressions in the partner management.
+ <p>Corresponds to "Partner impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The partner clicks in the partner management.
+ <p>Corresponds to "Partner clicks" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The partner CTR in the partner management.
+ <p>Corresponds to "Partner CTR" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ The gross revenue in the partner management.
+ <p>Corresponds to "Gross revenue" in the DFP UI. Compatible with the HISTORICAL report type.</p>
+
+
+
+
+
+
+ Monthly host impressions for partner finance reports.
+ <p>Corresponds to "Host impressions" in the DFP UI. Compatible with the PARTNER_FINANCE report type.</p>
+
+
+
+
+
+
+ Monthly host revenue for partner finance reports.
+ <p>Corresponds to "Host revenue" in the DFP UI. Compatible with the PARTNER_FINANCE report type.</p>
+
+
+
+
+
+
+ Monthly host eCPM for partner finance reports.
+ <p>Corresponds to "Host eCPM" in the DFP UI. Compatible with the PARTNER_FINANCE report type.</p>
+
+
+
+
+
+
+ Monthly partner revenue for partner finance reports.
+ <p>Corresponds to "Partner revenue" in the DFP UI. Compatible with the PARTNER_FINANCE report type.</p>
+
+
+
+
+
+
+ Monthly partner eCPM for partner finance reports.
+ <p>Corresponds to "Partner eCPM" in the DFP UI. Compatible with the PARTNER_FINANCE report type.</p>
+
+
+
+
+
+
+ Monthly gross revenue for partner finance reports.
+ <p>Corresponds to "Gross revenue" in the DFP UI. Compatible with the PARTNER_FINANCE report type.</p>
+
+
+
+
+
+
+
+
+ Describes reasons for common errors
+
+
+
+
+
+
+ Indicates that an attempt was made to retrieve an entity that does not
+ exist.
+
+
+
+
+
+
+ Indicates that an attempt was made to create an entity that already
+ exists.
+
+
+
+
+
+
+ Indicates that a value is not applicable for given use case.
+
+
+
+
+
+
+ Indicates that two elements in the collection were identical.
+
+
+
+
+
+
+ Indicates that an attempt was made to change an immutable field.
+
+
+
+
+
+
+ Indicates that another request attempted to update the same data in the same network
+ at about the same time. Please wait and try the request again.
+
+
+
+
+
+
+ The value returned if the actual value is not exposed by the requested API version.
+
+
+
+
+
+
+
+
+ The reason behind the currency code error.
+
+
+
+
+
+
+ The currency code is invalid and does not follow ISO 4217.
+
+
+
+
+
+
+ The currency code is valid, but is not supported.
+
+
+
+
+
+
+
+
+ Represents a period of time.
+
+
+
+
+
+
+ The current day.
+
+
+
+
+
+
+ The previous day.
+
+
+
+
+
+
+ The last week, from monday to sunday.
+
+
+
+
+
+
+ The previous month.
+
+
+
+
+
+
+ The last 3 full months. For example, if today is May 5, 2017, then LAST_3_MONTHS would go from
+ February 1 to April 30.
+
+
+
+
+
+
+ The last 5 months and the current month to date. This date range is only
+ usable for the columns {@link Column#REACH_FREQUENCY},
+ {@link Column#REACH_AVERAGE_REVENUE} and {@link Column#REACH}.
+
+
+
+
+
+
+ Specifying this value will enable the user to specify
+ {@link ReportQuery#startDate} and {@link ReportQuery#endDate}.
+
+
+
+
+
+
+ The next day.
+
+
+
+
+
+
+ The next ninety days.
+
+
+
+
+
+
+ The next week, from monday to sunday.
+
+
+
+
+
+
+ The next month.
+
+
+
+
+
+
+ Beginning of the next day until the end of the next month.
+
+
+
+
+
+
+ The next quarter.
+
+
+
+
+
+
+ The next three months.
+
+
+
+
+
+
+ The next twelve months.
+
+
+
+
+
+
+
+
+ {@code Dimension} provides the break-down and filterable types available for
+ running a {@link ReportJob}. Aggregate and percentage columns will be
+ calculated based on these groupings.
+
+
+
+
+
+
+ Breaks down reporting data by month and year in the network time zone. Can
+ be used to filter on month using ISO 4601 format 'YYYY-MM'.
+
+ <p><b>Note:</b> In v201802 and later, this dimension is compatible with the following
+ time zone types:
+ <ul>
+ <li> {@link TimeZoneType.PUBLISHER}
+ <li> {@link TimeZoneType.PROPOSAL_LOCAL}
+ </ul>
+ <p>Corresponds to "Month and year" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, PARTNER_FINANCE, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by week of the year in the network time zone.
+ Cannot be used for filtering.
+
+ <p><b>Note:</b> In v201802 and later, this dimension is compatible with the following
+ time zone types:
+ <ul>
+ <li> {@link TimeZoneType.PUBLISHER}
+ <li> {@link TimeZoneType.PROPOSAL_LOCAL}
+ </ul>
+ <p>Corresponds to "Week" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by date in the network time zone. Can be used to
+ filter by date using ISO 8601's format 'YYYY-MM-DD'".
+
+ <p><b>Note:</b> In v201802 and later, this dimension is compatible with the following
+ time zone types:
+ <ul>
+ <li> {@link TimeZoneType.PUBLISHER}
+ <li> {@link TimeZoneType.PROPOSAL_LOCAL}
+ </ul>
+ <p>Corresponds to "Date" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by day of the week in the network time zone. Can
+ be used to filter by day of the week using the index of the day (from 1 for
+ Monday is 1 to 7 for Sunday).
+ <p>Corresponds to "Day of week" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by hour of the day in the network time zone. Can
+ be used to filter by hour of the day (from 0 to 23).
+ <p>Corresponds to "Hour" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by {@link LineItem#id}. Can be used to
+ filter by {@link LineItem#id}.
+ <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by line item. {@link LineItem#name} and
+ {@link LineItem#id} are automatically included as columns in the report.
+ Can be used to filter by {@link LineItem#name}.
+ <p>Corresponds to "Line item" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by {@link LineItem#lineItemType}. Can be used
+ to filter by line item type using {@link LineItemType} enumeration names.
+ <p>Corresponds to "Line item type" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by aggregated demand channel type.
+
+ <p>This field is deprecated and will be removed in v201805.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by {@link Order#id}. Can be used to filter by
+ {@link Order#id}.
+ <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by order. {@link Order#name} and
+ {@link Order#id} are automatically included as columns in the report. Can
+ be used to filter by {@link Order#name}.
+ <p>Corresponds to "Order" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Delivery status of the order. Not available as a dimension to report on,
+ but exists as a dimension in order to filter on it using PQL.
+ Valid values are 'STARTED', 'NOT_STARTED' and 'COMPLETED'.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by advertising company {@link Company#id}. Can
+ be used to filter by {@link Company#id}.
+ <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by advertising company. {@link Company#name} and
+ {@link Company#id} are automatically included as columns in the report.
+ Can be used to filter by {@link Company#name}.
+ <p>Corresponds to "Advertiser" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ The network that provided the ad for SDK ad mediation.
+
+ <p>If selected for a report, that report will include only SDK mediation ads and will not
+ contain non-SDK mediation ads.
+
+ <p>SDK mediation ads are ads for mobile devices. They have a list of ad networks which can
+ provide ads to serve. Not every ad network will have an ad to serve so the device will try each
+ network one-by-one until it finds an ad network with an ad to serve. The ad network that ends
+ up serving the ad will appear here. Note that this id does not correlate to anything in the
+ companies table and is not the same id as is served by {@link #ADVERTISER_ID}.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ The name of the network defined in {@link #AD_NETWORK_ID}.
+ <p>Corresponds to "Ad network name" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH.</p>
+
+
+
+
+
+
+ Breaks down reporting data by salesperson {@link User#id}. Can be used to
+ filter by {@link User#id}.
+ <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by salesperson. {@link User#name} and
+ {@link User#id} of the salesperson are automatically included as columns in
+ the report. Can be used to filter by {@link User#name}.
+ <p>Corresponds to "Salesperson" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by {@link Creative#id} or creative set id
+ (master's {@link Creative#id}) if the creative is part of a creative set.
+ Can be used to filter by {@link Creative#id}.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH, DATA_LEAKAGE, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by creative. {@link Creative#name} and
+ {@link Creative#id} are automatically included as columns in the report.
+ Can be used to filter by {@link Creative#name}.
+ <p>Corresponds to "Creative" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by creative type.
+ <p>Corresponds to "Creative type" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by creative billing type.
+ <p>Corresponds to "Creative billing type" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by custom event ID.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by custom event name.
+ <p>Corresponds to "Custom event" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by custom event type (timer/exit/counter).
+ <p>Corresponds to "Custom event type" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by {@link Creative#size}. Cannot be used for
+ filtering.
+ <p>Corresponds to "Creative size" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by {@link AdUnit#id}. Can be used to filter by
+ {@link AdUnit#id}. {@link #AD_UNIT_NAME}, i.e. {@link AdUnit#name}, is
+ automatically included as a dimension in the report.
+ <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by ad unit. {@link AdUnit#name} and
+ {@link AdUnit#id} are automatically included as columns in the report. Can
+ be used to filter by {@link AdUnit#name}.
+ <p>Corresponds to "Ad unit" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Used to filter on all the descendants of an ad unit by {@link AdUnit#id}. Not available as a
+ dimension to report on.
+ <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Used to filter on all the descendants of an ad unit by {@link AdUnit#name}. Not available as a
+ dimension to report on.
+ <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by {@link Placement#id}. Can be used to filter
+ by {@link Placement#id}.
+ <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by placement. {@link Placement#name} and
+ {@link Placement#id} are automatically included as columns in the report.
+ Can be used to filter by {@link Placement#name}.
+ <p>Corresponds to "Placement" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Status of the placement. Not available as a dimension to report on, but
+ exists as a dimension in order to filter on it using PQL. Can be used to
+ filter on {@link Placement#status} by using {@link InventoryStatus}
+ enumeration names.
+ <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by criteria predefined by DoubleClick For Publishers like the
+ operating system, browser etc. Cannot be used for filtering.
+ <p>Corresponds to "Targeting" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH.</p>
+
+
+
+
+
+
+ The ID of the device category to which an ad is being targeted.
+
+ Can be used to filter by device category ID.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ The category of device (smartphone, feature phone, tablet, or desktop) to which an ad is being
+ targeted.
+
+ Can be used to filter by device category name.
+ <p>Corresponds to "Device category" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by country criteria ID. Can be used to filter by
+ country criteria ID.
+ <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by country name. The country name and the
+ country criteria ID are automatically included as columns in the report.
+ Can be used to filter by country name using the US English name.
+ <p>Corresponds to "Country" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by region criteria ID. Can be used to filter by
+ region criteria ID.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by region name. The region name and the region
+ criteria ID are automatically included as columns in the report. Can be
+ used to filter by region name using the US English name.
+ <p>Corresponds to "Region" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by city criteria ID. Can be used to filter by
+ city criteria ID.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by city name. The city name and the city
+ criteria ID are automatically included as columns in the report. Can be
+ used to filter by city name using the US English name.
+ <p>Corresponds to "City" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by metro criteria ID. Can be used to filter by
+ metro criteria ID.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by metro name. The metro name and the metro
+ criteria ID are automatically included as columns in the report. Can be
+ used to filter by metro name using the US English name.
+ <p>Corresponds to "Metro" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by postal code criteria ID. Can be used to
+ filter by postal code criteria ID.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by postal code. The postal code and the postal
+ code criteria ID are automatically included as columns in the report. Can
+ be used to filter by postal code.
+ <p>Corresponds to "Postal code" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH.</p>
+
+
+
+
+
+
+ Breaks down reporting data by {@link CustomTargetingValue#id}. Can be used
+ to filter by {@link CustomTargetingValue#id}.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH, SALES.</p>
+
+
+
+
+
+
+ Breaks down reporting data by custom criteria. The {@link CustomTargetingValue} is
+ displayed in the form:
+ <ul>
+ <li>
+ car=honda when value match type is
+ {@link CustomTargetingValue.MatchType#EXACT}
+ </li>
+ <li>
+ car~honda when value match type is
+ {@link CustomTargetingValue.MatchType#BROAD}
+ </li>
+ <li>
+ car=*honda when value match type is
+ {@link CustomTargetingValue.MatchType#PREFIX}
+ </li>
+ <li>
+ car~*honda when value match type is
+ {@link CustomTargetingValue.MatchType#BROAD_PREFIX}
+ </li>
+ </ul>
+ {@link #CUSTOM_TARGETING_VALUE_ID}, i.e. {@link CustomTargetingValue#id} is
+ automatically included as a column in the report.
+ Cannot be used for filtering; use {@link #CUSTOM_TARGETING_VALUE_ID} instead.
+ <p>
+ When using this {@code Dimension}, metrics for freeform key values are only
+ reported on when they are registered with {@code CustomTargetingService}.
+ <p>Corresponds to "Key-values" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES.</p>
+
+
+
+
+
+
+ Breaks down reporting data by activity ID. Can be used to filter by
+ activity ID.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH.</p>
+
+
+
+
+
+
+ Breaks down reporting data by activity. The activity name and the activity
+ ID are automatically included as columns in the report. Can be used to
+ filter by activity name.
+ <p>Corresponds to "Activity" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH.</p>
+
+
+
+
+
+
+ Breaks down reporting data by activity group ID. Can be used to filter by
+ activity group ID.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH.</p>
+
+
+
+
+
+
+ Breaks down reporting data by activity group. The activity group name and
+ the activity group ID are automatically included as columns in the report.
+ Can be used to filter by activity group name.
+ <p>Corresponds to "Activity group" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH.</p>
+
+
+
+
+
+
+ Breaks down reporting data by {@link Content#id}. Can be used to filter by
+ {@link Content#id}.
+ <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by content. {@link Content#name} and
+ {@link Content#id} are automatically included as columns in the report. Can
+ be used to filter by {@link Content#name}.
+ <p>Corresponds to "Content" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by {@link ContentBundle#id}. Can be used to filter
+ by {@link ContentBundle#id}.
+ <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by content bundle. {@link ContentBundle#name} and
+ {@link ContentBundle#id} are automatically included as columns in the
+ report. Can be used to filter by {@link ContentBundle#name}.
+ <p>Corresponds to "Content bundle" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by the content hierarchy. To use this dimension, a list of custom
+ targeting key IDs must be specified in
+ {@link ReportQuery#contentMetadataKeyHierarchyCustomTargetingKeyIds}.
+ <p>
+ This dimension can be used as a filter in the {@link Statement} in PQL syntax:
+ CONTENT_HIERARCHY_CUSTOM_TARGETING_KEY[contentMetadataKeyHierarchyCustomTargetingKeyId]_ID =
+ {@link CustomTargetingValue#id custom targeting value ID}
+ <p>
+ For example: WHERE CONTENT_HIERARCHY_CUSTOM_TARGETING_KEY[4242]_ID = 53423
+
+
+
+
+
+
+ Breaks down reporting data by the fallback position of the video ad, i.e.,
+ {@code NON_FALLBACK}, {@code FALLBACK_POSITION_1}, {@code FALLBACK_POSITION_2}, etc. Can be
+ used for filtering.
+ <p>Corresponds to "Fallback position" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by the position of the video ad within the video stream, i.e.,
+ {@code UNKNOWN_POSITION}, {@code PREROLL}, {@code POSTROLL}, {@code UNKNOWN_MIDROLL},
+ {@code MIDROLL_1}, {@code MIDROLL_2}, etc. {@code UNKNOWN_MIDROLL} represents a midroll, but
+ which specific midroll is unknown. Can be used for filtering.
+ <p>Corresponds to "Position of pod" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by the position of the video ad within the pod, i.e.,
+ {@code UNKNOWN_POSITION}, {@code POSITION_1}, {@code POSITION_2}, etc.
+ Can be used for filtering.
+ <p>Corresponds to "Position in pod" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by partner {@link Company#id}.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH, PARTNER_FINANCE.</p>
+
+
+
+
+
+
+ Breaks down reporting data by partner {@link Company#name} and {@link Company#id} are
+ automatically included as columns in the report.
+ <p>Corresponds to "Partner" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, PARTNER_FINANCE.</p>
+
+
+
+
+
+
+ Breaks down reporting data by partner label {@link Label#id}.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH, PARTNER_FINANCE.</p>
+
+
+
+
+
+
+ Breaks down reporting data by partner label. {@link Label#name} and {@link Label#id} are
+ automatically included as columns in the report.
+ <p>Corresponds to "Partner label" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, PARTNER_FINANCE.</p>
+
+
+
+
+
+
+ Breaks down reporting data by partner assignment id.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH, PARTNER_FINANCE.</p>
+
+
+
+
+
+
+ Breaks down reporting data by partner assignment name. ParnterAssignment name
+ and id are automatically included as columns in the report.
+ <p>Corresponds to "Assignment" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, PARTNER_FINANCE.</p>
+
+
+
+
+
+
+ Breaks down reporting data by gender and age group, i.e., MALE_13_TO_17, MALE_18_TO_24,
+ MALE_25_TO_34, MALE_35_TO_44, MALE_45_TO_54, MALE_55_TO_64, MALE_65_PLUS, FEMALE_13_TO_17,
+ FEMALE_18_TO_24, FEMALE_25_TO_34, FEMALE_35_TO_44, FEMALE_45_TO_54, FEMALE_55_TO_64,
+ FEMALE_65_PLUS, UNKNOWN_0_TO_17 and UNKNOWN. Whenever this dimension is selected, {@link
+ #COUNTRY_NAME} must be selected.
+
+ <p>This dimension is supported only for GRP columns.
+ <p>Can correspond to any of the following in the DFP UI: Demographics, comScore vCE demographics. Compatible with any of the following report types: HISTORICAL, REACH.</p>
+
+
+
+
+
+
+ Size of the creative requested for an ad.
+ <p>Corresponds to "Ad request size" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH.</p>
+
+
+
+
+
+
+ Breaks down reporting data by the ad unit sizes specified in ad requests.
+
+ <p>Formatted as comma separated values, e.g. "300x250,300x250v,300x60".
+
+ <p>This dimension is supported only for sell-through columns.
+ <p>Corresponds to "Ad request sizes" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH.</p>
+
+
+
+
+
+
+ Breaks down reporting data by the custom criteria specified in ad requests.
+
+ <p>Formatted as comma separated
+ {@link CustomTargetingKey key}-{@link CustomTargetingValue values}, where a key-value is
+ formatted as {@code key1=value_1|...|value_n,key2=value_1|...|value_n,...}.
+
+ <p>This dimension is supported only for sell-through columns.
+ <p>Corresponds to "Key-values" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH.</p>
+
+
+
+
+
+
+ The unique identifier used for an ad network that is associated with the company that the ad is
+ served for.
+ <p>Compatible with any of the following report types: BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ The name of the ad network that is associated with the company that the ad is served for.
+ <p>Corresponds to "Buyer" in the DFP UI. Compatible with any of the following report types: BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Whether the report contains only Ad Exchange traffic fulfilled by First Look Deals
+ or omits it. If this filter isn't included, the report will include
+ First Look Deals traffic in addition to any other traffic.
+ Not available as a dimension to report on.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by mediation group ID. A mediation group is an abstraction of
+ inventory used in the DFP Mediation.
+
+ <p>This field is deprecated and will be removed in v201805.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by mediation group name. A mediation group is an abstraction of
+ inventory used in the DFP Mediation.
+
+ <p>This field is deprecated and will be removed in v201805.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by yield group ID.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH.</p>
+
+
+
+
+
+
+ Breaks down reporting data by yield group name.
+ <p>Corresponds to "Yield group" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH.</p>
+
+
+
+
+
+
+ Breaks down reporting data by yield partner.
+ <p>Corresponds to "Yield partner" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, DFP_HISTORICAL_DATA_STUDIO.</p>
+
+
+
+
+
+
+ Breaks down reporting data by the tag of a yield partner in a yield group.
+ <p>Corresponds to "Yield partner tag" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by mediation network.
+
+ <p>This field is deprecated and will be removed in v201805.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange network tag name.
+
+ <p>This field is deprecated and will be removed in v201805.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by mediation type. A mediation type can be web, mobile app or
+ video.
+ <p>Corresponds to "Mediation type" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by native template (also known as creative template) ID.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by native template (also known as creative template) name.
+ <p>Corresponds to "Native ad format name" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by native style ID.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by native style name.
+ <p>Corresponds to "Native style name" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by mobile app name. Can be used for filtering.
+ <p>Corresponds to "App names" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by device name. Can be used for filtering.
+ <p>Corresponds to "Devices" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by inventory type. Can be used for filtering.
+ <p>Corresponds to "Inventory types" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by request type. Can be used for filtering.
+ <p>Corresponds to "Request type" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ ID of the advertiser that filled the ad either directly (through DFP) or indirectly via
+ Google Ad Exchange or another ad network or exchange.
+ <p>Compatible with any of the following report types: BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Name of the advertiser that filled the ad either directly (through DFP) or indirectly via
+ Google Ad Exchange or another ad network or exchange.
+ <p>Corresponds to "Verified advertiser" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Status of the ad unit. Not available as a dimension to report on,
+ but exists as a dimension in order to filter on it using PQL.
+ Valid values correspond to {@link InventoryStatus}.
+ <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by {@link Creative#id}. This includes regular creatives,
+ and master and companions in case of creative sets.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by creative. This includes regular creatives,
+ and master and companions in case of creative sets.
+ <p>Corresponds to "Master and Companion creative" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by {@link ProposalLineItem#id}. Can be used to filter by
+ {@link ProposalLineItem#id}.
+ <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by {@link ProposalLineItem#name}. Can be used to filter by
+ {@link ProposalLineItem#name}.
+ <p>Corresponds to "Proposal line item" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by {@link Proposal#id}. Can be used to filter by
+ {@link Proposal#id}.
+ <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by {@link Proposal#name}. Can be used to filter by
+ {@link Proposal#name}.
+ <p>Corresponds to "Proposal" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by salesperson {@link User#id}, including both salesperson and
+ secondary salespeople. Can be used to filter by all salespeople {@link User#id}.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by salesperson {@link User#name}, including both salesperson and
+ secondary salespeople. Can be used to filter by all salespeople {@link User#name}.
+ <p>Corresponds to "All salespeople" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Used to filter by {@link User#id} in sales team. Sales team includes salesperson, secondary
+ salesperson, sales planners. Not available as a dimension to report on.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Used to filter by {@link User#name} in sales team. Sales team includes salesperson, secondary
+ salesperson, sales planners. Not available as a dimension to report on.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by proposal agency {@link Company#id}. Can be used to filter by
+ proposal agency {@link Company#id}.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by proposal agency {@link Company#name}. Can be used to filter by
+ proposal agency {@link Company#name}.
+ <p>Corresponds to "Proposal agency" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by {@link Product#id}. Can be used to filter by {@link Product#id}.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by {@link Product#name}.
+ <p>Corresponds to "Product" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by {@link ProductTemplate#id}. Can be used to filter by
+ {@link ProductTemplate#id}.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by {@link ProductTemplate#name}. Can be used to filter by
+ {@link ProductTemplate#name}.
+ <p>Corresponds to "Product template" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by {@link RateCard#id}. Can be used to filter by {@link
+ RateCard#id}.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by {@link RateCard#name}. Can be used to filter by {@link
+ RateCard#name}.
+ <p>Corresponds to "Rate card" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Used to filter by {@link Workflow#id}. Not available as a dimension to report on.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Used to filter by {@link Workflow#name}. Not available as a dimension to report on.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by {@link Package#id}.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by {@link Package#name}.
+ <p>Corresponds to "Package" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by {@link ProductPackage#id}. Can be used to filter by
+ {@link ProductPackage#id}.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by {@link ProductPackage#name}. Can be used to filter by
+ {@link ProductPackage#name}.
+ <p>Corresponds to "Product package" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by billable audience segment ID.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH.</p>
+
+
+
+
+
+
+ Breaks down reporting data by billable audience segment name.
+ <p>Corresponds to "Audience segment (billable)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH.</p>
+
+
+
+
+
+
+ Breaks down reporting data by audience segment data provider name.
+ <p>Corresponds to "Data partner" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange inventory size.
+ <p>Corresponds to "Inventory sizes" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange inventory size code.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange device category.
+ <p>Corresponds to "Device categories" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange pricing rule ID.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange pricing rule.
+ <p>Corresponds to "Pricing rules" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange tag.
+ <p>Corresponds to "Tags" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange URL.
+ <p>Corresponds to "URLs" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Breaks down data by Ad Exchange mapped web property code.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange creative size.
+ <p>Corresponds to "Creative sizes" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange ad type.
+ <p>Corresponds to "Ad Types" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange channel.
+ <p>Corresponds to "Channels" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange product.
+ <p>Corresponds to "Products" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange product code.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange site.
+ <p>Corresponds to "Sites" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange request source.
+ <p>Corresponds to "Request sources" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by the Ad Exchange advertiser name that bids
+ on ads.
+ <p>Corresponds to "Advertisers" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by the Ad Exchange brand name that bids on
+ ads.
+ <p>Corresponds to "Brands" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange agency.
+ <p>Corresponds to "Agencies" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange bid type code.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange branding type code.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange branding type. Examples:
+ Branded, Anonymous.
+ <p>Corresponds to "Branding types" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange ad network name. Example:
+ Google Adwords.
+ <p>Corresponds to "Buyer networks" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange ad network ID.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange custom channel code.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange custom channel ID.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange date, in Ad Exchange timezone.
+
+ <p><b>Note:</b> In v201802 and later, this dimension is compatible with the following
+ time zone types:
+ <ul>
+ <li> {@link TimeZoneType.AD_EXCHANGE}
+ </ul>
+ <p>Corresponds to "Days" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange deal id.
+ <p>Corresponds to "Deal IDs" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange deal name.
+ <p>Corresponds to "Deal names" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange deal/transaction type. Example:
+ Open auction.
+ <p>Corresponds to "Transaction types" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange DSP buyer network name.
+ <p>Corresponds to "DSPs" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange expansion type.
+ <p>Corresponds to "Expandable types" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange country code.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange country name.
+ <p>Corresponds to "Countries" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange DFP ad unit ID.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange DFP ad unit.
+ <p>Corresponds to "DFP Ad Units" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange inventory ownership.
+ <p>Corresponds to "Inventory ownership" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange advertiser domain.
+ <p>Corresponds to "Advertiser domains" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange mobile app name.
+ <p>Corresponds to "App names" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange mobile carrier name.
+ <p>Corresponds to "Carrier names" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange mobile device name.
+ <p>Corresponds to "Devices" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange mobile inventory type.
+ <p>Corresponds to "Inventory types" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange month, in Ad Exchange timezone.
+
+ <p><b>Note:</b> In v201802 and later, this dimension is compatible with the following
+ time zone types:
+ <ul>
+ <li> {@link TimeZoneType.AD_EXCHANGE}
+ </ul>
+ <p>Corresponds to "Months" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange network partner name.
+ <p>Corresponds to "Network partner names" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange operating system version.
+ <p>Corresponds to "Operating systems" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange tags.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange targeting type code.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange targeting type.
+ <p>Corresponds to "Targeting types" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange transaction type code
+ <p>Compatible with any of the following report types: HISTORICAL, REACH.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange URL ID.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange user bandwidth.
+ <p>Corresponds to "Bandwidth" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange video ad duration.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange raw video ad duration.
+ <p>Corresponds to "Video ad durations" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange video ad type.
+ <p>Corresponds to "Video ad types" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange week, in Ad Exchange timezone.
+
+ <p><b>Note:</b> In v201802 and later, this dimension is compatible with the following
+ time zone types:
+ <ul>
+ <li> {@link TimeZoneType.AD_EXCHANGE}
+ </ul>
+ <p>Corresponds to "Weeks" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange ad location.
+ <p>Corresponds to "Ad locations" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Breaks down mapped Ad Exchange web property data by Ad Exchange advertiser vertical.
+ <p>Corresponds to "Advertiser verticals" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p>
+
+
+
+
+
+
+ Campaign date segment of Nielsen Digital Ad Ratings reporting.
+ <p>Corresponds to "Nielsen Digital Ad Ratings segment" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH.</p>
+
+
+
+
+
+
+ Breaks down reporting data by gender and age group, i.e., MALE_18_TO_20, MALE_21_TO_24,
+ MALE_25_TO_29, MALE_30_TO_35, MALE_35_TO_39, MALE_40_TO_44, MALE_45_TO_49, MALE_50_TO_54,
+ MALE_55_TO_64, MALE_65_PLUS, FEMALE_18_TO_20, FEMALE_21_TO_24, FEMALE_25_TO_29,
+ FEMALE_30_TO_34, FEMALE_35_TO_39, FEMALE_40_TO_44, FEMALE_45_TO_49, FEMALE_50_TO_54,
+ FEMALE_55_TO_64, FEMALE_65_PLUS, and OTHER.
+
+
+
+
+
+
+ Data restatement date of Nielsen Digital Ad Ratings data.
+ <p>Corresponds to "Nielsen Digital Ad Ratings restatement date" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH.</p>
+
+
+
+
+
+
+ Breaks down reporting data by {@link ProposalMarketplaceInfo#buyerAccountId}.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by programmatic buyer name.
+ <p>Corresponds to "Programmatic buyer" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by requested ad size(s).
+ This can be a chain of sizes or a single size.
+ <p>Corresponds to "Requested ad sizes" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by the creative size the ad was delivered to.
+ <p>Corresponds to "Creative size (delivered)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by demand channels.
+ <p>Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Breaks down reporting data by demand channel name.
+ <p>Corresponds to "Demand channel" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+
+
+ {@code DimensionAttribute} provides additional fields associated with a
+ {@link Dimension}. It can only be selected with its corresponding
+ {@link Dimension}. For example, {@link DimensionAttribute#ORDER_PO_NUMBER}
+ can only be used if the {@link ReportQuery#dimensions} contains
+ {@link Dimension#ORDER_NAME}.
+
+
+
+
+
+
+ Represents {@link LineItem#effectiveAppliedLabels} as a comma separated list of
+ {@link Label#name} for {@link Dimension#LINE_ITEM_NAME}.
+ <p>Corresponds to "Line item labels" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link LineItem#effectiveAppliedLabels} as a comma separated list of
+ {@link Label#id} for {@link Dimension#LINE_ITEM_NAME}.
+ <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Generated as {@code true} for {@link Dimension#LINE_ITEM_NAME} which is eligible
+ for optimization, {@code false} otherwise.
+ Can be used for filtering.
+ <p>Corresponds to "Optimizable" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Indicates the progress made for the delivery of the {@link Dimension#LINE_ITEM_NAME}.
+
+ <table>
+ <tr>
+ <th scope="col">Progress</th> <th scope="col">Definition</th>
+ </tr>
+ <tr>
+ <td>100%</td>
+ <td>The {@link LineItem} is on track to deliver in full as per
+ {@link LineItem#unitsBought}.</td>
+ </tr>
+ <tr>
+ <td>> 100%</td>
+ <td>The {@link LineItem} is on track to overdeliver.</td>
+ </tr>
+ <tr>
+ <td>< 100%</td>
+ <td>The {@link LineItem} is on track to underdeliver.</td>
+ </tr>
+ <tr>
+ <td>N/A</td>
+ <td>The {@link LineItem} does not have any quantity goals, or there is
+ insufficient information about the {@link LineItem}.</td>
+ </tr>
+ </table>
+ <p>Corresponds to "Delivery Indicator" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link LineItem#deliveryRateType} for {@link Dimension#LINE_ITEM_NAME}.
+ <p>Corresponds to "Delivery pacing" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link LineItem#frequencyCaps} as a comma separated list of
+ "{@link FrequencyCap#maxImpressions} impressions per/every {@link FrequencyCap#numTimeUnits}
+ {@link FrequencyCap#timeUnit}" (e.g. "10 impressions every day,500 impressions per lifetime")
+ for {@link Dimension#LINE_ITEM_NAME}.
+ <p>Corresponds to "Frequency cap" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents the monthly reconciliation status of the line item for
+ {@link Dimension#LINE_ITEM_NAME} and {@link Dimension#MONTH_YEAR}.
+ <p>Corresponds to "Line item reconciliation status" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL, PARTNER_FINANCE.</p>
+
+
+
+
+
+
+ Represents the monthly last reconciliation date time of the line item for
+ {@link Dimension#LINE_ITEM_NAME} and {@link Dimension#MONTH_YEAR}.
+ <p>Corresponds to "Line item last reconciliation time" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL, PARTNER_FINANCE.</p>
+
+
+
+
+
+
+ Represents {@link Company#externalId} for {@link Dimension#ADVERTISER_NAME}.
+ <p>Corresponds to "External advertiser ID" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Company#type} for {@link Dimension#ADVERTISER_NAME}.
+ Can be used for filtering.
+ <p>Corresponds to "Advertiser type" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Company#creditStatus} for {@link Dimension#ADVERTISER_NAME}.
+ Can be used for filtering.
+ <p>Corresponds to "Advertiser credit status" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents name and email address in the form of name(email) of primary contact for {@link
+ Dimension#ADVERTISER_NAME}.
+ <p>Corresponds to "Advertiser primary contact" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents the start date (in YYYY-MM-DD format) for {@link Dimension#ORDER_NAME}.
+ Can be used for filtering.
+ <p>Corresponds to "Order start date" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents the end date (in YYYY-MM-DD format) for {@link Dimension#ORDER_NAME}.
+ Can be used for filtering.
+ <p>Corresponds to "Order end date" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Order#externalOrderId} for {@link Dimension#ORDER_NAME}.
+ <p>Corresponds to "External order ID" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Order#poNumber} for {@link Dimension#ORDER_NAME}.
+ Can be used for filtering.
+ <p>Corresponds to "Order PO number" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Order#orderIsProgrammatic} for {@link Dimension#ORDER_NAME}.
+ Can be used for filtering.
+ <p>Corresponds to "Programmatic order" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents the name of {@link Order#agencyId} for {@link Dimension#ORDER_NAME}.
+ <p>Corresponds to "Agency" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Order#agencyId} for {@link Dimension#ORDER_NAME}.
+ Can be used for filtering.
+ <p>Corresponds to "Agency ID" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Order#effectiveAppliedLabels} as a comma separated list of
+ {@link Label#name} for {@link Dimension#ORDER_NAME}.
+ <p>Corresponds to "Order labels" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Order#effectiveAppliedLabels} as a comma separated list of
+ {@link Label#id} for {@link Dimension#ORDER_NAME}.
+ <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ The name and email address in the form of name(email) of the trafficker for
+ {@link Dimension#ORDER_NAME}
+ <p>Corresponds to "Trafficker" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Order#traffickerId} for {@link Dimension#ORDER_NAME}.
+ Can be used for filtering.
+ <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ The names and email addresses as a comma separated list of name(email) of the
+ {@link Order#secondaryTraffickerIds} for {@link Dimension#ORDER_NAME}.
+ <p>Corresponds to "Secondary traffickers" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ The name and email address in the form of name(email) of the
+ {@link Order#salespersonId} for {@link Dimension#ORDER_NAME}.
+ <p>Corresponds to "Salesperson" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ The names and email addresses as a comma separated list of name(email) of the
+ {@link Order#secondarySalespersonIds} for {@link Dimension#ORDER_NAME}.
+ <p>Corresponds to "Secondary salespeople" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ The total number of impressions delivered over the lifetime of an
+ {@link Dimension#ORDER_NAME}.
+ <p>Corresponds to "Order lifetime impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ The total number of clicks delivered over the lifetime of an
+ {@link Dimension#ORDER_NAME}.
+ <p>Corresponds to "Order lifetime clicks" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ The cost of booking all the CPM ads for {@link Dimension#ORDER_NAME}.
+ <p>Corresponds to "Booked CPM" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ The cost of booking all the CPC ads for {@link Dimension#ORDER_NAME}.
+ <p>Corresponds to "Booked CPC" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents the start date (in YYYY-MM-DD format) for {@link Dimension#LINE_ITEM_NAME}.
+ Can be used for filtering.
+ <p>Corresponds to "Line item start date" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents the end date (in YYYY-MM-DD format) for {@link Dimension#LINE_ITEM_NAME}.
+ Can be used for filtering.
+ <p>Corresponds to "Line item end date" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link LineItem#externalId} for {@link Dimension#LINE_ITEM_NAME}.
+ Can be used for filtering.
+ <p>Corresponds to "External Line Item ID" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link LineItem#costType} for {@link Dimension#LINE_ITEM_NAME}.
+ Can be used for filtering.
+ <p>Corresponds to "Cost type" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link LineItem#costPerUnit} for {@link Dimension#LINE_ITEM_NAME}.
+ <p>Corresponds to "Rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents the 3 letter currency code for {@link Dimension#LINE_ITEM_NAME}.
+ <p>Corresponds to "Currency code" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ The total number of impressions, clicks or days that is reserved
+ for {@link Dimension#LINE_ITEM_NAME}.
+ <p>Corresponds to "Goal quantity" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ The ratio between the goal quantity for {@link Dimension#LINE_ITEM_NAME} of
+ {@link LineItemType#SPONSORSHIP} and the {@link #LINE_ITEM_GOAL_QUANTITY}.
+ Represented as a number between 0..100.
+ <p>Corresponds to "Sponsorship goal (%)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ The total number of impressions delivered over the lifetime of a
+ {@link Dimension#LINE_ITEM_NAME}.
+ <p>Corresponds to "Line item lifetime impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ The total number of clicks delivered over the lifetime of a
+ {@link Dimension#LINE_ITEM_NAME}.
+ <p>Corresponds to "Line item lifetime clicks" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link LineItem#priority} for {@link Dimension#LINE_ITEM_NAME} as
+ a value between 1 and 16.
+ Can be used for filtering.
+ <p>Corresponds to "Line item priority" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Indicates if a creative is a regular creative or creative set.
+ Values will be 'Creative' or 'Creative set'
+ <p>Compatible with any of the following report types: HISTORICAL, REACH, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ The type of creative in a creative set - master or companion.
+ <p>Corresponds to "Master or Companion" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents the {@link LineItem#contractedUnitsBought} quantity
+ for {@link Dimension#LINE_ITEM_NAME}.
+ <p>Corresponds to "Contracted quantity" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents the {@link LineItem#discount} for {@link Dimension#LINE_ITEM_NAME}.
+ The number is either a percentage or an absolute value depending on
+ {@link LineItem#discountType}.
+ <p>Corresponds to "Discount" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ The cost of booking for a non-CPD {@link Dimension#LINE_ITEM_NAME}.
+ <p>Corresponds to "Booked revenue (exclude CPD)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Company#appliedLabels} as a comma separated list of
+ {@link Label#name} for {@link Dimension#ADVERTISER_NAME}.
+ <p>Corresponds to "Advertiser labels" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Company#appliedLabels} as a comma separated list of
+ {@link Label#id} for {@link Dimension#ADVERTISER_NAME}.
+ <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents the click-through URL for {@link Dimension#CREATIVE_NAME}.
+ <p>Corresponds to "Click-through URL" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents whether a creative is SSL-compliant.
+ <p>Corresponds to "Creative SSL scan result" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents whether a creative's SSL status was overridden.
+ <p>Corresponds to "Creative SSL compliance override" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents a {@link LineItemCreativeAssociation#startDateTime} for a
+ {@link Dimension#LINE_ITEM_NAME} and a {@link Dimension#CREATIVE_NAME}.
+ Includes the date without the time.
+ <p>Corresponds to "Creative start date" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL, SELL_THROUGH, SALES.</p>
+
+
+
+
+
+
+ Represents a {@link LineItemCreativeAssociation#endDateTime} for a
+ {@link Dimension#LINE_ITEM_NAME} and a {@link Dimension#CREATIVE_NAME}.
+ Includes the date without the time.
+ <p>Corresponds to "Creative end date" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL, SELL_THROUGH, SALES.</p>
+
+
+
+
+
+
+ Represents {@link Proposal#startDateTime} for {@link Dimension#PROPOSAL_NAME}.
+ <p>Corresponds to "Proposal start time" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Proposal#endDateTime} for {@link Dimension#PROPOSAL_NAME}.
+ <p>Corresponds to "Proposal end time" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Proposal#creationDateTime} for {@link Dimension#PROPOSAL_NAME}. Can be used
+ for filtering.
+ <p>Corresponds to "Creation time" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents the sold time for {@link Dimension#PROPOSAL_NAME}.
+ <p>Corresponds to "Sold time" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Proposal#isSold} for {@link Dimension#PROPOSAL_NAME}. Can be used for
+ filtering.
+ <p>Corresponds to "Sold" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Proposal#probabilityOfClose} for {@link Dimension#PROPOSAL_NAME}.
+ <p>Corresponds to "Probability of close" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Proposal#status} for {@link Dimension#PROPOSAL_NAME}.
+ This attribute includes post-sold statuses, e.g. DRAFT(SOLD) until v201611.
+ Starting from v201702, it will not include post-sold statuses.
+ Can be used for filtering.
+ <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents archival status for {@link Dimension#PROPOSAL_NAME}, the values are ARCHIVED
+ and NOT_ARCHIVED. Can be used for filtering.
+ <p>Corresponds to "Proposal archival status" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Proposal#currency} for {@link Dimension#PROPOSAL_NAME}.
+ <p>Corresponds to "Currency" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Proposal#exchangeRate} for {@link Dimension#PROPOSAL_NAME}.
+ <p>Corresponds to "Exchange rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Proposal#agencyCommission} for {@link Dimension#PROPOSAL_NAME}.
+ <p>Corresponds to "Agency commission rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Proposal#valueAddedTax} for {@link Dimension#PROPOSAL_NAME}.
+ <p>Corresponds to "VAT rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Proposal#proposalDiscount} for {@link Dimension#PROPOSAL_NAME}.
+ <p>Corresponds to "Proposal discount" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Proposal#advertiserDiscount} for {@link Dimension#PROPOSAL_NAME}.
+ <p>Corresponds to "Advertiser discount" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents the advertiser name of {@link Dimension#PROPOSAL_NAME}.
+ <p>Corresponds to "Advertiser" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents the advertiser id of {@link Dimension#PROPOSAL_NAME}.
+ <p>Corresponds to "Advertiser ID" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents the agency names as a comma separated string for {@link Dimension#PROPOSAL_NAME}.
+ <p>Corresponds to "Agencies" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents the agency ids as a comma separated string for {@link Dimension#PROPOSAL_NAME}.
+ <p>Corresponds to "Agency IDs" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Proposal#poNumber} for {@link Dimension#PROPOSAL_NAME}.
+ <p>Corresponds to "PO number" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents name and email address in the form of name(email) of primary salesperson for
+ {@link Dimension#PROPOSAL_NAME}.
+ <p>Corresponds to "Salesperson" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents name and email addresses in the form of name(email) of secondary salespeople as a
+ comma separated string for {@link Dimension#PROPOSAL_NAME}.
+ <p>Corresponds to "Secondary salespeople" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents name and email address in the form of name(email) of creator for {@link
+ Dimension#PROPOSAL_NAME}.
+ <p>Corresponds to "Creator" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents name and email addresses in the form of name(email) of {@link
+ Proposal#salesPlannerIds} as a comma separated list string for {@link Dimension#PROPOSAL_NAME}.
+ <p>Corresponds to "Sales planners" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Proposal#pricingModel} for {@link Dimension#PROPOSAL_NAME}.
+ <p>Corresponds to "Pricing model" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Proposal#billingSource} for {@link Dimension#PROPOSAL_NAME}.
+ <p>Corresponds to "Proposal billing source" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Proposal#billingCap} for {@link Dimension#PROPOSAL_NAME}.
+ <p>Corresponds to "Proposal caps and rollovers" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Proposal#billingSchedule} for {@link Dimension#PROPOSAL_NAME}.
+ <p>Corresponds to "Proposal billing schedule" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Proposal#appliedTeamIds} as a comma separated list of {@link Team#name}s for
+ {@link Dimension#PROPOSAL_NAME}.
+ <p>Corresponds to "Teams" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents the approval stage for {@link Dimension#PROPOSAL_NAME}.
+ <p>Corresponds to "Approval stage" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents the inventory release date time for {@link Dimension#PROPOSAL_NAME}.
+ <p>Corresponds to "Inventory release time" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Proposal#budget} in local currency for {@link Dimension#PROPOSAL_NAME}.
+ <p>Corresponds to "Budget (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents the remaining budget in local currency for {@link Dimension#PROPOSAL_NAME}.
+ <p>Corresponds to "Remaining budget (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents whether the {@link Proposal#billingBase} is {@link BillingBase#REVENUE}.
+ <p>Corresponds to "Proposal flat fee" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Proposal#isProgrammatic} for {@link Dimension#PROPOSAL_NAME}. Not available
+ as an attribute to report on, but exists as an attribute for filtering using PQL.
+ <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link ProposalLineItem#startDateTime} for
+ {@link Dimension#PROPOSAL_LINE_ITEM_NAME}.
+ <p>Corresponds to "Proposal line item start time" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link ProposalLineItem#endDateTime} for {@link Dimension#PROPOSAL_LINE_ITEM_NAME}.
+ <p>Corresponds to "Proposal line item end time" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link ProposalLineItem#rateType} for {@link Dimension#PROPOSAL_LINE_ITEM_NAME}.
+ Can be used for filtering.
+ <p>Corresponds to "Proposal line item rate type" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents the reservation status of {@link Dimension#PROPOSAL_LINE_ITEM_NAME}. Can be used for
+ filtering.
+ <p>Corresponds to "Reservation status" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link ProposalLineItem#costPerUnit} for {@link Dimension#PROPOSAL_LINE_ITEM_NAME}.
+ <p>Corresponds to "Rate (net)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link ProposalLineItem#costPerUnit} in local currency for
+ {@link Dimension#PROPOSAL_LINE_ITEM_NAME}.
+
+ See {@link #PROPOSAL_LINE_ITEM_COST_PER_UNIT}
+ <p>Can correspond to any of the following in the DFP UI: Rate (local), Rate (net) (local). Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents gross cost per unit for {@link Dimension#PROPOSAL_LINE_ITEM_NAME}.
+ <p>Corresponds to "Rate (gross)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents gross cost per unit in local currency for {@link Dimension#PROPOSAL_LINE_ITEM_NAME}.
+
+ See {@link #PROPOSAL_LINE_ITEM_COST_PER_UNIT_GROSS}
+ <p>Corresponds to "Rate (gross) (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents line item type (if applicable) and line item priority (if applicable) for
+ {@link Dimension#PROPOSAL_LINE_ITEM_NAME}.
+ <p>Corresponds to "Proposal line item type / priority" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents the size of {@link ProposalLineItem#creativePlaceholders}
+ for {@link Dimension#PROPOSAL_LINE_ITEM_NAME}.
+ <p>Corresponds to "Sizes" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents archival status for {@link Dimension#PROPOSAL_LINE_ITEM_NAME}, the values are
+ ARCHIVED and NOT_ARCHIVED. Can be used for filtering.
+ <p>Corresponds to "Proposal line item archival status" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents the product adjustment of {@link Dimension#PROPOSAL_LINE_ITEM_NAME}.
+ <p>Corresponds to "Product adjustment" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link ProposalLineItem#contractedQuantityBuffer} for
+ {@link Dimension#PROPOSAL_LINE_ITEM_NAME}.
+ <p>Corresponds to "Buffer (%)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents the listing rate (net) of {@link Dimension#PROPOSAL_LINE_ITEM_NAME}.
+ <p>Corresponds to "Listing rate (net)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link ProposalLineItem#billingSource} for
+ {@link Dimension#PROPOSAL_LINE_ITEM_NAME}.
+ <p>Corresponds to "Proposal line item billing source" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link ProposalLineItem#billingCap} for {@link Dimension#PROPOSAL_LINE_ITEM_NAME}.
+ <p>Corresponds to "Proposal line item caps and rollovers" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link ProposalLineItem#billingSchedule} for
+ {@link Dimension#PROPOSAL_LINE_ITEM_NAME}.
+ <p>Corresponds to "Proposal line item billing schedule" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Goal#units} of {@link ProposalLineItem#goal} for {@link
+ Dimension#PROPOSAL_LINE_ITEM_NAME} The attribute is available only if {@link
+ ProposalLineItem#lineItemType} is of type {@link LineItemType#SPONSORSHIP}, {@link
+ LineItemType#HOUSE}, {@link LineItemType#NETWORK}, or {@link LineItemType#BUMPER}.
+ <p>Corresponds to "Goal (%)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link ProposalLineItem#costAdjustment} for {@link
+ Dimension#PROPOSAL_LINE_ITEM_NAME}.
+ <p>Corresponds to "Cost adjustment" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents the {@link ProposalLineItem#notes comments} for {@link
+ Dimension#PROPOSAL_LINE_ITEM_NAME}.
+ <p>Corresponds to "Proposal line item comments" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents the monthly reconciliation status of the proposal line item for
+ {@link Dimension#PROPOSAL_LINE_ITEM_NAME} and {@link Dimension#MONTH_YEAR}.
+ <p>Corresponds to "Proposal line item reconciliation status" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL, PARTNER_FINANCE.</p>
+
+
+
+
+
+
+ Represents the monthly last reconciliation date time of the proposal line item for
+ {@link Dimension#PROPOSAL_LINE_ITEM_NAME} and {@link Dimension#MONTH_YEAR}.
+ <p>Corresponds to "Proposal line item last reconciliation time" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL, PARTNER_FINANCE.</p>
+
+
+
+
+
+
+ Represents whether the {@link ProposalLineItem#billingBase} is {@link BillingBase#REVENUE}.
+ <p>Corresponds to "Proposal line item flat fee" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents the corresponding product package item's archival status of
+ {@link Dimension#PROPOSAL_LINE_ITEM_NAME}. Not available as an attribute
+ to report on, but exists as an attribute for filtering using PQL.
+ <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents the {@link ProposalLineItem#lineItemType} of
+ {@link Dimension#PROPOSAL_LINE_ITEM_NAME}. Only used for filtering.
+ <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link ProductTemplate#rateType} for {@link Dimension#PRODUCT_TEMPLATE_NAME}.
+ <p>Corresponds to "Product template rate type" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link ProductTemplate#status} for {@link Dimension#PRODUCT_TEMPLATE_NAME}.
+ <p>Corresponds to "Product template status" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents the line item type (if applicable) and line item priority
+ (if applicable) of {@link Dimension#PRODUCT_TEMPLATE_NAME}.
+ <p>Corresponds to "Product template type / priority" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link ProductTemplate#productType} for {@link Dimension#PRODUCT_TEMPLATE_NAME}.
+ <p>Corresponds to "Product template product type" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link ProductTemplate#description} for {@link Dimension#PRODUCT_TEMPLATE_NAME}.
+ <p>Corresponds to "Description" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents the product template's name of {@link Dimension#PRODUCT_NAME}.
+ <p>Corresponds to "Product template name" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Product#rateType} for {@link Dimension#PRODUCT_NAME}.
+ <p>Corresponds to "Product rate type" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Product#status} for {@link Dimension#PRODUCT_NAME}.
+ <p>Corresponds to "Product status" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents the line item type (if applicable) and line item priority
+ (if applicable) of {@link Dimension#PRODUCT_NAME}.
+ <p>Corresponds to "Product type / priority" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents the product type of {@link Dimension#PRODUCT_NAME}.
+ <p>Corresponds to "Product product type" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Product#notes} for {@link Dimension#PRODUCT_NAME}.
+ <p>Corresponds to "Product notes" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Product#creativePlaceholders} for {@link Dimension#PRODUCT_NAME}.
+ <p>Corresponds to "Inventory sizes" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents the {@link Dimension#PRODUCT_NAME}'s rate in a {@link Dimension#RATE_CARD_NAME}.
+ <p>Corresponds to "Product rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents the {@link Dimension#PRODUCT_NAME}'s rate in a {@link Dimension#RATE_CARD_NAME}
+ and {@link Dimension#PRODUCT_PACKAGE_NAME}.
+ <p>Corresponds to "Packaged product rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents the {@link Company#type} of {@link Dimension#PROPOSAL_AGENCY_NAME}.
+ <p>Corresponds to "Proposal agency type" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents the {@link Company#creditStatus} of {@link Dimension#PROPOSAL_AGENCY_NAME}.
+ <p>Corresponds to "Proposal agency credit status" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Company#externalId} for {@link Dimension#PROPOSAL_AGENCY_NAME}.
+ <p>Corresponds to "External agency ID" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Company#comment} for {@link Dimension#PROPOSAL_AGENCY_NAME}.
+ <p>Corresponds to "Proposal agency comment" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents the {@link Dimension#ALL_SALESPEOPLE_NAME}'s contribution to a {@link
+ Dimension#PROPOSAL_NAME}. This is different from {@link #SALESPERSON_PROPOSAL_CONTRIBUTION} as
+ this will include both primary and secondary salespeople.
+ <p>Corresponds to "Salespeople proposal contribution" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL, SELL_THROUGH.</p>
+
+
+
+
+
+
+ Represents the {@link Dimension#SALESPERSON_NAME}'s contribution to a {@link
+ Dimension#PROPOSAL_NAME}.
+
+ <p>See {@link #SALESPERSON_PROPOSAL_CONTRIBUTION}.
+ <p>Corresponds to "Salesperson proposal contribution" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link ProductPackage#notes} for {@link Dimension#PRODUCT_PACKAGE_NAME}.
+ <p>Corresponds to "Product package notes" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents the products as a comma separated list of name for
+ {@link Dimension#PRODUCT_PACKAGE_NAME}.
+ <p>Corresponds to "Product package items" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link ProductPackage#status} for {@link Dimension#PRODUCT_PACKAGE_NAME}.
+ <p>Corresponds to "Product package status" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Package#comments} for {@link Dimension#PACKAGE_NAME}.
+ <p>Corresponds to "Package comments" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Package#startDateTime} for {@Dimension#PACKAGE_NAME}.
+ <p>Corresponds to "Package start time" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link Package#endDateTime} for {@Dimension#PACKAGE_NAME}.
+ <p>Corresponds to "Package end time" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents the {@link CmsContent#displayName} within the first element of
+ {@link Content#cmsContent} for {@link Dimension#CONTENT_NAME}.
+ <p>Corresponds to "Content source name" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents the {@link CmsContent#cmsContentId} within the first element of
+ {@link Content#cmsContent} for {@link Dimension#CONTENT_NAME}.
+ <p>Corresponds to "ID of the video in the content source" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+ Represents {@link AdUnit#adUnitCode} for {@link Dimension#AD_UNIT_NAME}.
+ <p>Corresponds to "Ad unit code" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p>
+
+
+
+
+
+
+
+
+ The file formats available for creating the report.
+
+
+
+
+
+
+ The report file is generated as a list of Tab Separated Values.
+
+
+
+
+
+
+ The report file is generated as a list of tab-separated values for Excel.
+
+
+
+
+
+
+ The report file is generated as a list of Comma Separated Values,
+ to be used with automated machine processing.
+ <p>
+ <ul>
+ <li>There is no pretty printing for the output, and no total row.</li>
+ <li>Column headers are the qualified name e.g. "Dimension.ORDER_NAME".</li>
+ <li>Network currency Monetary amounts are represented as micros in the
+ {@link Network#currencyCode currency of the network}.</li>
+ <li>Starting from v201705, local currency Monetary amounts are represented
+ as currency symbol + ' ' + micros. </li>
+ <li>Dates are formatted according to the ISO 8601 standard YYYY-MM-DD</li>
+ <li>DateTimes are formatted according to the ISO 8601 standard
+ YYYY-MM-DDThh:mm:ss[+-]hh:mm</li>
+ </ul>
+
+
+
+
+
+
+ The report file is generated as XML.
+
+
+
+
+
+
+ The report file is generated as an Office Open XML spreadsheet
+ designed for Excel 2007+.
+
+
+
+
+
+
+
+
+
+
+ A feature is being used that is not enabled on the current network.
+
+
+
+
+
+
+ The value returned if the actual value is not exposed by the requested API version.
+
+
+
+
+
+
+
+
+ The single reason for the internal API error.
+
+
+
+
+
+
+ API encountered an unexpected internal error.
+
+
+
+
+
+
+ A temporary error occurred during the request. Please retry.
+
+
+
+
+
+
+ The cause of the error is not known or only defined in newer versions.
+
+
+
+
+
+
+ The API is currently unavailable for a planned downtime.
+
+
+
+
+
+
+ Mutate succeeded but server was unable to build response. Client should not retry mutate.
+
+
+
+
+
+
+
+
+ The reasons for the target error.
+
+
+
+
+
+
+ Assuming that a method will not have more than 3 arguments, if it does,
+ return NULL
+
+
+
+
+
+
+
+
+
+ The value returned if the actual value is not exposed by the requested API version.
+
+
+
+
+
+
+
+
+ The reasons for the target error.
+
+
+
+
+
+
+ Indicates an error in parsing an attribute.
+
+
+
+
+
+
+ The value returned if the actual value is not exposed by the requested API version.
+
+
+
+
+
+
+
+
+ Describes reasons for permission errors.
+
+
+
+
+
+
+ User does not have the required permission for the request.
+
+
+
+
+
+
+ The value returned if the actual value is not exposed by the requested API version.
+
+
+
+
+
+
+
+
+ The reasons for the target error.
+
+
+
+
+
+
+ Indicates that there was an error executing the PQL.
+
+
+
+
+
+
+ The value returned if the actual value is not exposed by the requested API version.
+
+
+
+
+
+
+
+
+ The reasons for the target error.
+
+
+
+
+
+
+ Indicates that there was a PQL syntax error.
+
+
+
+
+
+
+ The value returned if the actual value is not exposed by the requested API version.
+
+
+
+
+
+
+
+
+
+
+ The number of requests made per second is too high and has exceeded the
+ allowable limit. The recommended approach to handle this error is to wait
+ about 5 seconds and then retry the request. Note that this does not
+ guarantee the request will succeed. If it fails again, try increasing the
+ wait time.
+ <p>Another way to mitigate this error is to limit requests to 2 per second for
+ Small Business networks, or 8 per second for Premium networks. Once again
+ this does not guarantee that every request will succeed, but may help
+ reduce the number of times you receive this error.
+
+
+
+
+
+
+ The value returned if the actual value is not exposed by the requested API version.
+
+
+
+
+
+
+ This user has exceeded the allowed number of new report requests per hour
+ (this includes both reports run via the UI and reports
+ run via {@link ReportService#runReportJob}).
+ The recommended approach to handle this error is to wait about 10 minutes
+ and then retry the request. Note that this does not guarantee the request
+ will succeed. If it fails again, try increasing the wait time.
+ <p>Another way to mitigate this error is to limit the number of new report
+ requests to 250 per hour per user. Once again, this does not guarantee that
+ every request will succeed, but may help reduce the number of times you
+ receive this error.
+
+
+
+
+
+
+
+
+
+
+ Default {@code ReportError} when the reason is not among any already
+ defined.
+
+
+
+
+
+
+ User does not have permission to access the report.
+
+
+
+
+
+
+ User does not have permission to view one or more {@link Dimension}.
+
+
+
+
+
+
+ User has no permission to view one or more attributes.
+
+
+
+
+
+
+ User does not have permission to view one or more {@link Column}.
+
+
+
+
+
+
+ The user has exceeded the limit on the number of reports that can be run
+ concurrently. The current limit is 30 per user.
+
+
+
+
+
+
+ The report query exceeds the maximum allowed number of characters.
+
+
+
+
+
+
+ Invalid report job state for the given operation.
+
+
+
+
+
+
+ Invalid {@link Dimension} objects specified.
+
+
+
+
+
+
+ The attribute ID(s) are not valid.
+
+
+
+
+
+
+ The API error when running the report with {@link ContentHierarchyDimension}. There are three
+ reasons for this error.
+ <ol>
+ <li>{@link ReportQuery#dimensions} contains {@link Dimension#CONTENT_HIERARCHY}, but
+ {@link ReportQuery#contentMetadataHierarchyCustomTargetingKeyIds} is empty.</li>
+
+ <li>{@link ReportQuery#contentMetadataHierarchyCustomTargetingKeyIds} is non-empty, but
+ {@link ReportQuery#dimensions} does not contain {@link Dimension#CONTENT_HIERARCHY}.</li>
+
+ <li>The {@link ReportQuery#contentMetadataKeyHierarchyCustomTargetingKeyIds} specified along
+ with the {@link Dimension#CONTENT_HIERARCHY} are not valid, i.e., these IDs are not defined
+ in the content hierarchy by the publisher.</li>
+ </ol>
+
+
+
+
+
+
+ Invalid {@link Column} objects specified.
+
+
+
+
+
+
+ Invalid {@link DimensionFilter} objects specified.
+
+
+
+
+
+
+ Invalid date.
+
+
+
+
+
+
+ The start date for running the report should not be later than the end
+ date.
+
+
+
+
+
+
+ The start date for running the report should not be more than
+ three years before now.
+
+
+
+
+
+
+ The list of {@link Dimension} and {@link Column} objects cannot be empty.
+
+
+
+
+
+
+ Attribute has to be selected in combination with dimensions.
+
+
+
+
+
+
+ The provided report violates one or more constraints, which govern incompatibilities and
+ requirements between different report properties. Some reasons for constraint violations
+ include:
+ <ul>
+ <li> Not all {@link Column} objects requested are supported for the given set
+ of {@link Dimension} objects.
+ <li> The report's date range is not compatible with the given set of {@link Column}
+ objects.
+ <li> The report's {@link TimeZoneType} is not compatible with the given set of
+ {@link Column} and {@link Dimension} objects (version 201802 and later).
+ <li> The report's currency is not compatible with the given set of {@link Column} objects
+ (version 201802 and later).
+ </ul>
+
+
+
+
+
+
+ Failed to store/cache a report.
+
+
+
+
+
+
+ The requested report does not exist.
+
+
+
+
+
+
+ User has no permission to view in another network.
+
+
+
+
+
+
+ The value returned if the actual value is not exposed by the requested API version.
+
+
+
+
+
+
+
+
+ Represents the status of a {@link ReportJob} running on the server.
+
+
+
+
+
+
+ The {@link ReportJob} has completed successfully and is ready to download.
+
+
+
+
+
+
+ The {@link ReportJob} is still being executed.
+
+
+
+
+
+
+ The {@link ReportJob} has failed to run to completion.
+
+
+
+
+
+
+
+
+
+
+ A required collection is missing.
+
+
+
+
+
+
+ Collection size is too large.
+
+
+
+
+
+
+ Collection size is too small.
+
+
+
+
+
+
+ The value returned if the actual value is not exposed by the requested API version.
+
+
+
+
+
+
+
+
+ The reasons for the target error.
+
+
+
+
+
+
+ Missing required field.
+
+
+
+
+
+
+
+
+ Describes reasons for server errors
+
+
+
+
+
+
+ Indicates that an unexpected error occured.
+
+
+
+
+
+
+ Indicates that the server is currently experiencing a high load. Please
+ wait and try your request again.
+
+
+
+
+
+
+ The value returned if the actual value is not exposed by the requested API version.
+
+
+
+
+
+
+
+
+
+
+ A bind variable has not been bound to a value.
+
+
+
+
+
+
+ The value returned if the actual value is not exposed by the requested API version.
+
+
+
+
+
+
+
+
+ The reasons for the target error.
+
+
+
+
+
+
+
+ The input string value contains disallowed characters.
+
+
+
+
+
+
+ The input string value is invalid for the associated field.
+
+
+
+
+
+
+
+
+
+
+
+
+ The value returned if the actual value is not exposed by the requested API version.
+
+
+
+
+
+
+
+
+ Enumerates all allowed time zones that can be used in reports. Note that some time zones are only
+ compatible with specific fields.
+
+
+
+
+
+
+ The value returned if the actual value is not exposed by the requested API version.
+
+
+
+
+
+
+ Use the proposal or proposal line item time zone. This time zone is only compatible with sales
+ metrics and attributes.
+
+ <p>For example, if
+ {@link com.google.ads.publisher.api.service.reports.Column#SALES_CONTRACT_CONTRACTED_CLICKS} is
+ included in a report with this flag set to {@code true}, then it will be calculated using the
+ {@link ProposalLineItem#timeZoneId} of the proposal line item the metric is for. If
+ {@link com.google.ads.publisher.api.service.reports.DimensionAttribute#PROPOSAL_CREATION_DATE_TIME}
+ is included in a report with this flag set to {@code true}, then a proposal's creation date
+ time will be formatted in {@link Proposal#timeZoneId} of that proposal.
+
+
+
+
+
+
+ Use the publisher's time zone. For DFP reports, this time zone is compatible with all
+ metrics. For Ad Exchange reports, this time zone is not compatible with "Bids" and "Deals"
+ metrics.
+
+ <p><b>Note:</b> if your report includes "time unit" dimensions, only the DFP "time unit"
+ dimensions are compatible with this timezone, e.g.:
+ <ul>
+ <li> {@link com.google.ads.publisher.api.service.reports.Dimension.DATE}
+ <li> {@link com.google.ads.publisher.api.service.reports.Dimension.WEEK}
+ <li> {@link com.google.ads.publisher.api.service.reports.Dimension.MONTH_AND_YEAR}
+ </ul>
+
+
+
+
+
+
+ Use the Ad Exchange time zone (Pacific Time Zone). This time zone is only compatible with
+ Ad Exchange metrics.
+
+ <p><b>Note:</b> if your report includes "time unit" dimensions, only the Ad Exchange
+ "time unit" dimensions are compatible with this timezone, e.g.:
+ <ul>
+ <li> {@link com.google.ads.publisher.api.service.reports.Dimension.AD_EXCHANGE_DATE}
+ <li> {@link com.google.ads.publisher.api.service.reports.Dimension.AD_EXCHANGE_WEEK}
+ <li> {@link com.google.ads.publisher.api.service.reports.Dimension.AD_EXCHANGE_MONTH}
+ </ul>
+
+
+
+
+
+
+
+
+ Returns the URL at which the report file can be downloaded.
+ <p>
+ The report will be generated as a gzip archive, containing the report file itself.
+
+ @param reportJobId the ID of the {@link ReportJob}
+ @param exportFormat the {@link ExportFormat} for the report file
+ @return the URL for report file download
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ A fault element of type ApiException.
+
+
+
+
+
+
+ Returns the URL at which the report file can be downloaded, and allows for customization
+ of the downloaded report.
+ <p>
+ By default, the report will be generated as a gzip archive, containing the report file itself.
+ This can be changed by setting {@link ReportDownloadOptions#useGzipCompression} to false.
+
+ @param reportJobId the ID of the {@link ReportJob}
+ @param reportDownloadOptions the {@link ReportDownloadOptions} for the request
+ @return the URL for report file download
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Returns the {@link ReportJobStatus} of the report job with the specified ID.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Retrieves a page of the saved queries either created by or shared with the current user. Each
+ {@link SavedQuery} in the page, if it is compatible with the current API version, will
+ contain a {@link ReportQuery} object which can be optionally modified and used to create a
+ {@link ReportJob}. This can then be passed to {@link ReportService#runReportJob}.
+ The following fields are supported for filtering:
+
+ <table>
+ <tr>
+ <th scope="col">PQL Property</th> <th scope="col">Object Property</th>
+ </tr>
+ <tr>
+ <td>{@code id}</td>
+ <td>{@link SavedQuery#id}</td>
+ </tr>
+ <tr>
+ <td>{@code name}</td>
+ <td>{@link SavedQuery#name}</td>
+ </tr>
+ </table>
+
+ @param filterStatement a Publisher Query Language statement used to filter which saved queries
+ should be returned.
+ @return a {@link SavedQueryPage} that contains all {@link SavedQuery} instances which satisfy
+ the given statement.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Initiates the execution of a {@link ReportQuery} on the server.
+
+ <p>The following fields are required:
+ <ul>
+ <li>{@link ReportJob#reportQuery}</li>
+ </ul>
+
+ @param reportJob the report job to run
+ @return the report job with its ID filled in
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Provides methods for executing a {@link ReportJob} and retrieving performance
+ and statistics about ad campaigns, networks, inventory and sales.
+ <p>Follow the steps outlined below:</p>
+ <p>
+ <ul>
+ <li>Create the {@code ReportJob} object by invoking
+ {@link ReportService#runReportJob}.</li>
+ <li>Poll the {@code ReportJob} object using
+ {@link ReportService#getReportJob}.</li>
+ <li>Continue to poll the {@code ReportJob} object until the
+ {@link ReportJob#reportJobStatus} field is equal to
+ {@link ReportJobStatus#COMPLETED} or {@link ReportJobStatus#FAILED}.</li>
+ <li>If successful, fetch the URL for downloading the report by invoking
+ {@link ReportService#getReportDownloadURL}.</li>
+ </ul>
+ </p>
+
+ <h4>Test network behavior</h4>
+
+ <p>
+ The networks created using {@link NetworkService#makeTestNetwork} are unable
+ to provide reports that would be comparable to the production environment
+ because reports require traffic history.
+ In the test networks, reports will consistently return no data for all reports.
+ </p>
+
+
+
+ Returns the URL at which the report file can be downloaded.
+ <p>
+ The report will be generated as a gzip archive, containing the report file itself.
+
+ @param reportJobId the ID of the {@link ReportJob}
+ @param exportFormat the {@link ExportFormat} for the report file
+ @return the URL for report file download
+
+
+
+
+
+
+
+ Returns the URL at which the report file can be downloaded, and allows for customization
+ of the downloaded report.
+ <p>
+ By default, the report will be generated as a gzip archive, containing the report file itself.
+ This can be changed by setting {@link ReportDownloadOptions#useGzipCompression} to false.
+
+ @param reportJobId the ID of the {@link ReportJob}
+ @param reportDownloadOptions the {@link ReportDownloadOptions} for the request
+ @return the URL for report file download
+
+
+
+
+
+
+
+ Returns the {@link ReportJobStatus} of the report job with the specified ID.
+
+
+
+
+
+
+
+ Retrieves a page of the saved queries either created by or shared with the current user. Each
+ {@link SavedQuery} in the page, if it is compatible with the current API version, will
+ contain a {@link ReportQuery} object which can be optionally modified and used to create a
+ {@link ReportJob}. This can then be passed to {@link ReportService#runReportJob}.
+ The following fields are supported for filtering:
+
+ <table>
+ <tr>
+ <th scope="col">PQL Property</th> <th scope="col">Object Property</th>
+ </tr>
+ <tr>
+ <td>{@code id}</td>
+ <td>{@link SavedQuery#id}</td>
+ </tr>
+ <tr>
+ <td>{@code name}</td>
+ <td>{@link SavedQuery#name}</td>
+ </tr>
+ </table>
+
+ @param filterStatement a Publisher Query Language statement used to filter which saved queries
+ should be returned.
+ @return a {@link SavedQueryPage} that contains all {@link SavedQuery} instances which satisfy
+ the given statement.
+
+
+
+
+
+
+
+ Initiates the execution of a {@link ReportQuery} on the server.
+
+ <p>The following fields are required:
+ <ul>
+ <li>{@link ReportJob#reportQuery}</li>
+ </ul>
+
+ @param reportJob the report job to run
+ @return the report job with its ID filled in
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tests/test_data/adwords_googleads.yaml b/tests/test_data/adwords_googleads.yaml
new file mode 100644
index 00000000..31fc1b92
--- /dev/null
+++ b/tests/test_data/adwords_googleads.yaml
@@ -0,0 +1,5 @@
+adwords:
+ developer_token: developer_token
+ client_id: client_id
+ client_secret: client_secret
+ refresh_token: refresh_token
diff --git a/tests/test_data/adwords_report_definition.xsd b/tests/test_data/adwords_report_definition.xsd
new file mode 100644
index 00000000..c707f2ae
--- /dev/null
+++ b/tests/test_data/adwords_report_definition.xsd
@@ -0,0 +1,155 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tests/test_data/adwords_report_post_body.txt b/tests/test_data/adwords_report_post_body.txt
new file mode 100644
index 00000000..c4afcd1f
--- /dev/null
+++ b/tests/test_data/adwords_report_post_body.txt
@@ -0,0 +1 @@
+__rdxml=%3Ctns%3AreportDefinition+xmlns%3Atns%3D%22https%3A%2F%2Fadwords.google.com%2Fapi%2Fadwords%2Fcm%2F{VERSION}%22%3E%0A+++%3Ctns%3Aselector%3E%0A++++++%3Ctns%3Afields%3ECampaignId%3C%2Ftns%3Afields%3E%0A++++++%3Ctns%3Afields%3EAdGroupId%3C%2Ftns%3Afields%3E%0A++++++%3Ctns%3Afields%3EId%3C%2Ftns%3Afields%3E%0A++++++%3Ctns%3Afields%3ECriteriaType%3C%2Ftns%3Afields%3E%0A++++++%3Ctns%3Afields%3ECriteria%3C%2Ftns%3Afields%3E%0A++++++%3Ctns%3Afields%3EFinalUrls%3C%2Ftns%3Afields%3E%0A++++++%3Ctns%3Afields%3EImpressions%3C%2Ftns%3Afields%3E%0A++++++%3Ctns%3Afields%3EClicks%3C%2Ftns%3Afields%3E%0A++++++%3Ctns%3Afields%3ECost%3C%2Ftns%3Afields%3E%0A+++%3C%2Ftns%3Aselector%3E%0A+++%3Ctns%3AreportName%3ELast+7+days+CRITERIA_PERFORMANCE_REPORT%3C%2Ftns%3AreportName%3E%0A+++%3Ctns%3AreportType%3ECRITERIA_PERFORMANCE_REPORT%3C%2Ftns%3AreportType%3E%0A+++%3Ctns%3AdateRangeType%3ELAST_7_DAYS%3C%2Ftns%3AdateRangeType%3E%0A+++%3Ctns%3AdownloadFormat%3ECSV%3C%2Ftns%3AdownloadFormat%3E%0A%3C%2Ftns%3AreportDefinition%3E
\ No newline at end of file
diff --git a/tests/test_data/adwords_report_post_body_no_formatting.txt b/tests/test_data/adwords_report_post_body_no_formatting.txt
new file mode 100644
index 00000000..f85dd7b7
--- /dev/null
+++ b/tests/test_data/adwords_report_post_body_no_formatting.txt
@@ -0,0 +1 @@
+__rdxml=%3Ctns%3AreportDefinition+xmlns%3Atns%3D%22https%3A%2F%2Fadwords.google.com%2Fapi%2Fadwords%2Fcm%2F{VERSION}%22%3E%3Ctns%3Aselector%3E%3Ctns%3Afields%3ECampaignId%3C%2Ftns%3Afields%3E%3Ctns%3Afields%3EAdGroupId%3C%2Ftns%3Afields%3E%3Ctns%3Afields%3EId%3C%2Ftns%3Afields%3E%3Ctns%3Afields%3ECriteriaType%3C%2Ftns%3Afields%3E%3Ctns%3Afields%3ECriteria%3C%2Ftns%3Afields%3E%3Ctns%3Afields%3EFinalUrls%3C%2Ftns%3Afields%3E%3Ctns%3Afields%3EImpressions%3C%2Ftns%3Afields%3E%3Ctns%3Afields%3EClicks%3C%2Ftns%3Afields%3E%3Ctns%3Afields%3ECost%3C%2Ftns%3Afields%3E%3C%2Ftns%3Aselector%3E%3Ctns%3AreportName%3ELast+7+days+CRITERIA_PERFORMANCE_REPORT%3C%2Ftns%3AreportName%3E%3Ctns%3AreportType%3ECRITERIA_PERFORMANCE_REPORT%3C%2Ftns%3AreportType%3E%3Ctns%3AdateRangeType%3ELAST_7_DAYS%3C%2Ftns%3AdateRangeType%3E%3Ctns%3AdownloadFormat%3ECSV%3C%2Ftns%3AdownloadFormat%3E%3C%2Ftns%3AreportDefinition%3E
\ No newline at end of file
diff --git a/tests/test_data/batch_job_util_budget_template.txt b/tests/test_data/batch_job_util_budget_template.txt
new file mode 100644
index 00000000..e0e48f3a
--- /dev/null
+++ b/tests/test_data/batch_job_util_budget_template.txt
@@ -0,0 +1,6 @@
+ %s
+ %s
+
+ %s
+
+ %s
\ No newline at end of file
diff --git a/tests/test_data/batch_job_util_campaign_criterion_template.txt b/tests/test_data/batch_job_util_campaign_criterion_template.txt
new file mode 100644
index 00000000..62d743ab
--- /dev/null
+++ b/tests/test_data/batch_job_util_campaign_criterion_template.txt
@@ -0,0 +1,7 @@
+ %s
+ %s
+
+ %s
+ %s
+ %s
+
diff --git a/tests/test_data/batch_job_util_campaign_label_template.txt b/tests/test_data/batch_job_util_campaign_label_template.txt
new file mode 100644
index 00000000..88eff6ba
--- /dev/null
+++ b/tests/test_data/batch_job_util_campaign_label_template.txt
@@ -0,0 +1,2 @@
+ %s
+ %s
\ No newline at end of file
diff --git a/tests/test_data/batch_job_util_invalid_request.txt b/tests/test_data/batch_job_util_invalid_request.txt
new file mode 100644
index 00000000..9bc8b869
--- /dev/null
+++ b/tests/test_data/batch_job_util_invalid_request.txt
@@ -0,0 +1,9 @@
+
+
+
+ Die monster. You don't belong in this world!
+
+
+ What is a man? A miserable little pile of secrets. But enough talk... Have at you!
+
+
\ No newline at end of file
diff --git a/tests/test_data/batch_job_util_not_request.txt b/tests/test_data/batch_job_util_not_request.txt
new file mode 100644
index 00000000..b45ef6fe
--- /dev/null
+++ b/tests/test_data/batch_job_util_not_request.txt
@@ -0,0 +1 @@
+Hello, World!
\ No newline at end of file
diff --git a/tests/test_data/batch_job_util_operations_template.txt b/tests/test_data/batch_job_util_operations_template.txt
new file mode 100644
index 00000000..f31c7b83
--- /dev/null
+++ b/tests/test_data/batch_job_util_operations_template.txt
@@ -0,0 +1,7 @@
+
+ %s
+ %s
+
+%s
+
+
\ No newline at end of file
diff --git a/tests/test_data/batch_job_util_raw_request_template.txt b/tests/test_data/batch_job_util_raw_request_template.txt
new file mode 100644
index 00000000..56a88638
--- /dev/null
+++ b/tests/test_data/batch_job_util_raw_request_template.txt
@@ -0,0 +1,17 @@
+
+
+
+
+ 000-000-0000
+ xxxxxxxxxxxxxxxxxxxx
+ notarealemail@fake.com (AwApi-Python, googleads/3.8.0, Python/3.6.7)
+ false
+ false
+
+
+
+
+%s
+
+
+
\ No newline at end of file
diff --git a/tests/test_data/batch_job_util_response_template.txt b/tests/test_data/batch_job_util_response_template.txt
new file mode 100644
index 00000000..4ccd1d1e
--- /dev/null
+++ b/tests/test_data/batch_job_util_response_template.txt
@@ -0,0 +1 @@
+410230034Batch budget #c776b6f1-5db6-47fc-96ef-1208edb6d898Money50000000STANDARDtrueENABLED0%s%s%s%s%s%s%s%sMoney%s%s%sENABLED%sManualCpcBiddingSchemefalse1
\ No newline at end of file
diff --git a/tests/test_data/batch_job_util_upload_template.txt b/tests/test_data/batch_job_util_upload_template.txt
new file mode 100644
index 00000000..61301f64
--- /dev/null
+++ b/tests/test_data/batch_job_util_upload_template.txt
@@ -0,0 +1,5 @@
+
+
+%s
+
\ No newline at end of file
diff --git a/tests/test_data/compact_fault_response_envelope.txt b/tests/test_data/compact_fault_response_envelope.txt
new file mode 100644
index 00000000..5f1d1e11
--- /dev/null
+++ b/tests/test_data/compact_fault_response_envelope.txt
@@ -0,0 +1,8 @@
+
+
+
+ soap:Client
+ Unmarshalling Error: For input string: "INSERT_ADVERTISER_COMPANY_ID_HERE"
+
+
+
\ No newline at end of file
diff --git a/tests/test_data/empty_fault_response_envelope.txt b/tests/test_data/empty_fault_response_envelope.txt
new file mode 100644
index 00000000..de942d40
--- /dev/null
+++ b/tests/test_data/empty_fault_response_envelope.txt
@@ -0,0 +1,19 @@
+
+
+
+ 644a8c6efd398cf8643c29ff68fe574e
+ 22
+
+
+
+
+ soap:Server
+ [AuthenticationError.NETWORK_CODE_REQUIRED @ ]
+
+
+ An error message without errors sibling tags
+
+
+
+
+
\ No newline at end of file
diff --git a/tests/test_data/fault_response_envelope.txt b/tests/test_data/fault_response_envelope.txt
new file mode 100644
index 00000000..4e2624ce
--- /dev/null
+++ b/tests/test_data/fault_response_envelope.txt
@@ -0,0 +1,25 @@
+
+
+
+ 644a8c6efd398cf8643c29ff68fe574e
+ 22
+
+
+
+
+ soap:Server
+ [AuthenticationError.NETWORK_CODE_REQUIRED @ ]
+
+
+ [AuthenticationError.NETWORK_CODE_REQUIRED @ ]
+
+
+
+ AuthenticationError.NETWORK_CODE_REQUIRED
+ NETWORK_CODE_REQUIRED
+
+
+
+
+
+
\ No newline at end of file
diff --git a/tests/test_data/gzip_response.bin b/tests/test_data/gzip_response.bin
new file mode 100644
index 00000000..567068ab
Binary files /dev/null and b/tests/test_data/gzip_response.bin differ
diff --git a/tests/test_data/multi_errors_fault_response_envelope.txt b/tests/test_data/multi_errors_fault_response_envelope.txt
new file mode 100644
index 00000000..007df960
--- /dev/null
+++ b/tests/test_data/multi_errors_fault_response_envelope.txt
@@ -0,0 +1,31 @@
+
+
+
+ 644a8c6efd398cf8643c29ff68fe574e
+ 22
+
+
+
+
+ soap:Server
+ [Error 1, Error 2]
+
+
+ Multiple errors occurred
+
+
+
+ ERROR_1
+ NETWORK_CODE_REQUIRED
+
+
+
+
+ ERROR_2
+ NETWORK_CODE_REQUIRED
+
+
+
+
+
+
\ No newline at end of file
diff --git a/tests/test_data/request_envelope_template.txt b/tests/test_data/request_envelope_template.txt
new file mode 100644
index 00000000..37e84386
--- /dev/null
+++ b/tests/test_data/request_envelope_template.txt
@@ -0,0 +1,27 @@
+
+
+
+
+ xxx-yyy-zzzz
+ %s
+ testing!
+ false
+ false
+
+
+
+
+
+ ADD
+
+ Test Budget #123456
+
+ 50000000
+
+ STANDARD
+ true
+
+
+
+
+
\ No newline at end of file
diff --git a/tests/test_data/test.crt b/tests/test_data/test.crt
new file mode 100644
index 00000000..f87867fc
--- /dev/null
+++ b/tests/test_data/test.crt
@@ -0,0 +1,18 @@
+-----BEGIN CERTIFICATE-----
+MIIC/DCCAmWgAwIBAgIJAI3wDXTv4zWcMA0GCSqGSIb3DQEBBQUAMIGWMQswCQYD
+VQQGEwJVUzELMAkGA1UECAwCTlkxETAPBgNVBAcMCE5ldyBZb3JrMQ8wDQYDVQQK
+DAZHb29nbGUxIDAeBgNVBAsMF0FkcyBEZXZlbG9wZXIgUmVsYXRpb25zMQwwCgYD
+VQQDDANNVFMxJjAkBgkqhkiG9w0BCQEWF21zYW5pc2NhbGNoaUBnb29nbGUuY29t
+MB4XDTE3MDkxODEzNDgxMVoXDTE4MDkxODEzNDgxMVowgZYxCzAJBgNVBAYTAlVT
+MQswCQYDVQQIDAJOWTERMA8GA1UEBwwITmV3IFlvcmsxDzANBgNVBAoMBkdvb2ds
+ZTEgMB4GA1UECwwXQWRzIERldmVsb3BlciBSZWxhdGlvbnMxDDAKBgNVBAMMA01U
+UzEmMCQGCSqGSIb3DQEJARYXbXNhbmlzY2FsY2hpQGdvb2dsZS5jb20wgZ8wDQYJ
+KoZIhvcNAQEBBQADgY0AMIGJAoGBANFRqR3lsWEl7EaIIIWj9m6/1wiTu0SHsgfd
+RIu+RieqkxRS2Gvnv8PIePb3P2QhtCPj6LjGQc+RB4XccyILKhK6T8cCUhEFB7F3
+JCrwJlJjShmPijSPPFyrZpj8xT/QGMQzrpxi/Qy/+1x7LG6tPHis5Fnhyzqu7i93
+6AlBzBAfAgMBAAGjUDBOMB0GA1UdDgQWBBQln01dzl4gpE6EEcbbavKiYK/6sTAf
+BgNVHSMEGDAWgBQln01dzl4gpE6EEcbbavKiYK/6sTAMBgNVHRMEBTADAQH/MA0G
+CSqGSIb3DQEBBQUAA4GBAAFr5vsQXMSbiFzfdPmbkQF2J+jtvXQId3zBJF4h4ZVq
+VMN9Rw4+zZVq8KUf77y6z0wzdFDU4BRLPI9hEKdik2qf7kyFoNnG3JqYprW9BbCi
+efh5JhiR7PpLsvqvr5x8Yv1tOe1CHKASCRlKEu79YuxQpx3mYG7N6qbFhJPsfpHY
+-----END CERTIFICATE-----
diff --git a/tests/test_data/traffic_estimator_service.xml b/tests/test_data/traffic_estimator_service.xml
new file mode 100644
index 00000000..da37e8c0
--- /dev/null
+++ b/tests/test_data/traffic_estimator_service.xml
@@ -0,0 +1,3343 @@
+
+
+
+
+
+
+
+
+
+ Errors that are thrown when a non-AdX feature is accessed by an AdX customer.
+
+
+
+
+
+
+
+
+ The error reason represented by an enum.
+
+
+
+
+
+
+
+
+
+
+ The API error base class that provides details about an error that occurred
+ while processing a service request.
+
+ <p>The OGNL field path is provided for parsers to identify the request data
+ element that may have caused the error.</p>
+
+
+
+
+
+
+ The OGNL field path to identify cause of error.
+
+
+
+
+
+
+ A parsed copy of the field path. For example, the field path "operations[1].operand"
+ corresponds to this list: {FieldPathElement(field = "operations", index = 1),
+ FieldPathElement(field = "operand", index = null)}.
+
+
+
+
+
+
+ The data that caused the error.
+
+
+
+
+
+
+ A simple string representation of the error and reason.
+
+
+
+
+
+
+ Indicates that this instance is a subtype of ApiError.
+ Although this field is returned in the response, it is ignored on input
+ and cannot be selected. Specify xsi:type instead.
+
+
+
+
+
+
+
+
+ Exception class for holding a list of service errors.
+
+
+
+
+
+
+
+
+ List of errors.
+
+
+
+
+
+
+
+
+
+
+ Base class for exceptions.
+
+
+
+
+
+
+ Error message.
+
+
+
+
+
+
+ Indicates that this instance is a subtype of ApplicationException.
+ Although this field is returned in the response, it is ignored on input
+ and cannot be selected. Specify xsi:type instead.
+
+
+
+
+
+
+
+
+ Errors returned when Authentication failed.
+
+
+
+
+
+
+
+
+ The error reason represented by an enum.
+
+
+
+
+
+
+
+
+
+
+ Errors encountered when trying to authorize a user.
+
+
+
+
+
+
+
+
+ The error reason represented by an enum.
+
+
+
+
+
+
+
+
+
+
+ Error due to user not accepting the AdWords terms of service.
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Errors associated with the size of the given collection being
+ out of bounds.
+
+
+
+
+
+
+
+
+ The error reason represented by an enum.
+
+
+
+
+
+
+
+
+
+
+ Comparable types for constructing ranges with.
+
+
+
+
+
+
+ Indicates that this instance is a subtype of ComparableValue.
+ Although this field is returned in the response, it is ignored on input
+ and cannot be selected. Specify xsi:type instead.
+
+
+
+
+
+
+
+
+ Represents a criterion (such as a keyword, placement, or vertical).
+ <span class="constraint AdxEnabled">This is disabled for AdX when it is contained within Operators: ADD, SET.</span>
+
+
+
+
+
+
+ ID of this criterion.
+ <span class="constraint Selectable">This field can be selected using the value "Id".</span><span class="constraint Filterable">This field can be filtered on.</span>
+ <span class="constraint Required">This field is required and should not be {@code null} when it is contained within {@link Operator}s : SET, REMOVE.</span>
+
+
+
+
+
+
+ <span class="constraint Selectable">This field can be selected using the value "CriteriaType".</span><span class="constraint Filterable">This field can be filtered on.</span>
+ <span class="constraint ReadOnly">This field is read only and will be ignored when sent to the API.</span>
+
+
+
+
+
+
+ Indicates that this instance is a subtype of Criterion.
+ Although this field is returned in the response, it is ignored on input
+ and cannot be selected. Specify xsi:type instead.
+
+
+
+
+
+
+
+
+ Errors that are thrown due to a database access problem.
+
+
+
+
+
+
+
+
+ The error reason represented by an enum.
+
+
+
+
+
+
+
+
+
+
+ Errors associated with invalid dates and date ranges.
+
+
+
+
+
+
+
+
+ The error reason represented by an enum.
+
+
+
+
+
+
+
+
+
+
+ Errors related to distinct ids or content.
+
+
+
+
+
+
+
+
+ The error reason represented by an enum.
+
+
+
+
+
+
+
+
+
+
+ Number value type for constructing double valued ranges.
+
+
+
+
+
+
+
+
+ the underlying double value.
+
+
+
+
+
+
+
+
+
+
+ Reports permission problems trying to access an entity.
+
+
+
+
+
+
+
+
+ Reason for this error.
+
+
+
+
+
+
+
+
+
+
+ An id did not correspond to an entity, or it referred to an entity which does not belong to the
+ customer.
+
+
+
+
+
+
+
+
+ Reason for this error.
+
+
+
+
+
+
+
+
+
+
+ A segment of a field path. Each dot in a field path defines a new segment.
+
+
+
+
+
+
+ The name of a field in lower camelcase. (e.g. "biddingStrategy")
+
+
+
+
+
+
+ For list fields, this is a 0-indexed position in the list. Null for non-list fields.
+
+
+
+
+
+
+
+
+ Errors associated with the ids.
+
+
+
+
+
+
+
+
+ The error reason represented by an enum.
+
+
+
+
+
+
+
+
+
+
+ Indicates that a server-side error has occured. {@code InternalApiError}s
+ are generally not the result of an invalid request or message sent by the
+ client.
+
+
+
+
+
+
+
+
+ The error reason represented by an enum.
+
+
+
+
+
+
+
+
+
+
+ Represents a keyword.
+ <span class="constraint AdxEnabled">This is disabled for AdX when it is contained within Operators: ADD, SET.</span>
+
+
+
+
+
+
+
+
+ Text of this keyword (at most 80 characters and ten words).
+ <span class="constraint Selectable">This field can be selected using the value "KeywordText".</span><span class="constraint Filterable">This field can be filtered on.</span>
+ <span class="constraint MatchesRegex">Keyword text must not contain NUL (code point 0x0) characters. This is checked by the regular expression '[^\x00]*'.</span>
+ <span class="constraint Required">This field is required and should not be {@code null} when it is contained within {@link Operator}s : ADD.</span>
+
+
+
+
+
+
+ Match type of this keyword.
+ <span class="constraint Selectable">This field can be selected using the value "KeywordMatchType".</span><span class="constraint Filterable">This field can be filtered on.</span>
+ <span class="constraint Required">This field is required and should not be {@code null} when it is contained within {@link Operator}s : ADD.</span>
+
+
+
+
+
+
+
+
+
+
+ Represents a Language criterion.
+ <p>A criterion of this type can only be created using an ID.
+ <span class="constraint AdxEnabled">This is enabled for AdX.</span>
+
+
+
+
+
+
+
+
+ <span class="constraint ReadOnly">This field is read only and will be ignored when sent to the API.</span>
+
+
+
+
+
+
+ <span class="constraint ReadOnly">This field is read only and will be ignored when sent to the API.</span>
+
+
+
+
+
+
+
+
+
+
+ Represents Location criterion.
+ <p>A criterion of this type can only be created using an ID.
+ <span class="constraint AdxEnabled">This is enabled for AdX.</span>
+
+
+
+
+
+
+
+
+ Name of the location criterion. <b> Note:</b> This field is filterable only in
+ LocationCriterionService. If used as a filter, a location name cannot be greater than 300
+ characters.
+ <span class="constraint ReadOnly">This field is read only and will be ignored when sent to the API.</span>
+
+
+
+
+
+
+ Display type of the location criterion.
+ <span class="constraint ReadOnly">This field is read only and will be ignored when sent to the API.</span>
+
+
+
+
+
+
+ The targeting status of the location criterion.
+ <span class="constraint ReadOnly">This field is read only and will be ignored when sent to the API.</span>
+
+
+
+
+
+
+ Ordered list of parents of the location criterion.
+ <span class="constraint ReadOnly">This field is read only and will be ignored when sent to the API.</span>
+
+
+
+
+
+
+
+
+
+
+ Number value type for constructing long valued ranges.
+
+
+
+
+
+
+
+
+ the underlying long value.
+
+
+
+
+
+
+
+
+
+
+ Represents the mobile app category to be targeted.
+ <a href="/adwords/api/docs/appendix/mobileappcategories">View the complete list of
+ available mobile app categories</a>.
+ <span class="constraint AdxEnabled">This is enabled for AdX.</span>
+
+
+
+
+
+
+
+
+ ID of this mobile app category. A complete list of the available mobile app categories is
+ available <a href="/adwords/api/docs/appendix/mobileappcategories">here</a>.
+ <span class="constraint Selectable">This field can be selected using the value "MobileAppCategoryId".</span>
+ <span class="constraint Required">This field is required and should not be {@code null} when it is contained within {@link Operator}s : ADD.</span>
+
+
+
+
+
+
+ Name of this mobile app category.
+ <span class="constraint ReadOnly">This field is read only and will be ignored when sent to the API.</span>
+
+
+
+
+
+
+
+
+
+
+ Represents the mobile application to be targeted.
+ <span class="constraint AdxEnabled">This is enabled for AdX.</span>
+
+
+
+
+
+
+
+
+ A string that uniquely identifies a mobile application to AdWords API. The format of this
+ string is "<code>{platform}-{platform_native_id}</code>", where <code>platform</code> is "1"
+ for iOS apps and "2" for Android apps, and where <code>platform_native_id</code> is the mobile
+ application identifier native to the corresponding platform.
+ For iOS, this native identifier is the 9 digit string that appears at the end of an App Store
+ URL (e.g., "476943146" for "Flood-It! 2" whose App Store link is
+ http://itunes.apple.com/us/app/flood-it!-2/id476943146).
+ For Android, this native identifier is the application's package name (e.g.,
+ "com.labpixies.colordrips" for "Color Drips" given Google Play link
+ https://play.google.com/store/apps/details?id=com.labpixies.colordrips).
+ A well formed app id for AdWords API would thus be "1-476943146" for iOS and
+ "2-com.labpixies.colordrips" for Android.
+ <span class="constraint Selectable">This field can be selected using the value "AppId".</span><span class="constraint Filterable">This field can be filtered on.</span>
+ <span class="constraint Required">This field is required and should not be {@code null} when it is contained within {@link Operator}s : ADD.</span>
+
+
+
+
+
+
+ Title of this mobile application.
+ <span class="constraint Selectable">This field can be selected using the value "DisplayName".</span><span class="constraint Filterable">This field can be filtered on.</span>
+ <span class="constraint ReadOnly">This field is read only and will be ignored when sent to the API.</span>
+
+
+
+
+
+
+
+
+
+
+ Represents a money amount.
+
+
+
+
+
+
+
+
+ Amount in micros. One million is equivalent to one unit.
+
+
+
+
+
+
+
+
+
+
+ Network settings for a Campaign.
+
+
+
+
+
+
+ Ads will be served with Google.com search results.
+ <span class="constraint AdxEnabled">This is disabled for AdX.</span>
+ <span class="constraint CampaignType">This field may only be set to true for campaign channel type SEARCH.</span>
+<span class="constraint CampaignType">This field may only be set to true for campaign channel type MULTI_CHANNEL.</span>
+<span class="constraint CampaignType">This field may only be set to false for campaign channel type DISPLAY.</span>
+<span class="constraint CampaignType">This field may only be set to true for campaign channel subtype SHOPPING_GOAL_OPTIMIZED_ADS.</span>
+
+
+
+
+
+
+ Ads will be served on partner sites in the Google Search Network
+ (requires {@code GOOGLE_SEARCH}).
+ <span class="constraint AdxEnabled">This is disabled for AdX.</span>
+ <span class="constraint CampaignType">This field may only be set to true for campaign channel type MULTI_CHANNEL.</span>
+<span class="constraint CampaignType">This field may only be set to true for campaign channel subtype SHOPPING_GOAL_OPTIMIZED_ADS.</span>
+
+
+
+
+
+
+ Ads will be served on specified placements in the Google Display Network.
+ Placements are specified using {@code Placement} criteria.
+ <span class="constraint CampaignType">This field may only be set to true for campaign channel type MULTI_CHANNEL.</span>
+<span class="constraint CampaignType">This field may only be set to false for campaign channel subtype SEARCH_MOBILE_APP.</span>
+<span class="constraint CampaignType">This field may only be set to true for campaign channel type DISPLAY with campaign channel subtype DISPLAY_SMART_CAMPAIGN.</span>
+<span class="constraint CampaignType">This field may only be set to true for campaign channel subtype SHOPPING_GOAL_OPTIMIZED_ADS.</span>
+
+
+
+
+
+
+ Ads will be served on the Google Partner Network. This is available to
+ only some specific Google partner accounts.
+ <span class="constraint AdxEnabled">This is disabled for AdX.</span>
+ <span class="constraint CampaignType">This field may only be set to false for campaign channel type MULTI_CHANNEL.</span>
+
+
+
+
+
+
+
+
+ Errors corresponding with violation of a NOT EMPTY check.
+
+
+
+
+
+
+
+
+ The error reason represented by an enum.
+
+
+
+
+
+
+
+
+
+
+ Errors associated with violation of a NOT NULL check.
+
+
+
+
+
+
+
+
+ The error reason represented by an enum.
+
+
+
+
+
+
+
+
+
+
+ Number value types for constructing number valued ranges.
+
+
+
+
+
+
+
+
+
+
+
+ Operation not permitted due to the invoked service's access policy.
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Errors due to the use of unsupported operations.
+
+
+
+
+
+
+
+
+ The error reason represented by an enum.
+
+
+
+
+
+
+
+
+
+
+ A placement used for modifying bids for sites when targeting the content
+ network.
+ <span class="constraint AdxEnabled">This is enabled for AdX.</span>
+
+
+
+
+
+
+
+
+ Url of the placement.
+
+ <p>For example, "http://www.domain.com".
+ <span class="constraint Selectable">This field can be selected using the value "PlacementUrl".</span><span class="constraint Filterable">This field can be filtered on.</span>
+ <span class="constraint Required">This field is required and should not be {@code null} when it is contained within {@link Operator}s : ADD.</span>
+
+
+
+
+
+
+
+
+
+
+ Represents Platform criterion.
+ <p>A criterion of this type can only be created using an ID.
+ <span class="constraint AdxEnabled">This is enabled for AdX.</span>
+
+
+
+
+
+
+
+
+ <span class="constraint ReadOnly">This field is read only and will be ignored when sent to the API.</span>
+
+
+
+
+
+
+
+
+
+
+ Encapsulates the errors thrown during developer quota checks.
+
+
+
+
+
+
+
+
+
+
+
+
+
+ A list of all errors associated with the Range constraint.
+
+
+
+
+
+
+
+
+ The error reason represented by an enum.
+
+
+
+
+
+
+
+
+
+
+ Signals that a call failed because a measured rate exceeded.
+
+
+
+
+
+
+
+
+ The error reason represented by an enum.
+
+
+
+
+
+
+ Cause of the rate exceeded error.
+
+
+
+
+
+
+ The scope of the rate (ACCOUNT/DEVELOPER).
+
+
+
+
+
+
+ The amount of time (in seconds) the client should wait before retrying the request.
+
+
+
+
+
+
+
+
+
+
+ Errors from attempting to write to read-only fields.
+
+
+
+
+
+
+
+
+ The error reason represented by an enum.
+
+
+
+
+
+
+
+
+
+
+ A list of all errors associated with the @RegionCode constraints.
+
+
+
+
+
+
+
+
+ The error reason represented by an enum.
+
+
+
+
+
+
+
+
+
+
+ Indicates that a field was rejected due to compatibility issues.
+
+
+
+
+
+
+
+
+ The error reason represented by an enum.
+
+
+
+
+
+
+
+
+
+
+ Encapsulates the generic errors thrown when there's an error with user
+ request.
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Errors due to missing required field.
+
+
+
+
+
+
+
+
+ The error reason represented by an enum.
+
+
+
+
+
+
+
+
+
+
+ Indicates that the number of entries in the request or response exceeds the system limit.
+
+
+
+
+
+
+
+
+ The error reason represented by an enum.
+
+
+
+
+
+
+
+
+
+
+ Defines the required and optional elements within the header of a SOAP request.
+
+
+
+
+
+
+ The header identifies the customer id of the client of the AdWords manager, if an AdWords
+ manager is acting on behalf of their client or the customer id of the advertiser managing their
+ own account.
+
+
+
+
+
+
+ Developer token to identify that the person making the call has enough
+ quota.
+
+
+
+
+
+
+ UserAgent is used to track distribution of API client programs and
+ application usage. The client is responsible for putting in a meaningful
+ value for tracking purposes. To be clear this is not the same as an HTTP
+ user agent.
+
+
+
+
+
+
+ Used to validate the request without executing it.
+
+
+
+
+
+
+ If true, API will try to commit as many error free operations as possible and
+ report the other operations' errors.
+
+ <p>Ignored for non-mutate calls.
+
+
+
+
+
+
+
+
+ Defines the elements within the header of a SOAP response.
+
+
+
+
+
+
+ Unique id that identifies this request. If developers have any support issues, sending us
+ this id will enable us to find their request more easily.
+
+
+
+
+
+
+ The name of the service being invoked.
+
+
+
+
+
+
+ The name of the method being invoked.
+
+
+
+
+
+
+ Number of operations performed for this SOAP request.
+
+
+
+
+
+
+ Elapsed time in milliseconds between the AdWords API receiving the request and sending the
+ response.
+
+
+
+
+
+
+
+
+ A list of error code for reporting invalid content of input strings.
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Errors associated with the length of the given string being
+ out of bounds.
+
+
+
+
+
+
+
+
+ The error reason represented by an enum.
+
+
+
+
+
+
+
+
+
+
+ User Interest represents a particular interest-based vertical to be targeted.
+ <span class="constraint AdxEnabled">This is enabled for AdX.</span>
+
+
+
+
+
+
+
+
+ Id of this user interest. This is a required field.
+ <span class="constraint Selectable">This field can be selected using the value "UserInterestId".</span>
+
+
+
+
+
+
+ Parent Id of this user interest.
+ <span class="constraint Selectable">This field can be selected using the value "UserInterestParentId".</span>
+ <span class="constraint ReadOnly">This field is read only and will be ignored when sent to the API.</span>
+
+
+
+
+
+
+ Name of this user interest.
+ <span class="constraint Selectable">This field can be selected using the value "UserInterestName".</span>
+
+
+
+
+
+
+
+
+
+
+ UserList - represents a user list that is defined by the advertiser to be targeted.
+ <span class="constraint AdxEnabled">This is enabled for AdX.</span>
+
+
+
+
+
+
+
+
+ Id of this user list. This is a required field.
+ <span class="constraint Selectable">This field can be selected using the value "UserListId".</span>
+
+
+
+
+
+
+ <span class="constraint Selectable">This field can be selected using the value "UserListName".</span>
+
+
+
+
+
+
+ <span class="constraint Selectable">This field can be selected using the value "UserListMembershipStatus".</span><span class="constraint Filterable">This field can be filtered on.</span>
+
+
+
+
+
+
+ Determines whether a user list is eligible for targeting in the google.com
+ (search) network.
+ <span class="constraint Selectable">This field can be selected using the value "UserListEligibleForSearch".</span><span class="constraint Filterable">This field can be filtered on.</span>
+ <span class="constraint ReadOnly">This field is read only and will be ignored when sent to the API.</span>
+
+
+
+
+
+
+ Determines whether a user list is eligible for targeting in the display network.
+ <span class="constraint Selectable">This field can be selected using the value "UserListEligibleForDisplay".</span><span class="constraint Filterable">This field can be filtered on.</span>
+ <span class="constraint ReadOnly">This field is read only and will be ignored when sent to the API.</span>
+
+
+
+
+
+
+
+
+
+
+ Use verticals to target or exclude placements in the Google Display Network
+ based on the category into which the placement falls (for example, "Pets &
+ Animals/Pets/Dogs").
+ <a href="/adwords/api/docs/appendix/verticals">View the complete list
+ of available vertical categories.</a>
+ <span class="constraint AdxEnabled">This is enabled for AdX.</span>
+
+
+
+
+
+
+
+
+ Id of this vertical.
+ <span class="constraint Selectable">This field can be selected using the value "VerticalId".</span>
+
+
+
+
+
+
+ Id of the parent of this vertical.
+ <span class="constraint Selectable">This field can be selected using the value "VerticalParentId".</span>
+ <span class="constraint ReadOnly">This field is read only and will be ignored when sent to the API.</span>
+
+
+
+
+
+
+ The category to target or exclude. Each subsequent element in the array
+ describes a more specific sub-category. For example,
+ <code>{"Pets & Animals", "Pets", "Dogs"}</code> represents the "Pets &
+ Animals/Pets/Dogs" category. A complete list of available vertical categories
+ is available <a href="/adwords/api/docs/appendix/verticals">here</a>
+ This field is required and must not be empty.
+ <span class="constraint Selectable">This field can be selected using the value "Path".</span>
+
+
+
+
+
+
+
+
+
+
+ The reasons for the AdX error.
+
+
+
+
+
+
+ Attempt to use non-AdX feature by AdX customer.
+
+
+
+
+
+
+
+
+ The single reason for the authentication failure.
+
+
+
+
+
+
+ Authentication of the request failed.
+
+
+
+
+
+
+ Client Customer Id is required if CustomerIdMode is set to CLIENT_EXTERNAL_CUSTOMER_ID.
+ Starting version V201409 ClientCustomerId will be required for all requests except
+ for {@link CustomerService#get}
+
+
+
+
+
+
+ Client Email is required if CustomerIdMode is set to CLIENT_EXTERNAL_EMAIL_FIELD.
+
+
+
+
+
+
+ Client customer Id is not a number.
+
+
+
+
+
+
+ Client customer Id is not a number.
+
+
+
+
+
+
+ Client email is not a valid customer email.
+
+
+
+
+
+
+ No customer found for the customer id provided in the header.
+
+
+
+
+
+
+ Client's Google Account is deleted.
+
+
+
+
+
+
+ Google account login token in the cookie is invalid.
+
+
+
+
+
+
+ problem occurred during Google account authentication.
+
+
+
+
+
+
+ The user in the google account login token does not match the UserId in the cookie.
+
+
+
+
+
+
+ Login cookie is required for authentication.
+
+
+
+
+
+
+ User in the cookie is not a valid Ads user.
+
+
+
+
+
+
+ Oauth token in the header is not valid.
+
+
+
+
+
+
+ Oauth token in the header has expired.
+
+
+
+
+
+
+ Oauth token in the header has been disabled.
+
+
+
+
+
+
+ Oauth token in the header has been revoked.
+
+
+
+
+
+
+ Oauth token HTTP header is malformed.
+
+
+
+
+
+
+ Login cookie is not valid.
+
+
+
+
+
+
+ Failed to decrypt the login cookie.
+
+
+
+
+
+
+ User Id in the header is not a valid id.
+
+
+
+
+
+
+
+
+ The reasons for the authorization error.
+
+
+
+
+
+
+ Could not complete authorization due to an internal problem.
+
+
+
+
+
+
+ Customer has no AdWords account.
+
+
+
+
+
+
+ User doesn't have permission to access customer.
+
+
+
+
+
+
+ Effective user doesn't have permission to access this customer.
+
+
+
+
+
+
+ Access denied since the customer is not active.
+
+
+
+
+
+
+ User has read-only permission cannot mutate.
+
+
+
+
+
+
+ No customer found.
+
+
+
+
+
+
+ Developer doesn't have permission to access service.
+
+
+
+
+
+
+ The customer has a policy to enforce 2-Step Verification, but the user is not enrolled.
+
+
+
+
+
+
+ The customer has a policy to enforce enrollment in the Advanced Protection Program, but
+ the user is not enrolled.
+
+
+
+
+
+
+
+
+ Enums for the various reasons an error can be thrown as a result of
+ ClientTerms violation.
+
+
+
+
+
+
+ Customer has not agreed to the latest AdWords Terms & Conditions
+
+
+
+
+
+
+
+
+ The reasons for the target error.
+
+
+
+
+
+
+
+
+
+
+ The types of criteria.
+
+
+
+
+
+
+ Content label for exclusion.
+
+
+
+
+
+
+ Keyword. e.g. 'mars cruise'
+
+
+
+
+
+
+ Placement. aka Website. e.g. 'www.flowers4sale.com'
+
+
+
+
+
+
+ Vertical, e.g. 'category::Animals>Pets' This is for vertical targeting on the content
+ network.
+
+
+
+
+
+
+ User lists, are links to sets of users defined by the advertiser.
+
+
+
+
+
+
+ User interests, categories of interests the user is interested in.
+
+
+
+
+
+
+ Mobile applications to target.
+
+
+
+
+
+
+ Mobile application categories to target.
+
+
+
+
+
+
+ Product partition (product group) in a shopping campaign.
+
+
+
+
+
+
+ IP addresses to exclude.
+
+
+
+
+
+
+ Webpages of an advertiser's website to target.
+
+
+
+
+
+
+ Languages to target.
+
+
+
+
+
+
+ Geographic regions to target.
+
+
+
+
+
+
+ Age Range to exclude.
+
+
+
+
+
+
+ Mobile carriers to target.
+
+
+
+
+
+
+ Mobile operating system versions to target.
+
+
+
+
+
+
+ Mobile devices to target.
+
+
+
+
+
+
+ Gender to exclude.
+
+
+
+
+
+
+ Parent to target and exclude.
+
+
+
+
+
+
+ Proximity (area within a radius) to target.
+
+
+
+
+
+
+ Platforms to target.
+
+
+
+
+
+
+ Representing preferred content bid modifier.
+
+
+
+
+
+
+ AdSchedule or specific days and time intervals to target.
+
+
+
+
+
+
+ Targeting based on location groups.
+
+
+
+
+
+
+ Scope of products. Contains a list of product dimensions, all of which a product has to match
+ to be included in the campaign.
+
+
+
+
+
+
+ Custom Affinity, a criterion used for custom audience targeting.
+
+
+
+
+
+
+ Custom Intent, a criterion used for custom audience targeting.
+
+
+
+
+
+
+ YouTube video to target.
+
+
+
+
+
+
+ YouTube channel to target.
+
+
+
+
+
+
+ Enables advertisers to target paid apps.
+
+
+
+
+
+
+ Income range to target and exclude.
+
+
+
+
+
+
+ Interaction type to bid modify.
+
+
+
+
+
+
+ <span class="constraint Rejected">Used for return value only. An enumeration could not be processed, typically due to incompatibility with your WSDL version.</span>
+
+
+
+
+
+
+
+
+ The reasons for the database error.
+
+
+
+
+
+
+ A concurrency problem occurred as two threads were attempting to modify same object.
+
+
+
+
+
+
+ The permission was denied to access an object.
+
+
+
+
+
+
+ The user's access to an object has been prohibited.
+
+
+
+
+
+
+ Requested campaign belongs to a product that is not supported by the api.
+
+
+
+
+
+
+ a duplicate key was detected upon insertion
+
+
+
+
+
+
+ a database error has occurred
+
+
+
+
+
+
+ an unknown error has occurred
+
+
+
+
+
+
+
+
+ The reasons for the target error.
+
+
+
+
+
+
+ Given field values do not correspond to a valid date.
+
+
+
+
+
+
+ Given field values do not correspond to a valid date time.
+
+
+
+
+
+
+ The string date's format should be yyyymmdd.
+
+
+
+
+
+
+ The string date range's format should be yyyymmdd yyyymmdd.
+
+
+
+
+
+
+ The string date time's format should be yyyymmdd hhmmss [tz].
+
+
+
+
+
+
+ Date is before allowed minimum.
+
+
+
+
+
+
+ Date is after allowed maximum.
+
+
+
+
+
+
+ Date range bounds are not in order.
+
+
+
+
+
+
+ Both dates in range are null.
+
+
+
+
+
+
+
+
+ The reasons for the validation error.
+
+
+
+
+
+
+
+
+
+
+
+
+ User did not have read access.
+
+
+
+
+
+
+ User did not have write access.
+
+
+
+
+
+
+
+
+
+
+ The specified id refered to an entity which either doesn't exist or is not accessible to the
+ customer. e.g. campaign belongs to another customer.
+
+
+
+
+
+
+
+
+ The reasons for the target error.
+
+
+
+
+
+
+ Id not found
+
+
+
+
+
+
+
+
+ The single reason for the internal API error.
+
+
+
+
+
+
+ API encountered an unexpected internal error.
+
+
+
+
+
+
+ A temporary error occurred during the request. Please retry.
+
+
+
+
+
+
+ The cause of the error is not known or only defined in newer versions.
+
+
+
+
+
+
+ The API is currently unavailable for a planned downtime.
+
+
+
+
+
+
+ Mutate succeeded but server was unable to build response. Client should not retry mutate.
+
+
+
+
+
+
+
+
+ Match type of a keyword. i.e. the way we match a keyword string with
+ search queries.
+
+
+
+
+
+
+ Exact match
+
+
+
+
+
+
+ Phrase match
+
+
+
+
+
+
+ Broad match
+
+
+
+
+
+
+
+
+ Enum that represents the different Targeting Status values for a Location criterion.
+
+
+
+
+
+
+ The location is active.
+
+
+
+
+
+
+ The location is not available for targeting.
+
+
+
+
+
+
+ The location is phasing out, it will marked obsolete soon.
+
+
+
+
+
+
+
+
+ The reasons for the validation error.
+
+
+
+
+
+
+
+
+
+ The reasons for the validation error.
+
+
+
+
+
+
+ Specified list/container must not contain any null elements
+
+
+
+
+
+
+
+
+ The reasons for the operation access error.
+
+
+
+
+
+
+ Unauthorized invocation of a service's method (get, mutate, etc.)
+
+
+
+
+
+
+ Unauthorized ADD operation in invoking a service's mutate method.
+
+
+
+
+
+
+ Unauthorized REMOVE operation in invoking a service's mutate method.
+
+
+
+
+
+
+ Unauthorized SET operation in invoking a service's mutate method.
+
+
+
+
+
+
+ A mutate action is not allowed on this campaign, from this client.
+
+
+
+
+
+
+ This operation is not permitted on this campaign type
+
+
+
+
+
+
+ An ADD operation may not set status to REMOVED.
+
+
+
+
+
+
+ This operation is not allowed because the campaign or adgroup is removed.
+
+
+
+
+
+
+ This operation is not permitted on this ad group type.
+
+
+
+
+
+
+ The reason the invoked method or operation is prohibited is not known
+ (the client may be of an older version than the server).
+
+
+
+
+
+
+
+
+ The reasons for the validation error.
+
+
+
+
+
+
+
+
+
+ Enums for all the reasons an error can be thrown to the user during
+ billing quota checks.
+
+
+
+
+
+
+ Customer passed in an invalid token in the header.
+
+
+
+
+
+
+ Customer is marked delinquent.
+
+
+
+
+
+
+ Customer is a fraudulent.
+
+
+
+
+
+
+ Inactive Account.
+
+
+
+
+
+
+ Signup not complete
+
+
+
+
+
+
+ Developer token is not approved for production access, and the customer
+ is attempting to access a production account.
+
+
+
+
+
+
+ Terms and conditions are not signed.
+
+
+
+
+
+
+ Monthly budget quota reached.
+
+
+
+
+
+
+ Monthly budget quota exceeded.
+
+
+
+
+
+
+
+
+ The reasons for the target error.
+
+
+
+
+
+
+
+
+
+
+ The reason for the rate exceeded error.
+
+
+
+
+
+
+ Rate exceeded.
+
+
+
+
+
+
+
+
+ The reasons for the target error.
+
+
+
+
+
+
+
+
+
+ The reasons for the validation error.
+
+
+
+
+
+
+
+
+
+ The reasons for the target error.
+
+
+
+
+
+
+ Unknown value encountered
+
+
+
+
+
+
+
+
+
+
+ Error reason is unknown.
+
+
+
+
+
+
+ Invalid input.
+
+
+
+
+
+
+ The api version in the request has been discontinued. Please update
+ to the new AdWords API version.
+
+
+
+
+
+
+
+
+ The reasons for the target error.
+
+
+
+
+
+
+ Missing required field.
+
+
+
+
+
+
+
+
+ The reasons for Ad Scheduling errors.
+
+
+
+
+
+
+ The number of entries in the request exceeds the system limit.
+
+
+
+
+
+
+ The number of entries in the response exceeds the system limit.
+
+
+
+
+
+
+ The account is too large to load.
+
+
+
+
+
+
+ <span class="constraint Rejected">Used for return value only. An enumeration could not be processed, typically due to incompatibility with your WSDL version.</span>
+
+
+
+
+
+
+
+
+ The reasons for the target error.
+
+
+
+
+
+
+
+ The input string value contains disallowed characters.
+
+
+
+
+
+
+ The input string value is invalid for the associated field.
+
+
+
+
+
+
+
+
+ The reasons for the target error.
+
+
+
+
+
+
+
+
+
+
+ Membership status of the user list.
+
+
+
+
+
+
+ Open status - list is accruing members and can be targeted to.
+
+
+
+
+
+
+ Closed status - No new members being added. Can not be used for targeting a new campaign.
+ Existing campaigns can still work as long as the list is not removed as a targeting criteria.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Represents the estimate results for a single ad group.
+
+
+
+
+
+
+
+
+ The adGroupId of the ad group specified in the request.
+
+ This will be <code>null</code> for new ad groups.
+
+
+
+
+
+
+ The estimates for the keywords specified in the request.
+
+ The list of estimates are returned in the same order as the keywords that
+ were sent in the request.
+
+
+
+
+
+
+
+
+
+
+ Represents an ad group that will be estimated. Ad groups may be all
+ new or all existing, or a mixture of new and existing. Only existing
+ campaigns can contain estimates for existing ad groups.<p>
+
+ <p>To make a keyword estimates request in which estimates do not consider
+ existing account information (e.g. historical ad group performance), set both
+ {@link #adGroupId} and the enclosing {@link CampaignEstimateRequest}'s
+ {@code campaignId} to {@code null}.
+
+ <p>For more details on usage, refer to document at
+ {@link CampaignEstimateRequest}.
+
+
+
+
+
+
+
+
+ The adGroupId for an ad group that belongs to the containing campaign from
+ {@link CampaignEstimateRequest} or {@code null}.
+
+ <p>For usage, refer to document from {@link CampaignEstimateRequest}.
+
+
+
+
+
+
+ The keywords to estimate.
+ <span class="constraint ContentsDistinct">This field must contain distinct elements.</span>
+ <span class="constraint ContentsNotNull">This field must not contain {@code null} elements.</span>
+ <span class="constraint Required">This field is required and should not be {@code null}.</span>
+
+
+
+
+
+
+ The max CPC bid to use for estimates for this ad group.
+
+ <p>This value overrides the max CPC of AdGroup specified by
+ {@link #adGroupId}.
+
+
+
+
+
+
+
+
+
+
+ Represents the estimate results for a single campaign.
+
+
+
+
+
+
+
+
+ The campaignId of the campaign specified in the request.
+
+ This will be <code>null</code> for new campaigns.
+
+
+
+
+
+
+ The estimates for the ad groups belonging to this campaign in the request.
+
+ They will be returned in the same order that they were sent in the request.
+
+
+
+
+
+
+ Traffic estimates segmented by platform for this campaign.
+
+
+
+
+
+
+
+
+
+
+ Represents a campaign that will be estimated.<p>
+
+ Returns traffic estimates for the requested set of campaigns.
+ The campaigns can be all new or all existing, or a mixture of
+ new and existing. Only existing campaigns may contain estimates for existing
+ ad groups.<p>
+
+ For existing campaigns, the campaign and optionally the ad group will be
+ used as context to produce more accurate estimates. Traffic estimates may
+ only be requested on keywords, so regardless of whether campaign and ad group
+ IDs are provided or left blank, at least one keyword is required to estimate
+ traffic.<p>
+
+ To make a keyword estimates request in which estimates do not consider
+ existing account information (e.g. historical ad group performance), set
+ {@link #campaignId} to {@code null}.
+
+
+
+
+
+
+
+
+ The campaignId of an existing campaign or {@code null}.<p>
+
+ Refer to the {@link CampaignEstimateRequest} documentation for
+ detailed usage.
+
+
+
+
+
+
+ The list of ad groups to estimate. This field is required and should not be {@code null}. At
+ least one ad group is required.
+
+ <p>New campaigns may only contain new ad groups. If an
+ {@link AdGroupEstimateRequest} has an adGroupId but the campaign is new,
+ the API will return an error.
+ <span class="constraint ContentsNotNull">This field must not contain {@code null} elements.</span>
+
+
+
+
+
+
+ A list of {@link Criterion}s to be used for this Campaign. Criteria
+ provide information about geographical and language targeting.
+
+ <p>Values in this field override the current targets in the Campaign
+ specified by {@link #campaignId} by the following mechanism:
+
+ <p>This field accepts two types of {@link Criterion}s: {@link Location}, which should contain
+ all geographic targeting and {@link Language}, which should contain all language targeting.
+ If {@link Location}s are passed in, all geographic targeting in the campaign will be
+ overridden. If any {@link Language}s are passed in, all language targeting in the campaign
+ will be overridden.
+
+ <p>If multiple {@link Location}s are specified, the traffic estimate will
+ be the sum of the estimates for each targeted area. This means that if
+ criteria are chosen which overlap each other (for example, targeting both
+ a country and a city within that country), the traffic estimate will be
+ be larger than if no overlap were present - i. e., the overlap region will
+ be double-counted in the estimate.
+
+ <p>If no criteria are specified and this is for a new campaign then it
+ will default to all languages in all countries and territories, and
+ Google search.
+
+ <p>If no criteria are specified and this is for an existing campaign
+ then the current targeting on that campaign will be used.
+
+ <p>While there's no solid limit on number of criteria,
+ TrafficEstimatorService may return error with TOO_MANY_TARGETS if the
+ request contains too many criteria across all
+ {@link CampaignEstimateRequest}s in a {@link TrafficEstimatorSelector}.
+
+ <p>Supported Criteria : {@link Language} and {@link Location}.
+ <span class="constraint ContentsDistinct">This field must contain distinct elements.</span>
+ <span class="constraint ContentsNotNull">This field must not contain {@code null} elements.</span>
+
+
+
+
+
+
+ A {@link NetworkSetting} to be used for this Campaign. The value of this
+ field overrides the current targets in the Campaign specified by
+ {@link #campaignId}.
+
+ <p>For non Google partner accounts, only
+ {@link NetworkSetting#targetGoogleSearch} and
+ {@link NetworkSetting#targetSearchNetwork} are supported, they may be
+ combined to sum the estimates.
+
+ <p>For some Google partner accounts, in addition
+ {@link NetworkSetting#getTargetPartnerSearchNetwork} is supported.
+
+ <p>If all request network settings and Campaign's network settings are
+ empty, the default is {@link NetworkSetting#targetGoogleSearch}.
+
+
+
+
+
+
+ Daily campaign budget to use in traffic estimation. If not specified,
+ the daily budget is unlimited.
+
+
+
+
+
+
+
+
+
+
+ Errors for currency codes.
+
+
+
+
+
+
+
+
+ The error reason represented by an enum.
+
+
+
+
+
+
+
+
+
+
+ Abstract class representing an reply to an {@link EstimateRequest}.
+
+
+
+
+
+
+ Indicates that this instance is a subtype of Estimate.
+ Although this field is returned in the response, it is ignored on input
+ and cannot be selected. Specify xsi:type instead.
+
+
+
+
+
+
+
+
+ Abstract class representing a request to estimate stats.
+
+
+
+
+
+
+ Indicates that this instance is a subtype of EstimateRequest.
+ Although this field is returned in the response, it is ignored on input
+ and cannot be selected. Specify xsi:type instead.
+
+
+
+
+
+
+
+
+ Represents the traffic estimate result for a single keyword.
+
+
+
+
+
+
+
+
+ The existing criterionId for this keyword, if any.
+
+ This will not be returned if this is a new keyword.
+
+
+
+
+
+
+ The lower bound on the estimated stats.
+
+ <p>This is not a guarantee that actual performance will never be lower than
+ these stats.
+
+
+
+
+
+
+ The upper bound on the estimated stats.
+
+ <p>This is not a guarantee that actual performance will never be higher than
+ these stats.
+
+
+
+
+
+
+
+
+
+
+ Represents a keyword to be estimated.
+
+
+
+
+
+
+
+
+ The {@link Keyword} to estimate. The keyword text is required regardless
+ of whether the keyword ID is included. The keyword ID is optional and has
+ the following characteristics:
+ <ul>
+ <li>When omitted, the ID indicates a new keyword to be estimated.</li>
+ <li>When present with a campaign and ad group also specified, the ID should
+ be for an existing keyword in the ad group. This can improve the estimates
+ since historical performance is known.</li>
+ <li>When present without a campaign and ad group specified, the ID is
+ ignored.</li>
+ </ul>
+ <span class="constraint Required">This field is required and should not be {@code null}.</span>
+
+
+
+
+
+
+ The max CPC bid for this keyword.
+
+ In general, the {@code maxCpc} of a {@link KeywordEstimateRequest} is
+ optional, since there is usually another {@code maxCpc} that can be used,
+ such as the {@code maxCpc} on an existing keyword, an existing or
+ overriding {@code maxCpc} of containing {@link AdGroupEstimateRequest}.
+ However, if there is no backup value of {@code maxCpc} anywhere along the
+ line, you must provide a value for {@code maxCpc} in
+ {@link KeywordEstimateRequest}. This would happen, for example, if the
+ {@link KeywordEstimateRequest} is for a new keyword.
+
+
+
+
+
+
+ Whether the keyword is negative or not. The default value is false.
+ If negative, no current ad group ads will appear for searches containing
+ this keyword.<p>
+
+ The estimate for negative keywords should reflect no traffic and zero CPC,
+ but including a negative keyword will affect the other estimates in the
+ request.
+
+
+
+
+
+
+
+
+
+
+ Contains a campaign level estimate for a specified {@link Platform}.
+
+
+
+
+
+
+ The {@link Platform} associated with this estimate.
+ <span class="constraint Required">This field is required and should not be {@code null}.</span>
+
+
+
+
+
+
+ Minimum estimate for the specified {@link Platform}.
+
+
+
+
+
+
+ Maximum estimate for the specified {@link Platform}.
+
+
+
+
+
+
+
+
+ Represents a set of stats for a daily traffic estimate.
+
+ <p>{@code averageCpc}, {@code averagePosition} and {@code clickThroughRate} will be
+ {@code null} when not defined and {@code clicksPerDay} or {@code impressionsPerDay}
+ is {@code 0}, respectively.</p>
+
+
+
+
+
+
+ The estimated average CPC.
+
+
+
+
+
+
+ The estimated average position.
+
+
+
+
+
+
+ The estimated click through rate.
+
+
+
+
+
+
+ The estimated number of clicks, in floating point representation.
+
+
+
+
+
+
+ The estimated number of impressions, in floating point representation.
+
+
+
+
+
+
+ The estimated total cost.
+
+
+
+
+
+
+
+
+ Base error class for {@link TrafficEstimatorService}.
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Contains results of traffic estimation request.
+
+
+
+
+
+
+ The estimates for the campaigns specified in the request.
+
+ They are listed in the same order as the campaigns that were sent in the
+ request.
+
+
+
+
+
+
+
+
+ Contains a list of campaigns to perform a traffic estimate on.
+
+
+
+
+
+
+ A list of all campaigns to estimate.<p>
+
+ To create a Keyword estimates request, use {@code null} campaign id.
+ <span class="constraint CollectionSize">The maximum size of this collection is 5.</span>
+ <span class="constraint ContentsDistinct">This field must contain distinct elements.</span>
+ <span class="constraint ContentsNotNull">This field must not contain {@code null} elements.</span>
+ <span class="constraint NotEmpty">This field must contain at least one element.</span>
+ <span class="constraint Required">This field is required and should not be {@code null}.</span>
+
+
+
+
+
+
+ To request a list of campaign level estimates segmented by platform.
+
+
+
+
+
+
+
+
+ Encodes the reason (cause) of a particular {@link CurrencyCodeError}.
+
+
+
+
+
+
+
+
+
+
+
+ When the request with {@code null} campaign ID in {@link CampaignEstimateRequest} contains an
+ {@link AdGroupEstimateRequest} with an ID.
+
+
+
+
+
+
+ When the request with {@code null} adgroup ID in {@link AdGroupEstimateRequest} contains a
+ {@link KeywordEstimateRequest} with an ID.
+
+
+
+
+
+
+ All {@link KeywordEstimateRequest} items should have maxCpc associated with them.
+
+
+
+
+
+
+ When there are more {@link KeywordEstimateRequest}s in the request than
+ TrafficEstimatorService allows.
+
+
+
+
+
+
+ When there are more {@link CampaignEstimateRequest}s in the request than
+ TrafficEstimatorService allows.
+
+
+
+
+
+
+ When there are more {@link AdGroupEstimateRequest}s in the request than
+ TrafficEstimatorService allows.
+
+
+
+
+
+
+ When there are more targets in the request than TrafficEstimatorService allows. See
+ documentation on {@link CampaignEstimateRequest} for more information about this error.
+
+
+
+
+
+
+ Request contains a keyword that is too long for backends to handle.
+
+
+
+
+
+
+ Request contains a keyword that contains broad match modifiers.
+
+
+
+
+
+
+ When an unexpected error occurs.
+
+
+
+
+
+
+ When backend service calls fail.
+
+
+
+
+
+
+
+
+ Returns traffic estimates for specified criteria.
+
+ @param selector Campaigns, ad groups and keywords for which traffic
+ should be estimated.
+ @return Traffic estimation results.
+ @throws ApiException if problems occurred while retrieving estimates
+
+
+
+
+
+
+
+ <span class="constraint Required">This field is required and should not be {@code null}.</span>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ A fault element of type ApiException.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Use this service to request traffic estimates for proposed or existing campaigns, ad
+ groups, and keywords.
+
+ <p>
+ To simply retrieve estimates for a list of proposed keywords, create a
+ {@linkplain CampaignEstimateRequest campaign estimate request} and a child
+ {@linkplain AdGroupEstimateRequest ad group estimate request} with {@code null} IDs,
+ and then set the
+ {@link AdGroupEstimateRequest#keywordEstimateRequests keywordEstimateRequests}
+ to contain the keywords.</p>
+
+ <p>You can refine the traffic estimates by setting
+ {@linkplain CampaignEstimateRequest#targets campaign targeting options} in the request.
+ If an ad group ID is provided, all creatives from that ad group will be loaded and used
+ to improve estimates.</p>
+
+ <p>The maximum number of {@linkplain KeywordEstimateRequest keyword estimate
+ requests} across all campaign estimate requests and
+ ad group estimate requests is 2500.</p>
+
+ <p>The maximum number of {@linkplain AdGroupEstimateRequest adgroup estimate
+ requests} across all campaign estimate requests is 50.</p>
+
+ <p>Note that the API returns intervals whereas the Traffic Estimator UI displays averages.
+ Estimates are account specific since they are based on creatives already in the account.
+ When comparing numbers, use the same account for the API and UI.</p>
+ <span class="constraint AdxEnabled">This is disabled for AdX.</span>
+
+
+
+ Returns traffic estimates for specified criteria.
+
+ @param selector Campaigns, ad groups and keywords for which traffic
+ should be estimated.
+ @return Traffic estimation results.
+ @throws ApiException if problems occurred while retrieving estimates
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tests/test_data/unicode_test_data.txt b/tests/test_data/unicode_test_data.txt
new file mode 100644
index 00000000..1c1638de
--- /dev/null
+++ b/tests/test_data/unicode_test_data.txt
@@ -0,0 +1,965 @@
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻
+あいうえおくくくどれみふぁちどけけけすしかかか
+¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿
+あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか
diff --git a/tests/testing.py b/tests/testing.py
new file mode 100644
index 00000000..71d23912
--- /dev/null
+++ b/tests/testing.py
@@ -0,0 +1,33 @@
+# Copyright 2017 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Functions and classes used for unit tests."""
+
+
+import functools
+import unittest
+
+import googleads.common
+
+
+class CleanUtilityRegistryTestCase(unittest.TestCase):
+ """Base class for testing content affecting the UtilityRegistry.
+
+ Subclasses will clear the UtilityRegistry between each test to ensure that it
+ is in a clean state before the next test.
+ """
+
+ def tearDown(self):
+ """Ensures that the UtilityRegistry is cleared between tests."""
+ googleads.common._utility_registry.Clear()
diff --git a/tests/util_test.py b/tests/util_test.py
new file mode 100644
index 00000000..93dcada0
--- /dev/null
+++ b/tests/util_test.py
@@ -0,0 +1,278 @@
+# Copyright 2016 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Unit tests to cover the errors module."""
+
+from contextlib import contextmanager
+import logging
+import os
+import unittest
+
+import googleads.ad_manager
+import googleads.adwords
+import googleads.errors
+import googleads.util
+from lxml import etree
+import mock
+
+
+class PatchesTest(unittest.TestCase):
+ """Tests for the PatchHelper utility."""
+
+ def setUp(self):
+ oauth_header = {'Authorization': 'header'}
+ oauth2_client = mock.Mock()
+ oauth2_client.CreateHttpHeader.return_value = dict(oauth_header)
+
+ # AdWordsClient setup
+ client_customer_id = 'client customer id'
+ dev_token = '?wH47154M4n'
+ user_agent = '4M153rAb13p1l30F53CR37s'
+ self.adwords_client = googleads.adwords.AdWordsClient(
+ dev_token, oauth2_client, user_agent,
+ client_customer_id=client_customer_id)
+ # AdWordsClient setup (compression enabled)
+ self.adwords_client_with_compression = googleads.adwords.AdWordsClient(
+ dev_token, oauth2_client, user_agent,
+ client_customer_id=client_customer_id,
+ enable_compression=True)
+ self.adwords_version = sorted(googleads.adwords._SERVICE_MAP.keys())[-1]
+ self.adwords_namespace_partial = (
+ 'https://adwords.google.com/api/adwords/%s/' + self.adwords_version)
+
+ # AdManagerClient setup
+ network_code = '12345'
+ application_name = 'application name'
+ self.ad_manager_client = googleads.ad_manager.AdManagerClient(
+ oauth2_client, application_name, network_code)
+
+ self.ad_manager_version = sorted(
+ googleads.ad_manager._SERVICE_MAP.keys())[-1]
+ self.ad_manager_namespace = (
+ 'https://www.google.com/apis/ads/publisher/%s'
+ % self.ad_manager_version)
+
+ @contextmanager
+ def mock_fault_response(self, response_file, version):
+ test_dir = os.path.dirname(__file__)
+ with open(os.path.join(test_dir, response_file), 'rb') as handler:
+ response_data = handler.read()
+ response_data = response_data.replace(b'{VERSION}', bytes(version, 'utf-8'))
+
+ with mock.patch('zeep.transports.Transport.post') as mock_post:
+ reply_instance = mock.Mock()
+ reply_instance.status_code = 500
+ reply_instance.headers = {}
+ reply_instance.content = response_data
+ mock_post.return_value = reply_instance
+ yield
+
+ def testSingleErrorListIssue90(self):
+ """Verifies that issue 90 has been resolved with the patch."""
+ query = 'WHERE 1 = 0'
+ statement = googleads.ad_manager.FilterStatement(query)
+ line_item_service = self.ad_manager_client.GetService('LineItemService')
+ line_item_action = {'xsi_type': 'ActivateLineItems'}
+ st = statement.ToStatement()
+ with self.mock_fault_response(
+ 'test_data/fault_response_envelope.txt', self.ad_manager_version):
+ try:
+ line_item_service.performLineItemAction(line_item_action, st)
+ except googleads.errors.GoogleAdsServerFault as e:
+ self.assertEqual(1, len(e.errors))
+
+ def testSingleErrorListIssue90_emptyErrors(self):
+ """Verifies that issue 90 has been resolved with the patch."""
+ query = 'WHERE 1 = 0'
+ statement = googleads.ad_manager.FilterStatement(query)
+ line_item_service = self.ad_manager_client.GetService('LineItemService')
+ line_item_action = {'xsi_type': 'ActivateLineItems'}
+ st = statement.ToStatement()
+
+ with self.mock_fault_response(
+ 'test_data/empty_fault_response_envelope.txt', self.ad_manager_version):
+ try:
+ line_item_service.performLineItemAction(line_item_action, st)
+ except googleads.errors.GoogleAdsServerFault as e:
+ self.assertEqual(0, len(e.errors))
+
+ def testSingleErrorListIssue90_multipleErrors(self):
+ """Verifies that issue 90 has been resolved with the patch."""
+ query = 'WHERE 1 = 0'
+ statement = googleads.ad_manager.FilterStatement(query)
+ line_item_service = self.ad_manager_client.GetService('LineItemService')
+ line_item_action = {'xsi_type': 'ActivateLineItems'}
+ st = statement.ToStatement()
+
+ with self.mock_fault_response(
+ 'test_data/multi_errors_fault_response_envelope.txt',
+ self.ad_manager_version):
+ try:
+ line_item_service.performLineItemAction(line_item_action, st)
+ except googleads.errors.GoogleAdsServerFault as e:
+ self.assertEqual(2, len(e.errors))
+
+
+class GoogleAdsCommonFilterTest(unittest.TestCase):
+ """Tests for the GoogleAdsCommonFilter utility."""
+
+ def setUp(self):
+ self.filter = googleads.util.GetGoogleAdsCommonFilter()
+ self.redacted_text = 'REDACTED'
+ self.dev_token_template = ('%s')
+
+ def testGetGoogleAdsCommonFilter(self):
+ self.assertIs(self.filter, googleads.util.GetGoogleAdsCommonFilter())
+
+ def testFilterAtInfoLevel(self):
+ record = mock.Mock()
+ record.levelno = logging.INFO
+ doc = mock.Mock()
+ doc.str.return_value = self.dev_token_template % 'test'
+
+ record.args = [doc]
+ self.filter.filter(record)
+ self.assertEqual(
+ record.args, (self.dev_token_template % self.redacted_text,))
+
+ def testFilterAtUnfilteredLevel(self):
+ expected_args = (1, 2, 3, 4, 5)
+ record = mock.Mock()
+ record.levelno = logging.DEBUG
+ record.args = expected_args
+ self.filter.filter(record)
+ self.assertEqual(record.args, expected_args)
+
+
+XML_WITH_DEV_TOKEN = (
+ ''
+ 'a token'
+ 'hi'
+ '')
+XML_WITH_DEV_TOKEN_SAFE = etree.fromstring(
+ XML_WITH_DEV_TOKEN.replace('a token', 'REDACTED'))
+XML_WITH_DEV_TOKEN = etree.fromstring(XML_WITH_DEV_TOKEN)
+XML_PRETTY = etree.tostring(XML_WITH_DEV_TOKEN, pretty_print=True)
+XML_PRETTY_SAFE = etree.tostring(XML_WITH_DEV_TOKEN_SAFE, pretty_print=True)
+XML_PRETTY_SAFE = XML_PRETTY_SAFE.decode('utf-8')
+XML_WITH_FAULT = etree.fromstring(
+ ''
+ ''
+ 'value'
+ ''
+ ''
+ 'hi'
+ ''
+ '')
+
+ZEEP_HEADER = {'abc': 'hi', 'authorization': 'secret'}
+ZEEP_HEADER_SAFE = ZEEP_HEADER.copy()
+ZEEP_HEADER_SAFE['authorization'] = 'REDACTED'
+BINDING_OPTIONS = {'address': 'myaddress'}
+
+
+class ZeepLoggerTest(unittest.TestCase):
+
+ def setUp(self):
+ self.logger = mock.Mock()
+ self.zeep_logger = googleads.util.ZeepLogger()
+ self.zeep_logger._logger = self.logger
+ self.operation = mock.Mock()
+ self.operation.name = 'opname'
+ self.operation.binding.wsdl.services.keys.return_value = ['service_name']
+
+ def enable_log_levels(self, *levels):
+ self.logger.isEnabledFor.side_effect = lambda lvl: lvl in levels
+
+ def testIngressPassesThroughArguments(self):
+ self.enable_log_levels()
+
+ # This result isn't related to logging, just confirming that the plugin
+ # is passing along the data unmodified.
+ result = self.zeep_logger.ingress(
+ XML_WITH_DEV_TOKEN, ZEEP_HEADER, self.operation)
+
+ self.assertEqual(result, (XML_WITH_DEV_TOKEN, ZEEP_HEADER))
+
+ def testIngressNoLoggingByDefault(self):
+ self.enable_log_levels()
+
+ self.zeep_logger.ingress(
+ XML_WITH_DEV_TOKEN, ZEEP_HEADER, self.operation)
+
+ self.logger.debug.assert_not_called()
+
+ def testIngressDebugLogging(self):
+ self.enable_log_levels(logging.DEBUG)
+
+ # Re-using the XML with for convenience, but this
+ # is testing inbound data, which would not have anything sensitive in it.
+ self.zeep_logger.ingress(
+ XML_WITH_DEV_TOKEN, ZEEP_HEADER, self.operation)
+
+ self.logger.debug.assert_called_once_with(
+ googleads.util._RESPONSE_XML_LOG_LINE, XML_PRETTY)
+
+ def testIngressFaultLogging(self):
+ self.enable_log_levels(logging.WARN)
+
+ self.zeep_logger.ingress(
+ XML_WITH_FAULT, ZEEP_HEADER, self.operation)
+
+ self.assertEqual({'faultMessage': 'hi',
+ 'key': 'value',
+ 'methodName': 'opname',
+ 'serviceName': 'service_name'},
+ self.logger.warn.mock_calls[0][1][1])
+
+ def testEgressPassesThroughArguments(self):
+ self.enable_log_levels()
+
+ self.enable_log_levels(logging.DEBUG)
+
+ # This result isn't related to logging, just confirming that the plugin
+ # is passing along the data unmodified.
+ result = self.zeep_logger.egress(
+ XML_WITH_DEV_TOKEN, ZEEP_HEADER, self.operation, BINDING_OPTIONS)
+
+ self.assertEqual(result, (XML_WITH_DEV_TOKEN, ZEEP_HEADER))
+
+ def testEgressNoLoggingByDefault(self):
+ self.enable_log_levels()
+
+ self.zeep_logger.egress(
+ XML_WITH_DEV_TOKEN, ZEEP_HEADER, self.operation, BINDING_OPTIONS)
+
+ self.logger.debug.assert_not_called()
+
+ def testEgressDebugLogging(self):
+ self.enable_log_levels(logging.DEBUG)
+ self.zeep_logger.egress(
+ XML_WITH_DEV_TOKEN, ZEEP_HEADER, self.operation, BINDING_OPTIONS)
+
+ # With egress, they should be redacted.
+ self.logger.debug.assert_called_once_with(
+ googleads.util._REQUEST_XML_LOG_LINE, ZEEP_HEADER_SAFE, XML_PRETTY_SAFE)
+
+ def testEgressInfoLogging(self):
+ self.enable_log_levels(logging.INFO)
+ self.zeep_logger.egress(
+ XML_WITH_DEV_TOKEN, ZEEP_HEADER, self.operation, BINDING_OPTIONS)
+
+ self.logger.info.assert_called_once_with(
+ googleads.util._REQUEST_LOG_LINE, 'service_name', 'opname', 'myaddress')
+
+
+if __name__ == '__main__':
+ unittest.main()