Skip to content

Commit 444f919

Browse files
authored
Fix issues with async services per #1045 (#1046)
1 parent 8f47b17 commit 444f919

File tree

12 files changed

+1992
-13
lines changed

12 files changed

+1992
-13
lines changed
Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
1+
#!/usr/bin/env python
2+
# Copyright 2018 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 add a campaign using asyncio."""
16+
17+
18+
import argparse
19+
import asyncio
20+
import datetime
21+
import sys
22+
from typing import List
23+
import uuid
24+
25+
from google.ads.googleads.client import GoogleAdsClient
26+
from google.ads.googleads.errors import GoogleAdsException
27+
from google.ads.googleads.v22.services.services.campaign_budget_service import (
28+
CampaignBudgetServiceClient,
29+
)
30+
from google.ads.googleads.v22.services.types.campaign_budget_service import (
31+
CampaignBudgetOperation,
32+
MutateCampaignBudgetsResponse,
33+
)
34+
from google.ads.googleads.v22.services.services.campaign_service import (
35+
CampaignServiceClient,
36+
)
37+
from google.ads.googleads.v22.services.types.campaign_service import (
38+
CampaignOperation,
39+
MutateCampaignsResponse,
40+
)
41+
from google.ads.googleads.v22.resources.types.campaign_budget import (
42+
CampaignBudget,
43+
)
44+
from google.ads.googleads.v22.resources.types.campaign import Campaign
45+
46+
47+
_DATE_FORMAT: str = "%Y%m%d"
48+
49+
50+
async def main(client: GoogleAdsClient, customer_id: str) -> None:
51+
campaign_budget_service: CampaignBudgetServiceClient = client.get_service(
52+
"CampaignBudgetService", is_async=True
53+
)
54+
campaign_service: CampaignServiceClient = client.get_service(
55+
"CampaignService", is_async=True
56+
)
57+
58+
# Create a budget, which can be shared by multiple campaigns.
59+
campaign_budget_operation: CampaignBudgetOperation = client.get_type(
60+
"CampaignBudgetOperation"
61+
)
62+
campaign_budget: CampaignBudget = campaign_budget_operation.create
63+
campaign_budget.name = f"Interplanetary Budget {uuid.uuid4()}"
64+
campaign_budget.delivery_method = (
65+
client.enums.BudgetDeliveryMethodEnum.STANDARD
66+
)
67+
campaign_budget.amount_micros = 500000
68+
69+
# Add budget.
70+
budget_operations: List[CampaignBudgetOperation] = [
71+
campaign_budget_operation
72+
]
73+
campaign_budget_response: MutateCampaignBudgetsResponse = (
74+
await campaign_budget_service.mutate_campaign_budgets(
75+
customer_id=customer_id,
76+
operations=budget_operations,
77+
)
78+
)
79+
80+
# Create campaign.
81+
campaign_operation: CampaignOperation = client.get_type("CampaignOperation")
82+
campaign: Campaign = campaign_operation.create
83+
campaign.name = f"Interplanetary Cruise {uuid.uuid4()}"
84+
campaign.advertising_channel_type = (
85+
client.enums.AdvertisingChannelTypeEnum.SEARCH
86+
)
87+
88+
# Recommendation: Set the campaign to PAUSED when creating it to prevent
89+
# the ads from immediately serving. Set to ENABLED once you've added
90+
# targeting and the ads are ready to serve.
91+
campaign.status = client.enums.CampaignStatusEnum.PAUSED
92+
93+
# Set the bidding strategy and budget.
94+
campaign.manual_cpc = client.get_type("ManualCpc")
95+
campaign.campaign_budget = campaign_budget_response.results[0].resource_name
96+
97+
# Set the campaign network options.
98+
campaign.network_settings.target_google_search = True
99+
campaign.network_settings.target_search_network = True
100+
campaign.network_settings.target_partner_search_network = False
101+
# Enable Display Expansion on Search campaigns. For more details see:
102+
# https://support.google.com/google-ads/answer/7193800
103+
campaign.network_settings.target_content_network = True
104+
105+
# Declare whether or not this campaign serves political ads targeting the
106+
# EU. Valid values are:
107+
# CONTAINS_EU_POLITICAL_ADVERTISING
108+
# DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING
109+
campaign.contains_eu_political_advertising = (
110+
client.enums.EuPoliticalAdvertisingStatusEnum.DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING
111+
)
112+
113+
# Optional: Set the start date.
114+
start_time: datetime.date = datetime.date.today() + datetime.timedelta(
115+
days=1
116+
)
117+
campaign.start_date = datetime.date.strftime(start_time, _DATE_FORMAT)
118+
119+
# Optional: Set the end date.
120+
end_time: datetime.date = start_time + datetime.timedelta(weeks=4)
121+
campaign.end_date = datetime.date.strftime(end_time, _DATE_FORMAT)
122+
# [END add_campaigns_1]
123+
124+
# Add the campaign.
125+
campaign_operations: List[CampaignOperation] = [campaign_operation]
126+
campaign_response: MutateCampaignsResponse = await campaign_service.mutate_campaigns(
127+
customer_id=customer_id, operations=campaign_operations
128+
)
129+
print(f"Created campaign {campaign_response.results[0].resource_name}.")
130+
131+
132+
if __name__ == "__main__":
133+
parser = argparse.ArgumentParser(
134+
description="Adds a campaign for specified customer."
135+
)
136+
# The following argument(s) should be provided to run the example.
137+
parser.add_argument(
138+
"-c",
139+
"--customer_id",
140+
type=str,
141+
required=True,
142+
help="The Google Ads customer ID.",
143+
)
144+
args: argparse.Namespace = parser.parse_args()
145+
146+
# GoogleAdsClient will read the google-ads.yaml configuration file in the
147+
# home directory if none is specified.
148+
googleads_client: GoogleAdsClient = GoogleAdsClient.load_from_storage(
149+
version="v22"
150+
)
151+
152+
try:
153+
asyncio.run(main(googleads_client, args.customer_id))
154+
except GoogleAdsException as ex:
155+
print(
156+
f'Request with ID "{ex.request_id}" failed with status '
157+
f'"{ex.error.code().name}" and includes the following errors:'
158+
)
159+
for error in ex.failure.errors:
160+
print(f'\tError with message "{error.message}".')
161+
if error.location:
162+
for field_path_element in error.location.field_path_elements:
163+
print(f"\t\tOn field: {field_path_element.field_name}")
164+
sys.exit(1)

examples/asyncio/async_search.py

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
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 using asyncio."""
16+
17+
18+
import argparse
19+
import asyncio
20+
import sys
21+
from typing import List
22+
23+
from google.ads.googleads.client import GoogleAdsClient
24+
from google.ads.googleads.errors import GoogleAdsException
25+
from google.ads.googleads.v22.services.services.google_ads_service import (
26+
GoogleAdsServiceAsyncClient,
27+
)
28+
from google.ads.googleads.v22.services.types.google_ads_service import (
29+
GoogleAdsRow,
30+
)
31+
32+
33+
async def main(client: GoogleAdsClient, customer_id: str) -> None:
34+
ga_service: GoogleAdsServiceAsyncClient = client.get_service(
35+
"GoogleAdsService", is_async=True
36+
)
37+
38+
query: str = """
39+
SELECT
40+
campaign.id,
41+
campaign.name
42+
FROM campaign
43+
ORDER BY campaign.id
44+
LIMIT 10"""
45+
46+
# Issues a search request using streaming.
47+
stream = await ga_service.search(
48+
customer_id=customer_id, query=query
49+
)
50+
51+
async for row in stream:
52+
print(
53+
f"Campaign with ID {row.campaign.id} and name "
54+
f'"{row.campaign.name}" was found.'
55+
)
56+
57+
58+
if __name__ == "__main__":
59+
parser = argparse.ArgumentParser(
60+
description="Lists all campaigns for specified customer using asyncio."
61+
)
62+
# The following argument(s) should be provided to run the example.
63+
parser.add_argument(
64+
"-c",
65+
"--customer_id",
66+
type=str,
67+
required=True,
68+
help="The Google Ads customer ID.",
69+
)
70+
args: argparse.Namespace = parser.parse_args()
71+
72+
# GoogleAdsClient will read the google-ads.yaml configuration file in the
73+
# home directory if none is specified.
74+
googleads_client: GoogleAdsClient = GoogleAdsClient.load_from_storage(
75+
version="v22"
76+
)
77+
78+
try:
79+
asyncio.run(main(googleads_client, args.customer_id))
80+
except GoogleAdsException as ex:
81+
print(
82+
f'Request with ID "{ex.request_id}" failed with status '
83+
f'"{ex.error.code().name}" and includes the following errors:'
84+
)
85+
for error in ex.failure.errors:
86+
print(f'\tError with message "{error.message}".')
87+
if error.location:
88+
for field_path_element in error.location.field_path_elements:
89+
print(f"\t\tOn field: {field_path_element.field_name}")
90+
sys.exit(1)
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
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 using asyncio."""
16+
17+
18+
import argparse
19+
import asyncio
20+
import sys
21+
from typing import List
22+
23+
from google.ads.googleads.client import GoogleAdsClient
24+
from google.ads.googleads.errors import GoogleAdsException
25+
from google.ads.googleads.v22.services.services.google_ads_service import (
26+
GoogleAdsServiceAsyncClient,
27+
)
28+
from google.ads.googleads.v22.services.types.google_ads_service import (
29+
GoogleAdsRow,
30+
)
31+
32+
33+
async def main(client: GoogleAdsClient, customer_id: str) -> None:
34+
ga_service: GoogleAdsServiceAsyncClient = client.get_service(
35+
"GoogleAdsService", is_async=True
36+
)
37+
38+
query: str = """
39+
SELECT
40+
campaign.id,
41+
campaign.name
42+
FROM campaign
43+
ORDER BY campaign.id
44+
LIMIT 10"""
45+
46+
# Issues a search request using streaming.
47+
stream = await ga_service.search_stream(
48+
customer_id=customer_id, query=query
49+
)
50+
51+
async for batch in stream:
52+
for row in batch.results:
53+
print(
54+
f"Campaign with ID {row.campaign.id} and name "
55+
f'"{row.campaign.name}" was found.'
56+
)
57+
58+
59+
if __name__ == "__main__":
60+
parser = argparse.ArgumentParser(
61+
description="Lists all campaigns for specified customer using asyncio."
62+
)
63+
# The following argument(s) should be provided to run the example.
64+
parser.add_argument(
65+
"-c",
66+
"--customer_id",
67+
type=str,
68+
required=True,
69+
help="The Google Ads customer ID.",
70+
)
71+
args: argparse.Namespace = parser.parse_args()
72+
73+
# GoogleAdsClient will read the google-ads.yaml configuration file in the
74+
# home directory if none is specified.
75+
googleads_client: GoogleAdsClient = GoogleAdsClient.load_from_storage(
76+
version="v22"
77+
)
78+
79+
try:
80+
asyncio.run(main(googleads_client, args.customer_id))
81+
except GoogleAdsException as ex:
82+
print(
83+
f'Request with ID "{ex.request_id}" failed with status '
84+
f'"{ex.error.code().name}" and includes the following errors:'
85+
)
86+
for error in ex.failure.errors:
87+
print(f'\tError with message "{error.message}".')
88+
if error.location:
89+
for field_path_element in error.location.field_path_elements:
90+
print(f"\t\tOn field: {field_path_element.field_name}")
91+
sys.exit(1)

0 commit comments

Comments
 (0)