get_campaign.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #!/usr/bin/env python
  2. # Copyright 2020 Google LLC
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # https://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """This example illustrates how to get all campaigns.
  16. To add campaigns, run add_campaigns.py.
  17. """
  18. import argparse
  19. import sys
  20. from google.ads.googleads.client import GoogleAdsClient
  21. from google.ads.googleads.errors import GoogleAdsException
  22. def main(client, customer_id):
  23. ga_service = client.get_service("GoogleAdsService")
  24. query = """
  25. SELECT
  26. campaign.id,
  27. campaign.name
  28. FROM campaign
  29. ORDER BY campaign.id"""
  30. # Issues a search request using streaming.
  31. stream = ga_service.search_stream(customer_id=customer_id, query=query)
  32. for batch in stream:
  33. for row in batch.results:
  34. print(
  35. f"Campaign with ID {row.campaign.id} and name "
  36. f'"{row.campaign.name}" was found.'
  37. )
  38. if __name__ == "__main__":
  39. # GoogleAdsClient will read the google-ads.yaml configuration file in the
  40. # home directory if none is specified.
  41. # googleads_client = GoogleAdsClient.load_from_storage(version="v10")
  42. googleads_client = GoogleAdsClient.load_from_storage(r"c:\gitlab\kw_tools\kw_tools\google-ads\google-ads.yaml",version="v10")
  43. parser = argparse.ArgumentParser(
  44. description="Lists all campaigns for specified customer."
  45. )
  46. # The following argument(s) should be provided to run the example.
  47. parser.add_argument(
  48. "-c",
  49. "--customer_id",
  50. type=str,
  51. required=True,
  52. help="The Google Ads customer ID.",
  53. )
  54. args = parser.parse_args()
  55. try:
  56. main(googleads_client, args.customer_id)
  57. except GoogleAdsException as ex:
  58. print(
  59. f'Request with ID "{ex.request_id}" failed with status '
  60. f'"{ex.error.code().name}" and includes the following errors:'
  61. )
  62. for error in ex.failure.errors:
  63. print(f'\tError with message "{error.message}".')
  64. if error.location:
  65. for field_path_element in error.location.field_path_elements:
  66. print(f"\t\tOn field: {field_path_element.field_name}")
  67. sys.exit(1)