diff --git a/librarian.yaml b/librarian.yaml index b2514a42b804..dd76883cd0be 100644 --- a/librarian.yaml +++ b/librarian.yaml @@ -16,8 +16,8 @@ version: v0.30.0 repo: googleapis/google-cloud-python sources: googleapis: - commit: fe04226e3d76435acbfd3ffb51f6771740e1fb5b - sha256: e99c641a9c5525394de43c762b9db50c3ada1f219d6dbdba594ae992fbe1d838 + commit: ede8b2e652dc3716b544205ef772b39b86e3d2cb + sha256: 8f7c17af87f6215012010dddaffec3aa5df5668bf0def727577bc0bc6b698193 default: output: packages tag_format: '{name}-v{version}' diff --git a/packages/google-ads-admanager/docs/admanager_v1/ad_rule_service.rst b/packages/google-ads-admanager/docs/admanager_v1/ad_rule_service.rst new file mode 100644 index 000000000000..c4799d113db7 --- /dev/null +++ b/packages/google-ads-admanager/docs/admanager_v1/ad_rule_service.rst @@ -0,0 +1,10 @@ +AdRuleService +------------------------------- + +.. automodule:: google.ads.admanager_v1.services.ad_rule_service + :members: + :inherited-members: + +.. automodule:: google.ads.admanager_v1.services.ad_rule_service.pagers + :members: + :inherited-members: diff --git a/packages/google-ads-admanager/docs/admanager_v1/ad_spot_service.rst b/packages/google-ads-admanager/docs/admanager_v1/ad_spot_service.rst new file mode 100644 index 000000000000..3e99e55933d1 --- /dev/null +++ b/packages/google-ads-admanager/docs/admanager_v1/ad_spot_service.rst @@ -0,0 +1,10 @@ +AdSpotService +------------------------------- + +.. automodule:: google.ads.admanager_v1.services.ad_spot_service + :members: + :inherited-members: + +.. automodule:: google.ads.admanager_v1.services.ad_spot_service.pagers + :members: + :inherited-members: diff --git a/packages/google-ads-admanager/docs/admanager_v1/cdn_config_service.rst b/packages/google-ads-admanager/docs/admanager_v1/cdn_config_service.rst new file mode 100644 index 000000000000..7bc351e7b06b --- /dev/null +++ b/packages/google-ads-admanager/docs/admanager_v1/cdn_config_service.rst @@ -0,0 +1,10 @@ +CdnConfigService +---------------------------------- + +.. automodule:: google.ads.admanager_v1.services.cdn_config_service + :members: + :inherited-members: + +.. automodule:: google.ads.admanager_v1.services.cdn_config_service.pagers + :members: + :inherited-members: diff --git a/packages/google-ads-admanager/docs/admanager_v1/creative_set_service.rst b/packages/google-ads-admanager/docs/admanager_v1/creative_set_service.rst new file mode 100644 index 000000000000..b4d6c8438d94 --- /dev/null +++ b/packages/google-ads-admanager/docs/admanager_v1/creative_set_service.rst @@ -0,0 +1,10 @@ +CreativeSetService +------------------------------------ + +.. automodule:: google.ads.admanager_v1.services.creative_set_service + :members: + :inherited-members: + +.. automodule:: google.ads.admanager_v1.services.creative_set_service.pagers + :members: + :inherited-members: diff --git a/packages/google-ads-admanager/docs/admanager_v1/live_stream_service.rst b/packages/google-ads-admanager/docs/admanager_v1/live_stream_service.rst new file mode 100644 index 000000000000..ebae4ac520c4 --- /dev/null +++ b/packages/google-ads-admanager/docs/admanager_v1/live_stream_service.rst @@ -0,0 +1,10 @@ +LiveStreamService +----------------------------------- + +.. automodule:: google.ads.admanager_v1.services.live_stream_service + :members: + :inherited-members: + +.. automodule:: google.ads.admanager_v1.services.live_stream_service.pagers + :members: + :inherited-members: diff --git a/packages/google-ads-admanager/docs/admanager_v1/services_.rst b/packages/google-ads-admanager/docs/admanager_v1/services_.rst index 2f5e87aff11a..6ee9d4b7896e 100644 --- a/packages/google-ads-admanager/docs/admanager_v1/services_.rst +++ b/packages/google-ads-admanager/docs/admanager_v1/services_.rst @@ -5,12 +5,15 @@ Services for Google Ads Admanager v1 API ad_break_service ad_review_center_ad_service + ad_rule_service + ad_spot_service ad_unit_service application_service audience_segment_service bandwidth_group_service browser_language_service browser_service + cdn_config_service cms_metadata_key_service cms_metadata_value_service company_service @@ -18,6 +21,7 @@ Services for Google Ads Admanager v1 API content_bundle_service content_label_service content_service + creative_set_service creative_template_service custom_field_service custom_targeting_key_service @@ -30,6 +34,7 @@ Services for Google Ads Admanager v1 API label_service line_item_service linked_device_service + live_stream_service mcm_earnings_service mobile_carrier_service mobile_device_service @@ -46,6 +51,10 @@ Services for Google Ads Admanager v1 API rich_media_ads_company_service role_service site_service + slate_service + suggested_ad_unit_service + targeting_preset_service taxonomy_category_service team_service + third_party_company_service user_service diff --git a/packages/google-ads-admanager/docs/admanager_v1/slate_service.rst b/packages/google-ads-admanager/docs/admanager_v1/slate_service.rst new file mode 100644 index 000000000000..f7f416128bdf --- /dev/null +++ b/packages/google-ads-admanager/docs/admanager_v1/slate_service.rst @@ -0,0 +1,10 @@ +SlateService +------------------------------ + +.. automodule:: google.ads.admanager_v1.services.slate_service + :members: + :inherited-members: + +.. automodule:: google.ads.admanager_v1.services.slate_service.pagers + :members: + :inherited-members: diff --git a/packages/google-ads-admanager/docs/admanager_v1/suggested_ad_unit_service.rst b/packages/google-ads-admanager/docs/admanager_v1/suggested_ad_unit_service.rst new file mode 100644 index 000000000000..6314f0d0421f --- /dev/null +++ b/packages/google-ads-admanager/docs/admanager_v1/suggested_ad_unit_service.rst @@ -0,0 +1,10 @@ +SuggestedAdUnitService +---------------------------------------- + +.. automodule:: google.ads.admanager_v1.services.suggested_ad_unit_service + :members: + :inherited-members: + +.. automodule:: google.ads.admanager_v1.services.suggested_ad_unit_service.pagers + :members: + :inherited-members: diff --git a/packages/google-ads-admanager/docs/admanager_v1/targeting_preset_service.rst b/packages/google-ads-admanager/docs/admanager_v1/targeting_preset_service.rst new file mode 100644 index 000000000000..3e0d5821a824 --- /dev/null +++ b/packages/google-ads-admanager/docs/admanager_v1/targeting_preset_service.rst @@ -0,0 +1,10 @@ +TargetingPresetService +---------------------------------------- + +.. automodule:: google.ads.admanager_v1.services.targeting_preset_service + :members: + :inherited-members: + +.. automodule:: google.ads.admanager_v1.services.targeting_preset_service.pagers + :members: + :inherited-members: diff --git a/packages/google-ads-admanager/docs/admanager_v1/third_party_company_service.rst b/packages/google-ads-admanager/docs/admanager_v1/third_party_company_service.rst new file mode 100644 index 000000000000..a97a3ef3d6fd --- /dev/null +++ b/packages/google-ads-admanager/docs/admanager_v1/third_party_company_service.rst @@ -0,0 +1,10 @@ +ThirdPartyCompanyService +------------------------------------------ + +.. automodule:: google.ads.admanager_v1.services.third_party_company_service + :members: + :inherited-members: + +.. automodule:: google.ads.admanager_v1.services.third_party_company_service.pagers + :members: + :inherited-members: diff --git a/packages/google-ads-admanager/google/ads/admanager/__init__.py b/packages/google-ads-admanager/google/ads/admanager/__init__.py index 73276c9d2e0a..c99204e7be11 100644 --- a/packages/google-ads-admanager/google/ads/admanager/__init__.py +++ b/packages/google-ads-admanager/google/ads/admanager/__init__.py @@ -24,6 +24,8 @@ from google.ads.admanager_v1.services.ad_review_center_ad_service.client import ( AdReviewCenterAdServiceClient, ) +from google.ads.admanager_v1.services.ad_rule_service.client import AdRuleServiceClient +from google.ads.admanager_v1.services.ad_spot_service.client import AdSpotServiceClient from google.ads.admanager_v1.services.ad_unit_service.client import AdUnitServiceClient from google.ads.admanager_v1.services.application_service.client import ( ApplicationServiceClient, @@ -38,6 +40,9 @@ BrowserLanguageServiceClient, ) from google.ads.admanager_v1.services.browser_service.client import BrowserServiceClient +from google.ads.admanager_v1.services.cdn_config_service.client import ( + CdnConfigServiceClient, +) from google.ads.admanager_v1.services.cms_metadata_key_service.client import ( CmsMetadataKeyServiceClient, ) @@ -53,6 +58,9 @@ ContentLabelServiceClient, ) from google.ads.admanager_v1.services.content_service.client import ContentServiceClient +from google.ads.admanager_v1.services.creative_set_service.client import ( + CreativeSetServiceClient, +) from google.ads.admanager_v1.services.creative_template_service.client import ( CreativeTemplateServiceClient, ) @@ -87,6 +95,9 @@ from google.ads.admanager_v1.services.linked_device_service.client import ( LinkedDeviceServiceClient, ) +from google.ads.admanager_v1.services.live_stream_service.client import ( + LiveStreamServiceClient, +) from google.ads.admanager_v1.services.mcm_earnings_service.client import ( McmEarningsServiceClient, ) @@ -125,10 +136,20 @@ ) from google.ads.admanager_v1.services.role_service.client import RoleServiceClient from google.ads.admanager_v1.services.site_service.client import SiteServiceClient +from google.ads.admanager_v1.services.slate_service.client import SlateServiceClient +from google.ads.admanager_v1.services.suggested_ad_unit_service.client import ( + SuggestedAdUnitServiceClient, +) +from google.ads.admanager_v1.services.targeting_preset_service.client import ( + TargetingPresetServiceClient, +) from google.ads.admanager_v1.services.taxonomy_category_service.client import ( TaxonomyCategoryServiceClient, ) from google.ads.admanager_v1.services.team_service.client import TeamServiceClient +from google.ads.admanager_v1.services.third_party_company_service.client import ( + ThirdPartyCompanyServiceClient, +) from google.ads.admanager_v1.services.user_service.client import UserServiceClient from google.ads.admanager_v1.types.ad_break_messages import AdBreak from google.ads.admanager_v1.types.ad_break_service import ( @@ -153,6 +174,49 @@ SearchAdReviewCenterAdsRequest, SearchAdReviewCenterAdsResponse, ) +from google.ads.admanager_v1.types.ad_rule_enums import ( + AdRuleFrequencyCapBehaviorEnum, + AdRuleStatusEnum, +) +from google.ads.admanager_v1.types.ad_rule_messages import AdRule, AdRuleSlot +from google.ads.admanager_v1.types.ad_rule_service import ( + BatchActivateAdRulesRequest, + BatchActivateAdRulesResponse, + BatchCreateAdRulesRequest, + BatchCreateAdRulesResponse, + BatchDeactivateAdRulesRequest, + BatchDeactivateAdRulesResponse, + BatchDeleteAdRulesRequest, + BatchUpdateAdRulesRequest, + BatchUpdateAdRulesResponse, + CreateAdRuleRequest, + GetAdRuleRequest, + ListAdRulesRequest, + ListAdRulesResponse, + UpdateAdRuleRequest, +) +from google.ads.admanager_v1.types.ad_rule_slot_behavior_enum import ( + AdRuleSlotBehaviorEnum, +) +from google.ads.admanager_v1.types.ad_rule_slot_bumper_enum import AdRuleSlotBumperEnum +from google.ads.admanager_v1.types.ad_rule_slot_midroll_frequency_type_enum import ( + AdRuleSlotMidrollFrequencyTypeEnum, +) +from google.ads.admanager_v1.types.ad_spot_messages import AdSpot +from google.ads.admanager_v1.types.ad_spot_service import ( + BatchCreateAdSpotsRequest, + BatchCreateAdSpotsResponse, + BatchUpdateAdSpotsRequest, + BatchUpdateAdSpotsResponse, + CreateAdSpotRequest, + GetAdSpotRequest, + ListAdSpotsRequest, + ListAdSpotsResponse, + UpdateAdSpotRequest, +) +from google.ads.admanager_v1.types.ad_spot_targeting_type_enum import ( + AdSpotTargetingTypeEnum, +) from google.ads.admanager_v1.types.ad_unit_enums import ( AdUnitStatusEnum, SmartSizeModeEnum, @@ -219,6 +283,7 @@ ListBandwidthGroupsRequest, ListBandwidthGroupsResponse, ) +from google.ads.admanager_v1.types.brand_lift_partner_enum import BrandLiftPartnerEnum from google.ads.admanager_v1.types.browser_language_messages import BrowserLanguage from google.ads.admanager_v1.types.browser_language_service import ( GetBrowserLanguageRequest, @@ -231,6 +296,39 @@ ListBrowsersRequest, ListBrowsersResponse, ) +from google.ads.admanager_v1.types.cdn_config_messages import ( + AdMediaDeliveryConfig, + CdnConfig, + CdnSecurityPolicy, + MediaLocation, + SourceContentConfig, +) +from google.ads.admanager_v1.types.cdn_config_service import ( + BatchActivateCdnConfigsRequest, + BatchActivateCdnConfigsResponse, + BatchArchiveCdnConfigsRequest, + BatchArchiveCdnConfigsResponse, + BatchCreateCdnConfigsRequest, + BatchCreateCdnConfigsResponse, + BatchUpdateCdnConfigsRequest, + BatchUpdateCdnConfigsResponse, + CreateCdnConfigRequest, + GetCdnConfigRequest, + ListCdnConfigsRequest, + ListCdnConfigsResponse, + UpdateCdnConfigRequest, +) +from google.ads.admanager_v1.types.cdn_config_status_enum import CdnConfigStatusEnum +from google.ads.admanager_v1.types.cdn_config_type_enum import CdnConfigTypeEnum +from google.ads.admanager_v1.types.cdn_security_policy_enum import ( + CdnSecurityPolicyTypeEnum, +) +from google.ads.admanager_v1.types.cdn_security_policy_origin_forwarding_enum import ( + CdnSecurityPolicyOriginForwardingEnum, +) +from google.ads.admanager_v1.types.child_content_eligibility_enum import ( + ChildContentEligibilityEnum, +) from google.ads.admanager_v1.types.child_publisher_messages import ChildPublisher from google.ads.admanager_v1.types.cms_metadata_key_enums import ( CmsMetadataKeyStatusEnum, @@ -281,24 +379,53 @@ ListContactsResponse, UpdateContactRequest, ) +from google.ads.admanager_v1.types.content_bundle_enums import ContentBundleStatusEnum from google.ads.admanager_v1.types.content_bundle_messages import ContentBundle from google.ads.admanager_v1.types.content_bundle_service import ( + BatchActivateContentBundlesRequest, + BatchActivateContentBundlesResponse, + BatchDeactivateContentBundlesRequest, + BatchDeactivateContentBundlesResponse, GetContentBundleRequest, ListContentBundlesRequest, ListContentBundlesResponse, ) +from google.ads.admanager_v1.types.content_enums import ( + ContentStatusEnum, + ContentStatusSourceEnum, + DaiIngestErrorReasonEnum, + DaiIngestStatusEnum, +) from google.ads.admanager_v1.types.content_label_messages import ContentLabel from google.ads.admanager_v1.types.content_label_service import ( GetContentLabelRequest, ListContentLabelsRequest, ListContentLabelsResponse, ) -from google.ads.admanager_v1.types.content_messages import Content +from google.ads.admanager_v1.types.content_messages import ( + CmsContent, + Content, + DaiIngestError, +) from google.ads.admanager_v1.types.content_service import ( GetContentRequest, ListContentRequest, ListContentResponse, ) +from google.ads.admanager_v1.types.creative_messages import Creative +from google.ads.admanager_v1.types.creative_placeholder import ( + CreativePlaceholder, + CreativePlaceholderCompanion, +) +from google.ads.admanager_v1.types.creative_set_messages import CreativeSet +from google.ads.admanager_v1.types.creative_set_service import ( + CreateCreativeSetRequest, + GetCreativeSetRequest, + ListCreativeSetsRequest, + ListCreativeSetsResponse, + UpdateCreativeSetRequest, +) +from google.ads.admanager_v1.types.creative_targeting import CreativeTargeting from google.ads.admanager_v1.types.creative_template_enums import ( CreativeTemplateStatusEnum, CreativeTemplateTypeEnum, @@ -341,6 +468,13 @@ UpdateCustomFieldRequest, ) from google.ads.admanager_v1.types.custom_field_value import CustomFieldValue +from google.ads.admanager_v1.types.custom_pacing_curve import ( + CustomPacingCurve, + CustomPacingGoal, +) +from google.ads.admanager_v1.types.custom_pacing_goal_unit_enum import ( + CustomPacingGoalUnitEnum, +) from google.ads.admanager_v1.types.custom_targeting_key_enums import ( CustomTargetingKeyReportableTypeEnum, CustomTargetingKeyStatusEnum, @@ -372,13 +506,33 @@ CustomTargetingValue, ) from google.ads.admanager_v1.types.custom_targeting_value_service import ( + ActivateCustomTargetingValueRequest, + BatchActivateCustomTargetingValuesRequest, + BatchActivateCustomTargetingValuesResponse, + BatchCreateCustomTargetingValuesRequest, + BatchCreateCustomTargetingValuesResponse, + BatchDeactivateCustomTargetingValuesRequest, + BatchDeactivateCustomTargetingValuesResponse, + BatchUpdateCustomTargetingValuesRequest, + BatchUpdateCustomTargetingValuesResponse, + CreateCustomTargetingValueRequest, + DeactivateCustomTargetingValueRequest, GetCustomTargetingValueRequest, ListCustomTargetingValuesRequest, ListCustomTargetingValuesResponse, + UpdateCustomTargetingValueRequest, ) from google.ads.admanager_v1.types.deal_buyer_permission_type_enum import ( DealBuyerPermissionTypeEnum, ) +from google.ads.admanager_v1.types.deal_priority_tier_enum import DealPriorityTierEnum +from google.ads.admanager_v1.types.delivery_enums import ( + CompanionDeliveryOptionEnum, + CreativeRotationTypeEnum, + LineItemDeliveryRateTypeEnum, + RoadblockingTypeEnum, +) +from google.ads.admanager_v1.types.delivery_indicator import DeliveryIndicator from google.ads.admanager_v1.types.device_capability_messages import DeviceCapability from google.ads.admanager_v1.types.device_capability_service import ( GetDeviceCapabilityRequest, @@ -399,6 +553,7 @@ ListDeviceManufacturersRequest, ListDeviceManufacturersResponse, ) +from google.ads.admanager_v1.types.discount_type_enum import DiscountTypeEnum from google.ads.admanager_v1.types.early_ad_break_notification_enums import ( AdBreakStateEnum, ) @@ -420,6 +575,7 @@ from google.ads.admanager_v1.types.exchange_syndication_product_enum import ( ExchangeSyndicationProductEnum, ) +from google.ads.admanager_v1.types.exclusion_scope_enum import ExclusionScopeEnum from google.ads.admanager_v1.types.frequency_cap import FrequencyCap from google.ads.admanager_v1.types.geo_target_messages import GeoTarget from google.ads.admanager_v1.types.geo_target_service import ( @@ -429,6 +585,9 @@ ) from google.ads.admanager_v1.types.goal import Goal from google.ads.admanager_v1.types.goal_enums import GoalTypeEnum, UnitTypeEnum +from google.ads.admanager_v1.types.grp_provider_enum import GrpProviderEnum +from google.ads.admanager_v1.types.grp_settings import GrpSettings +from google.ads.admanager_v1.types.grp_target_gender_enum import GrpTargetGenderEnum from google.ads.admanager_v1.types.label_enums import LabelTypeEnum from google.ads.admanager_v1.types.label_messages import Label from google.ads.admanager_v1.types.label_service import ( @@ -446,13 +605,27 @@ ListLabelsResponse, UpdateLabelRequest, ) -from google.ads.admanager_v1.types.line_item_enums import LineItemTypeEnum +from google.ads.admanager_v1.types.line_item_allowed_format_enum import ( + LineItemAllowedFormatEnum, +) +from google.ads.admanager_v1.types.line_item_deal_info import LineItemDealInfo +from google.ads.admanager_v1.types.line_item_delivery_forecast_source_enum import ( + LineItemDeliveryForecastSourceEnum, +) +from google.ads.admanager_v1.types.line_item_discount import LineItemDiscount +from google.ads.admanager_v1.types.line_item_enums import ( + LineItemComputedStatusEnum, + LineItemCostTypeEnum, + LineItemReservationStatusEnum, + LineItemTypeEnum, +) from google.ads.admanager_v1.types.line_item_messages import LineItem from google.ads.admanager_v1.types.line_item_service import ( GetLineItemRequest, ListLineItemsRequest, ListLineItemsResponse, ) +from google.ads.admanager_v1.types.line_item_stats import LineItemStats from google.ads.admanager_v1.types.linked_device_enums import LinkedDeviceVisibilityEnum from google.ads.admanager_v1.types.linked_device_messages import LinkedDevice from google.ads.admanager_v1.types.linked_device_service import ( @@ -460,7 +633,48 @@ ListLinkedDevicesRequest, ListLinkedDevicesResponse, ) +from google.ads.admanager_v1.types.live_stream_event_enums import ( + AdBreakFillTypeEnum, + AdBreakMarkupTypeEnum, + DynamicAdInsertionTypeEnum, + HlsMasterPlaylistRefreshTypeEnum, + HlsSettingsPlaylistTypeEnum, + LiveStreamEventStatusEnum, + LiveStreamEventStreamingFormatEnum, + SlateStatusEnum, +) from google.ads.admanager_v1.types.live_stream_event_messages import LiveStreamEvent +from google.ads.admanager_v1.types.live_stream_messages import ( + AuxiliaryAdSettings, + DashBridge, + HlsSettings, + LiveStream, + LiveStreamConditioning, + MasterPlaylistSettings, + PrefetchSettings, + PrerollSettings, +) +from google.ads.admanager_v1.types.live_stream_service import ( + BatchActivateLiveStreamsRequest, + BatchActivateLiveStreamsResponse, + BatchArchiveLiveStreamsRequest, + BatchArchiveLiveStreamsResponse, + BatchCreateLiveStreamsRequest, + BatchCreateLiveStreamsResponse, + BatchPauseAdsLiveStreamsRequest, + BatchPauseAdsLiveStreamsResponse, + BatchPauseLiveStreamsRequest, + BatchPauseLiveStreamsResponse, + BatchRefreshMasterPlaylistsRequest, + BatchRefreshMasterPlaylistsResponse, + BatchUpdateLiveStreamsRequest, + BatchUpdateLiveStreamsResponse, + CreateLiveStreamRequest, + GetLiveStreamRequest, + ListLiveStreamsRequest, + ListLiveStreamsResponse, + UpdateLiveStreamRequest, +) from google.ads.admanager_v1.types.mcm_earnings_messages import ( EarningsProductBreakdown, McmEarnings, @@ -499,6 +713,10 @@ ListNetworksRequest, ListNetworksResponse, ) +from google.ads.admanager_v1.types.nielsen_ctv_pacing_enum import NielsenCtvPacingEnum +from google.ads.admanager_v1.types.non_guaranteed_deal_priority import ( + NonGuaranteedDealPriority, +) from google.ads.admanager_v1.types.operating_system_messages import OperatingSystem from google.ads.admanager_v1.types.operating_system_service import ( GetOperatingSystemRequest, @@ -516,9 +734,50 @@ from google.ads.admanager_v1.types.order_enums import OrderStatusEnum from google.ads.admanager_v1.types.order_messages import Order from google.ads.admanager_v1.types.order_service import ( + BatchApproveAndOverbookOrdersRequest, + BatchApproveAndOverbookOrdersResponse, + BatchApproveOrdersRequest, + BatchApproveOrdersResponse, + BatchApproveOrdersWithoutReservationRequest, + BatchApproveOrdersWithoutReservationResponse, + BatchArchiveOrdersRequest, + BatchArchiveOrdersResponse, + BatchCreateOrdersRequest, + BatchCreateOrdersResponse, + BatchDeleteOrdersRequest, + BatchDeleteOrdersResponse, + BatchDisapproveOrdersRequest, + BatchDisapproveOrdersResponse, + BatchDisapproveOrdersWithoutReservationChangesRequest, + BatchDisapproveOrdersWithoutReservationChangesResponse, + BatchPauseOrdersRequest, + BatchPauseOrdersResponse, + BatchResumeAndOverbookOrdersRequest, + BatchResumeAndOverbookOrdersResponse, + BatchResumeOrdersRequest, + BatchResumeOrdersResponse, + BatchRetractOrdersRequest, + BatchRetractOrdersResponse, + BatchRetractOrdersWithoutReservationChangesRequest, + BatchRetractOrdersWithoutReservationChangesResponse, + BatchSubmitOrdersForApprovalAndOverbookRequest, + BatchSubmitOrdersForApprovalAndOverbookResponse, + BatchSubmitOrdersForApprovalRequest, + BatchSubmitOrdersForApprovalResponse, + BatchSubmitOrdersForApprovalWithoutReservationChangesRequest, + BatchSubmitOrdersForApprovalWithoutReservationChangesResponse, + BatchUnarchiveOrdersRequest, + BatchUnarchiveOrdersResponse, + BatchUpdateOrdersRequest, + BatchUpdateOrdersResponse, + CreateOrderRequest, GetOrderRequest, ListOrdersRequest, ListOrdersResponse, + UpdateOrderRequest, +) +from google.ads.admanager_v1.types.pacing_device_categorization_enum import ( + PacingDeviceCategorizationEnum, ) from google.ads.admanager_v1.types.placement_enums import PlacementStatusEnum from google.ads.admanager_v1.types.placement_messages import Placement @@ -566,12 +825,10 @@ ListProgrammaticBuyersRequest, ListProgrammaticBuyersResponse, ) +from google.ads.admanager_v1.types.reach_partner_enum import ReachPartnerEnum from google.ads.admanager_v1.types.report_definition import ReportDefinition -from google.ads.admanager_v1.types.report_messages import ( - Report, - ReportDataTable, - ScheduleOptions, -) +from google.ads.admanager_v1.types.report_delivery import ScheduleOptions +from google.ads.admanager_v1.types.report_messages import Report, ReportDataTable from google.ads.admanager_v1.types.report_service import ( CreateReportRequest, FetchReportResultRowsRequest, @@ -626,6 +883,32 @@ ) from google.ads.admanager_v1.types.size import Size from google.ads.admanager_v1.types.size_type_enum import SizeTypeEnum +from google.ads.admanager_v1.types.skippable_ad_type_enum import SkippableAdTypeEnum +from google.ads.admanager_v1.types.slate_messages import Slate +from google.ads.admanager_v1.types.slate_service import ( + BatchArchiveSlatesRequest, + BatchArchiveSlatesResponse, + BatchCreateSlatesRequest, + BatchCreateSlatesResponse, + BatchUnarchiveSlatesRequest, + BatchUnarchiveSlatesResponse, + BatchUpdateSlatesRequest, + BatchUpdateSlatesResponse, + CreateSlateRequest, + GetSlateRequest, + ListSlatesRequest, + ListSlatesResponse, + UpdateSlateRequest, +) +from google.ads.admanager_v1.types.suggested_ad_unit_messages import SuggestedAdUnit +from google.ads.admanager_v1.types.suggested_ad_unit_service import ( + BatchApproveSuggestedAdUnitsRequest, + BatchApproveSuggestedAdUnitsResponse, + GetSuggestedAdUnitRequest, + ListSuggestedAdUnitsRequest, + ListSuggestedAdUnitsResponse, +) +from google.ads.admanager_v1.types.target_platform_enum import TargetPlatformEnum from google.ads.admanager_v1.types.targeted_video_bumper_type_enum import ( TargetedVideoBumperTypeEnum, ) @@ -650,6 +933,7 @@ MobileApplicationTargeting, MobileCarrierTargeting, OperatingSystemTargeting, + RequestFormatTargeting, RequestPlatformTargeting, Targeting, TechnologyTargeting, @@ -657,6 +941,24 @@ VideoPosition, VideoPositionTargeting, ) +from google.ads.admanager_v1.types.targeting_preset_enums import ( + TargetingPresetStatusEnum, +) +from google.ads.admanager_v1.types.targeting_preset_messages import TargetingPreset +from google.ads.admanager_v1.types.targeting_preset_service import ( + BatchCreateTargetingPresetsRequest, + BatchCreateTargetingPresetsResponse, + BatchDeactivateTargetingPresetsRequest, + BatchDeactivateTargetingPresetsResponse, + BatchUpdateTargetingPresetsRequest, + BatchUpdateTargetingPresetsResponse, + CreateTargetingPresetRequest, + DeactivateTargetingPresetRequest, + GetTargetingPresetRequest, + ListTargetingPresetsRequest, + ListTargetingPresetsResponse, + UpdateTargetingPresetRequest, +) from google.ads.admanager_v1.types.taxonomy_category_messages import TaxonomyCategory from google.ads.admanager_v1.types.taxonomy_category_service import ( GetTaxonomyCategoryRequest, @@ -681,21 +983,43 @@ ListTeamsResponse, UpdateTeamRequest, ) +from google.ads.admanager_v1.types.third_party_company_enums import ( + ThirdPartyCompanyStatusEnum, + ThirdPartyCompanyTypeEnum, +) +from google.ads.admanager_v1.types.third_party_company_messages import ThirdPartyCompany +from google.ads.admanager_v1.types.third_party_company_service import ( + GetThirdPartyCompanyRequest, + ListThirdPartyCompaniesRequest, + ListThirdPartyCompaniesResponse, +) +from google.ads.admanager_v1.types.third_party_measurement_settings import ( + ThirdPartyMeasurementSettings, +) from google.ads.admanager_v1.types.time_unit_enum import TimeUnitEnum from google.ads.admanager_v1.types.user_messages import User from google.ads.admanager_v1.types.user_service import GetUserRequest from google.ads.admanager_v1.types.video_position_enum import VideoPositionEnum +from google.ads.admanager_v1.types.video_transcode_status_enum import ( + VideoTranscodeStatusEnum, +) +from google.ads.admanager_v1.types.viewability_partner_enum import ( + ViewabilityPartnerEnum, +) from google.ads.admanager_v1.types.web_property import WebProperty __all__ = ( "AdBreakServiceClient", "AdReviewCenterAdServiceClient", + "AdRuleServiceClient", + "AdSpotServiceClient", "AdUnitServiceClient", "ApplicationServiceClient", "AudienceSegmentServiceClient", "BandwidthGroupServiceClient", "BrowserLanguageServiceClient", "BrowserServiceClient", + "CdnConfigServiceClient", "CmsMetadataKeyServiceClient", "CmsMetadataValueServiceClient", "CompanyServiceClient", @@ -703,6 +1027,7 @@ "ContentBundleServiceClient", "ContentLabelServiceClient", "ContentServiceClient", + "CreativeSetServiceClient", "CreativeTemplateServiceClient", "CustomFieldServiceClient", "CustomTargetingKeyServiceClient", @@ -715,6 +1040,7 @@ "LabelServiceClient", "LineItemServiceClient", "LinkedDeviceServiceClient", + "LiveStreamServiceClient", "McmEarningsServiceClient", "MobileCarrierServiceClient", "MobileDeviceServiceClient", @@ -731,8 +1057,12 @@ "RichMediaAdsCompanyServiceClient", "RoleServiceClient", "SiteServiceClient", + "SlateServiceClient", + "SuggestedAdUnitServiceClient", + "TargetingPresetServiceClient", "TaxonomyCategoryServiceClient", "TeamServiceClient", + "ThirdPartyCompanyServiceClient", "UserServiceClient", "AdBreak", "CreateAdBreakRequest", @@ -751,6 +1081,38 @@ "BatchBlockAdReviewCenterAdsResponse", "SearchAdReviewCenterAdsRequest", "SearchAdReviewCenterAdsResponse", + "AdRuleFrequencyCapBehaviorEnum", + "AdRuleStatusEnum", + "AdRule", + "AdRuleSlot", + "BatchActivateAdRulesRequest", + "BatchActivateAdRulesResponse", + "BatchCreateAdRulesRequest", + "BatchCreateAdRulesResponse", + "BatchDeactivateAdRulesRequest", + "BatchDeactivateAdRulesResponse", + "BatchDeleteAdRulesRequest", + "BatchUpdateAdRulesRequest", + "BatchUpdateAdRulesResponse", + "CreateAdRuleRequest", + "GetAdRuleRequest", + "ListAdRulesRequest", + "ListAdRulesResponse", + "UpdateAdRuleRequest", + "AdRuleSlotBehaviorEnum", + "AdRuleSlotBumperEnum", + "AdRuleSlotMidrollFrequencyTypeEnum", + "AdSpot", + "BatchCreateAdSpotsRequest", + "BatchCreateAdSpotsResponse", + "BatchUpdateAdSpotsRequest", + "BatchUpdateAdSpotsResponse", + "CreateAdSpotRequest", + "GetAdSpotRequest", + "ListAdSpotsRequest", + "ListAdSpotsResponse", + "UpdateAdSpotRequest", + "AdSpotTargetingTypeEnum", "AdUnitStatusEnum", "SmartSizeModeEnum", "TargetWindowEnum", @@ -803,6 +1165,7 @@ "GetBandwidthGroupRequest", "ListBandwidthGroupsRequest", "ListBandwidthGroupsResponse", + "BrandLiftPartnerEnum", "BrowserLanguage", "GetBrowserLanguageRequest", "ListBrowserLanguagesRequest", @@ -811,6 +1174,29 @@ "GetBrowserRequest", "ListBrowsersRequest", "ListBrowsersResponse", + "AdMediaDeliveryConfig", + "CdnConfig", + "CdnSecurityPolicy", + "MediaLocation", + "SourceContentConfig", + "BatchActivateCdnConfigsRequest", + "BatchActivateCdnConfigsResponse", + "BatchArchiveCdnConfigsRequest", + "BatchArchiveCdnConfigsResponse", + "BatchCreateCdnConfigsRequest", + "BatchCreateCdnConfigsResponse", + "BatchUpdateCdnConfigsRequest", + "BatchUpdateCdnConfigsResponse", + "CreateCdnConfigRequest", + "GetCdnConfigRequest", + "ListCdnConfigsRequest", + "ListCdnConfigsResponse", + "UpdateCdnConfigRequest", + "CdnConfigStatusEnum", + "CdnConfigTypeEnum", + "CdnSecurityPolicyTypeEnum", + "CdnSecurityPolicyOriginForwardingEnum", + "ChildContentEligibilityEnum", "ChildPublisher", "CmsMetadataKeyStatusEnum", "CmsMetadataKey", @@ -847,18 +1233,39 @@ "ListContactsRequest", "ListContactsResponse", "UpdateContactRequest", + "ContentBundleStatusEnum", "ContentBundle", + "BatchActivateContentBundlesRequest", + "BatchActivateContentBundlesResponse", + "BatchDeactivateContentBundlesRequest", + "BatchDeactivateContentBundlesResponse", "GetContentBundleRequest", "ListContentBundlesRequest", "ListContentBundlesResponse", + "ContentStatusEnum", + "ContentStatusSourceEnum", + "DaiIngestErrorReasonEnum", + "DaiIngestStatusEnum", "ContentLabel", "GetContentLabelRequest", "ListContentLabelsRequest", "ListContentLabelsResponse", + "CmsContent", "Content", + "DaiIngestError", "GetContentRequest", "ListContentRequest", "ListContentResponse", + "Creative", + "CreativePlaceholder", + "CreativePlaceholderCompanion", + "CreativeSet", + "CreateCreativeSetRequest", + "GetCreativeSetRequest", + "ListCreativeSetsRequest", + "ListCreativeSetsResponse", + "UpdateCreativeSetRequest", + "CreativeTargeting", "CreativeTemplateStatusEnum", "CreativeTemplateTypeEnum", "CreativeTemplate", @@ -887,6 +1294,9 @@ "ListCustomFieldsResponse", "UpdateCustomFieldRequest", "CustomFieldValue", + "CustomPacingCurve", + "CustomPacingGoal", + "CustomPacingGoalUnitEnum", "CustomTargetingKeyReportableTypeEnum", "CustomTargetingKeyStatusEnum", "CustomTargetingKeyTypeEnum", @@ -907,10 +1317,28 @@ "CustomTargetingValueMatchTypeEnum", "CustomTargetingValueStatusEnum", "CustomTargetingValue", + "ActivateCustomTargetingValueRequest", + "BatchActivateCustomTargetingValuesRequest", + "BatchActivateCustomTargetingValuesResponse", + "BatchCreateCustomTargetingValuesRequest", + "BatchCreateCustomTargetingValuesResponse", + "BatchDeactivateCustomTargetingValuesRequest", + "BatchDeactivateCustomTargetingValuesResponse", + "BatchUpdateCustomTargetingValuesRequest", + "BatchUpdateCustomTargetingValuesResponse", + "CreateCustomTargetingValueRequest", + "DeactivateCustomTargetingValueRequest", "GetCustomTargetingValueRequest", "ListCustomTargetingValuesRequest", "ListCustomTargetingValuesResponse", + "UpdateCustomTargetingValueRequest", "DealBuyerPermissionTypeEnum", + "DealPriorityTierEnum", + "CompanionDeliveryOptionEnum", + "CreativeRotationTypeEnum", + "LineItemDeliveryRateTypeEnum", + "RoadblockingTypeEnum", + "DeliveryIndicator", "DeviceCapability", "GetDeviceCapabilityRequest", "ListDeviceCapabilitiesRequest", @@ -923,6 +1351,7 @@ "GetDeviceManufacturerRequest", "ListDeviceManufacturersRequest", "ListDeviceManufacturersResponse", + "DiscountTypeEnum", "AdBreakStateEnum", "EntitySignalsMapping", "BatchCreateEntitySignalsMappingsRequest", @@ -936,6 +1365,7 @@ "UpdateEntitySignalsMappingRequest", "EnvironmentTypeEnum", "ExchangeSyndicationProductEnum", + "ExclusionScopeEnum", "FrequencyCap", "GeoTarget", "GetGeoTargetRequest", @@ -944,6 +1374,9 @@ "Goal", "GoalTypeEnum", "UnitTypeEnum", + "GrpProviderEnum", + "GrpSettings", + "GrpTargetGenderEnum", "LabelTypeEnum", "Label", "BatchActivateLabelsRequest", @@ -959,17 +1392,60 @@ "ListLabelsRequest", "ListLabelsResponse", "UpdateLabelRequest", + "LineItemAllowedFormatEnum", + "LineItemDealInfo", + "LineItemDeliveryForecastSourceEnum", + "LineItemDiscount", + "LineItemComputedStatusEnum", + "LineItemCostTypeEnum", + "LineItemReservationStatusEnum", "LineItemTypeEnum", "LineItem", "GetLineItemRequest", "ListLineItemsRequest", "ListLineItemsResponse", + "LineItemStats", "LinkedDeviceVisibilityEnum", "LinkedDevice", "GetLinkedDeviceRequest", "ListLinkedDevicesRequest", "ListLinkedDevicesResponse", + "AdBreakFillTypeEnum", + "AdBreakMarkupTypeEnum", + "DynamicAdInsertionTypeEnum", + "HlsMasterPlaylistRefreshTypeEnum", + "HlsSettingsPlaylistTypeEnum", + "LiveStreamEventStatusEnum", + "LiveStreamEventStreamingFormatEnum", + "SlateStatusEnum", "LiveStreamEvent", + "AuxiliaryAdSettings", + "DashBridge", + "HlsSettings", + "LiveStream", + "LiveStreamConditioning", + "MasterPlaylistSettings", + "PrefetchSettings", + "PrerollSettings", + "BatchActivateLiveStreamsRequest", + "BatchActivateLiveStreamsResponse", + "BatchArchiveLiveStreamsRequest", + "BatchArchiveLiveStreamsResponse", + "BatchCreateLiveStreamsRequest", + "BatchCreateLiveStreamsResponse", + "BatchPauseAdsLiveStreamsRequest", + "BatchPauseAdsLiveStreamsResponse", + "BatchPauseLiveStreamsRequest", + "BatchPauseLiveStreamsResponse", + "BatchRefreshMasterPlaylistsRequest", + "BatchRefreshMasterPlaylistsResponse", + "BatchUpdateLiveStreamsRequest", + "BatchUpdateLiveStreamsResponse", + "CreateLiveStreamRequest", + "GetLiveStreamRequest", + "ListLiveStreamsRequest", + "ListLiveStreamsResponse", + "UpdateLiveStreamRequest", "EarningsProductBreakdown", "McmEarnings", "FetchMcmEarningsRequest", @@ -992,6 +1468,8 @@ "GetNetworkRequest", "ListNetworksRequest", "ListNetworksResponse", + "NielsenCtvPacingEnum", + "NonGuaranteedDealPriority", "OperatingSystem", "GetOperatingSystemRequest", "ListOperatingSystemsRequest", @@ -1002,9 +1480,48 @@ "ListOperatingSystemVersionsResponse", "OrderStatusEnum", "Order", + "BatchApproveAndOverbookOrdersRequest", + "BatchApproveAndOverbookOrdersResponse", + "BatchApproveOrdersRequest", + "BatchApproveOrdersResponse", + "BatchApproveOrdersWithoutReservationRequest", + "BatchApproveOrdersWithoutReservationResponse", + "BatchArchiveOrdersRequest", + "BatchArchiveOrdersResponse", + "BatchCreateOrdersRequest", + "BatchCreateOrdersResponse", + "BatchDeleteOrdersRequest", + "BatchDeleteOrdersResponse", + "BatchDisapproveOrdersRequest", + "BatchDisapproveOrdersResponse", + "BatchDisapproveOrdersWithoutReservationChangesRequest", + "BatchDisapproveOrdersWithoutReservationChangesResponse", + "BatchPauseOrdersRequest", + "BatchPauseOrdersResponse", + "BatchResumeAndOverbookOrdersRequest", + "BatchResumeAndOverbookOrdersResponse", + "BatchResumeOrdersRequest", + "BatchResumeOrdersResponse", + "BatchRetractOrdersRequest", + "BatchRetractOrdersResponse", + "BatchRetractOrdersWithoutReservationChangesRequest", + "BatchRetractOrdersWithoutReservationChangesResponse", + "BatchSubmitOrdersForApprovalAndOverbookRequest", + "BatchSubmitOrdersForApprovalAndOverbookResponse", + "BatchSubmitOrdersForApprovalRequest", + "BatchSubmitOrdersForApprovalResponse", + "BatchSubmitOrdersForApprovalWithoutReservationChangesRequest", + "BatchSubmitOrdersForApprovalWithoutReservationChangesResponse", + "BatchUnarchiveOrdersRequest", + "BatchUnarchiveOrdersResponse", + "BatchUpdateOrdersRequest", + "BatchUpdateOrdersResponse", + "CreateOrderRequest", "GetOrderRequest", "ListOrdersRequest", "ListOrdersResponse", + "UpdateOrderRequest", + "PacingDeviceCategorizationEnum", "PlacementStatusEnum", "Placement", "BatchActivatePlacementsRequest", @@ -1039,10 +1556,11 @@ "GetProgrammaticBuyerRequest", "ListProgrammaticBuyersRequest", "ListProgrammaticBuyersResponse", + "ReachPartnerEnum", "ReportDefinition", + "ScheduleOptions", "Report", "ReportDataTable", - "ScheduleOptions", "CreateReportRequest", "FetchReportResultRowsRequest", "FetchReportResultRowsResponse", @@ -1084,6 +1602,28 @@ "UpdateSiteRequest", "Size", "SizeTypeEnum", + "SkippableAdTypeEnum", + "Slate", + "BatchArchiveSlatesRequest", + "BatchArchiveSlatesResponse", + "BatchCreateSlatesRequest", + "BatchCreateSlatesResponse", + "BatchUnarchiveSlatesRequest", + "BatchUnarchiveSlatesResponse", + "BatchUpdateSlatesRequest", + "BatchUpdateSlatesResponse", + "CreateSlateRequest", + "GetSlateRequest", + "ListSlatesRequest", + "ListSlatesResponse", + "UpdateSlateRequest", + "SuggestedAdUnit", + "BatchApproveSuggestedAdUnitsRequest", + "BatchApproveSuggestedAdUnitsResponse", + "GetSuggestedAdUnitRequest", + "ListSuggestedAdUnitsRequest", + "ListSuggestedAdUnitsResponse", + "TargetPlatformEnum", "TargetedVideoBumperTypeEnum", "AdUnitTargeting", "AudienceSegmentTargeting", @@ -1105,12 +1645,27 @@ "MobileApplicationTargeting", "MobileCarrierTargeting", "OperatingSystemTargeting", + "RequestFormatTargeting", "RequestPlatformTargeting", "Targeting", "TechnologyTargeting", "UserDomainTargeting", "VideoPosition", "VideoPositionTargeting", + "TargetingPresetStatusEnum", + "TargetingPreset", + "BatchCreateTargetingPresetsRequest", + "BatchCreateTargetingPresetsResponse", + "BatchDeactivateTargetingPresetsRequest", + "BatchDeactivateTargetingPresetsResponse", + "BatchUpdateTargetingPresetsRequest", + "BatchUpdateTargetingPresetsResponse", + "CreateTargetingPresetRequest", + "DeactivateTargetingPresetRequest", + "GetTargetingPresetRequest", + "ListTargetingPresetsRequest", + "ListTargetingPresetsResponse", + "UpdateTargetingPresetRequest", "TaxonomyCategory", "GetTaxonomyCategoryRequest", "ListTaxonomyCategoriesRequest", @@ -1132,9 +1687,18 @@ "ListTeamsRequest", "ListTeamsResponse", "UpdateTeamRequest", + "ThirdPartyCompanyStatusEnum", + "ThirdPartyCompanyTypeEnum", + "ThirdPartyCompany", + "GetThirdPartyCompanyRequest", + "ListThirdPartyCompaniesRequest", + "ListThirdPartyCompaniesResponse", + "ThirdPartyMeasurementSettings", "TimeUnitEnum", "User", "GetUserRequest", "VideoPositionEnum", + "VideoTranscodeStatusEnum", + "ViewabilityPartnerEnum", "WebProperty", ) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/__init__.py b/packages/google-ads-admanager/google/ads/admanager_v1/__init__.py index 0174eed93a9a..006d9cc2d9a0 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/__init__.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/__init__.py @@ -32,12 +32,15 @@ __lazy_modules__ = { "google.ads.admanager_v1.services.ad_break_service", "google.ads.admanager_v1.services.ad_review_center_ad_service", + "google.ads.admanager_v1.services.ad_rule_service", + "google.ads.admanager_v1.services.ad_spot_service", "google.ads.admanager_v1.services.ad_unit_service", "google.ads.admanager_v1.services.application_service", "google.ads.admanager_v1.services.audience_segment_service", "google.ads.admanager_v1.services.bandwidth_group_service", "google.ads.admanager_v1.services.browser_language_service", "google.ads.admanager_v1.services.browser_service", + "google.ads.admanager_v1.services.cdn_config_service", "google.ads.admanager_v1.services.cms_metadata_key_service", "google.ads.admanager_v1.services.cms_metadata_value_service", "google.ads.admanager_v1.services.company_service", @@ -45,6 +48,7 @@ "google.ads.admanager_v1.services.content_bundle_service", "google.ads.admanager_v1.services.content_label_service", "google.ads.admanager_v1.services.content_service", + "google.ads.admanager_v1.services.creative_set_service", "google.ads.admanager_v1.services.creative_template_service", "google.ads.admanager_v1.services.custom_field_service", "google.ads.admanager_v1.services.custom_targeting_key_service", @@ -57,6 +61,7 @@ "google.ads.admanager_v1.services.label_service", "google.ads.admanager_v1.services.line_item_service", "google.ads.admanager_v1.services.linked_device_service", + "google.ads.admanager_v1.services.live_stream_service", "google.ads.admanager_v1.services.mcm_earnings_service", "google.ads.admanager_v1.services.mobile_carrier_service", "google.ads.admanager_v1.services.mobile_device_service", @@ -73,14 +78,27 @@ "google.ads.admanager_v1.services.rich_media_ads_company_service", "google.ads.admanager_v1.services.role_service", "google.ads.admanager_v1.services.site_service", + "google.ads.admanager_v1.services.slate_service", + "google.ads.admanager_v1.services.suggested_ad_unit_service", + "google.ads.admanager_v1.services.targeting_preset_service", "google.ads.admanager_v1.services.taxonomy_category_service", "google.ads.admanager_v1.services.team_service", + "google.ads.admanager_v1.services.third_party_company_service", "google.ads.admanager_v1.services.user_service", "google.ads.admanager_v1.types.ad_break_messages", "google.ads.admanager_v1.types.ad_break_service", "google.ads.admanager_v1.types.ad_review_center_ad_enums", "google.ads.admanager_v1.types.ad_review_center_ad_messages", "google.ads.admanager_v1.types.ad_review_center_ad_service", + "google.ads.admanager_v1.types.ad_rule_enums", + "google.ads.admanager_v1.types.ad_rule_messages", + "google.ads.admanager_v1.types.ad_rule_service", + "google.ads.admanager_v1.types.ad_rule_slot_behavior_enum", + "google.ads.admanager_v1.types.ad_rule_slot_bumper_enum", + "google.ads.admanager_v1.types.ad_rule_slot_midroll_frequency_type_enum", + "google.ads.admanager_v1.types.ad_spot_messages", + "google.ads.admanager_v1.types.ad_spot_service", + "google.ads.admanager_v1.types.ad_spot_targeting_type_enum", "google.ads.admanager_v1.types.ad_unit_enums", "google.ads.admanager_v1.types.ad_unit_messages", "google.ads.admanager_v1.types.ad_unit_service", @@ -93,10 +111,18 @@ "google.ads.admanager_v1.types.audience_segment_service", "google.ads.admanager_v1.types.bandwidth_group_messages", "google.ads.admanager_v1.types.bandwidth_group_service", + "google.ads.admanager_v1.types.brand_lift_partner_enum", "google.ads.admanager_v1.types.browser_language_messages", "google.ads.admanager_v1.types.browser_language_service", "google.ads.admanager_v1.types.browser_messages", "google.ads.admanager_v1.types.browser_service", + "google.ads.admanager_v1.types.cdn_config_messages", + "google.ads.admanager_v1.types.cdn_config_service", + "google.ads.admanager_v1.types.cdn_config_status_enum", + "google.ads.admanager_v1.types.cdn_config_type_enum", + "google.ads.admanager_v1.types.cdn_security_policy_enum", + "google.ads.admanager_v1.types.cdn_security_policy_origin_forwarding_enum", + "google.ads.admanager_v1.types.child_content_eligibility_enum", "google.ads.admanager_v1.types.child_publisher_messages", "google.ads.admanager_v1.types.cms_metadata_key_enums", "google.ads.admanager_v1.types.cms_metadata_key_messages", @@ -110,12 +136,19 @@ "google.ads.admanager_v1.types.contact_enums", "google.ads.admanager_v1.types.contact_messages", "google.ads.admanager_v1.types.contact_service", + "google.ads.admanager_v1.types.content_bundle_enums", "google.ads.admanager_v1.types.content_bundle_messages", "google.ads.admanager_v1.types.content_bundle_service", + "google.ads.admanager_v1.types.content_enums", "google.ads.admanager_v1.types.content_label_messages", "google.ads.admanager_v1.types.content_label_service", "google.ads.admanager_v1.types.content_messages", "google.ads.admanager_v1.types.content_service", + "google.ads.admanager_v1.types.creative_messages", + "google.ads.admanager_v1.types.creative_placeholder", + "google.ads.admanager_v1.types.creative_set_messages", + "google.ads.admanager_v1.types.creative_set_service", + "google.ads.admanager_v1.types.creative_targeting", "google.ads.admanager_v1.types.creative_template_enums", "google.ads.admanager_v1.types.creative_template_messages", "google.ads.admanager_v1.types.creative_template_service", @@ -124,6 +157,8 @@ "google.ads.admanager_v1.types.custom_field_messages", "google.ads.admanager_v1.types.custom_field_service", "google.ads.admanager_v1.types.custom_field_value", + "google.ads.admanager_v1.types.custom_pacing_curve", + "google.ads.admanager_v1.types.custom_pacing_goal_unit_enum", "google.ads.admanager_v1.types.custom_targeting_key_enums", "google.ads.admanager_v1.types.custom_targeting_key_messages", "google.ads.admanager_v1.types.custom_targeting_key_service", @@ -131,32 +166,48 @@ "google.ads.admanager_v1.types.custom_targeting_value_messages", "google.ads.admanager_v1.types.custom_targeting_value_service", "google.ads.admanager_v1.types.deal_buyer_permission_type_enum", + "google.ads.admanager_v1.types.deal_priority_tier_enum", + "google.ads.admanager_v1.types.delivery_enums", + "google.ads.admanager_v1.types.delivery_indicator", "google.ads.admanager_v1.types.device_capability_messages", "google.ads.admanager_v1.types.device_capability_service", "google.ads.admanager_v1.types.device_category_messages", "google.ads.admanager_v1.types.device_category_service", "google.ads.admanager_v1.types.device_manufacturer_messages", "google.ads.admanager_v1.types.device_manufacturer_service", + "google.ads.admanager_v1.types.discount_type_enum", "google.ads.admanager_v1.types.early_ad_break_notification_enums", "google.ads.admanager_v1.types.entity_signals_mapping_messages", "google.ads.admanager_v1.types.entity_signals_mapping_service", "google.ads.admanager_v1.types.environment_type_enum", "google.ads.admanager_v1.types.exchange_syndication_product_enum", + "google.ads.admanager_v1.types.exclusion_scope_enum", "google.ads.admanager_v1.types.frequency_cap", "google.ads.admanager_v1.types.geo_target_messages", "google.ads.admanager_v1.types.geo_target_service", "google.ads.admanager_v1.types.goal", "google.ads.admanager_v1.types.goal_enums", + "google.ads.admanager_v1.types.grp_provider_enum", + "google.ads.admanager_v1.types.grp_settings", + "google.ads.admanager_v1.types.grp_target_gender_enum", "google.ads.admanager_v1.types.label_enums", "google.ads.admanager_v1.types.label_messages", "google.ads.admanager_v1.types.label_service", + "google.ads.admanager_v1.types.line_item_allowed_format_enum", + "google.ads.admanager_v1.types.line_item_deal_info", + "google.ads.admanager_v1.types.line_item_delivery_forecast_source_enum", + "google.ads.admanager_v1.types.line_item_discount", "google.ads.admanager_v1.types.line_item_enums", "google.ads.admanager_v1.types.line_item_messages", "google.ads.admanager_v1.types.line_item_service", + "google.ads.admanager_v1.types.line_item_stats", "google.ads.admanager_v1.types.linked_device_enums", "google.ads.admanager_v1.types.linked_device_messages", "google.ads.admanager_v1.types.linked_device_service", + "google.ads.admanager_v1.types.live_stream_event_enums", "google.ads.admanager_v1.types.live_stream_event_messages", + "google.ads.admanager_v1.types.live_stream_messages", + "google.ads.admanager_v1.types.live_stream_service", "google.ads.admanager_v1.types.mcm_earnings_messages", "google.ads.admanager_v1.types.mcm_earnings_service", "google.ads.admanager_v1.types.mcm_enums", @@ -168,6 +219,8 @@ "google.ads.admanager_v1.types.mobile_device_submodel_service", "google.ads.admanager_v1.types.network_messages", "google.ads.admanager_v1.types.network_service", + "google.ads.admanager_v1.types.nielsen_ctv_pacing_enum", + "google.ads.admanager_v1.types.non_guaranteed_deal_priority", "google.ads.admanager_v1.types.operating_system_messages", "google.ads.admanager_v1.types.operating_system_service", "google.ads.admanager_v1.types.operating_system_version_messages", @@ -175,6 +228,7 @@ "google.ads.admanager_v1.types.order_enums", "google.ads.admanager_v1.types.order_messages", "google.ads.admanager_v1.types.order_service", + "google.ads.admanager_v1.types.pacing_device_categorization_enum", "google.ads.admanager_v1.types.placement_enums", "google.ads.admanager_v1.types.placement_messages", "google.ads.admanager_v1.types.placement_service", @@ -185,7 +239,9 @@ "google.ads.admanager_v1.types.private_marketplace_enums", "google.ads.admanager_v1.types.programmatic_buyer_messages", "google.ads.admanager_v1.types.programmatic_buyer_service", + "google.ads.admanager_v1.types.reach_partner_enum", "google.ads.admanager_v1.types.report_definition", + "google.ads.admanager_v1.types.report_delivery", "google.ads.admanager_v1.types.report_messages", "google.ads.admanager_v1.types.report_service", "google.ads.admanager_v1.types.report_value", @@ -201,30 +257,48 @@ "google.ads.admanager_v1.types.site_service", "google.ads.admanager_v1.types.size", "google.ads.admanager_v1.types.size_type_enum", + "google.ads.admanager_v1.types.skippable_ad_type_enum", + "google.ads.admanager_v1.types.slate_messages", + "google.ads.admanager_v1.types.slate_service", + "google.ads.admanager_v1.types.suggested_ad_unit_messages", + "google.ads.admanager_v1.types.suggested_ad_unit_service", + "google.ads.admanager_v1.types.target_platform_enum", "google.ads.admanager_v1.types.targeted_video_bumper_type_enum", "google.ads.admanager_v1.types.targeting", + "google.ads.admanager_v1.types.targeting_preset_enums", + "google.ads.admanager_v1.types.targeting_preset_messages", + "google.ads.admanager_v1.types.targeting_preset_service", "google.ads.admanager_v1.types.taxonomy_category_messages", "google.ads.admanager_v1.types.taxonomy_category_service", "google.ads.admanager_v1.types.taxonomy_type_enum", "google.ads.admanager_v1.types.team_enums", "google.ads.admanager_v1.types.team_messages", "google.ads.admanager_v1.types.team_service", + "google.ads.admanager_v1.types.third_party_company_enums", + "google.ads.admanager_v1.types.third_party_company_messages", + "google.ads.admanager_v1.types.third_party_company_service", + "google.ads.admanager_v1.types.third_party_measurement_settings", "google.ads.admanager_v1.types.time_unit_enum", "google.ads.admanager_v1.types.user_messages", "google.ads.admanager_v1.types.user_service", "google.ads.admanager_v1.types.video_position_enum", + "google.ads.admanager_v1.types.video_transcode_status_enum", + "google.ads.admanager_v1.types.viewability_partner_enum", "google.ads.admanager_v1.types.web_property", } from .services.ad_break_service import AdBreakServiceClient from .services.ad_review_center_ad_service import AdReviewCenterAdServiceClient +from .services.ad_rule_service import AdRuleServiceClient +from .services.ad_spot_service import AdSpotServiceClient from .services.ad_unit_service import AdUnitServiceClient from .services.application_service import ApplicationServiceClient from .services.audience_segment_service import AudienceSegmentServiceClient from .services.bandwidth_group_service import BandwidthGroupServiceClient from .services.browser_language_service import BrowserLanguageServiceClient from .services.browser_service import BrowserServiceClient +from .services.cdn_config_service import CdnConfigServiceClient from .services.cms_metadata_key_service import CmsMetadataKeyServiceClient from .services.cms_metadata_value_service import CmsMetadataValueServiceClient from .services.company_service import CompanyServiceClient @@ -232,6 +306,7 @@ from .services.content_bundle_service import ContentBundleServiceClient from .services.content_label_service import ContentLabelServiceClient from .services.content_service import ContentServiceClient +from .services.creative_set_service import CreativeSetServiceClient from .services.creative_template_service import CreativeTemplateServiceClient from .services.custom_field_service import CustomFieldServiceClient from .services.custom_targeting_key_service import CustomTargetingKeyServiceClient @@ -244,6 +319,7 @@ from .services.label_service import LabelServiceClient from .services.line_item_service import LineItemServiceClient from .services.linked_device_service import LinkedDeviceServiceClient +from .services.live_stream_service import LiveStreamServiceClient from .services.mcm_earnings_service import McmEarningsServiceClient from .services.mobile_carrier_service import MobileCarrierServiceClient from .services.mobile_device_service import MobileDeviceServiceClient @@ -262,8 +338,12 @@ from .services.rich_media_ads_company_service import RichMediaAdsCompanyServiceClient from .services.role_service import RoleServiceClient from .services.site_service import SiteServiceClient +from .services.slate_service import SlateServiceClient +from .services.suggested_ad_unit_service import SuggestedAdUnitServiceClient +from .services.targeting_preset_service import TargetingPresetServiceClient from .services.taxonomy_category_service import TaxonomyCategoryServiceClient from .services.team_service import TeamServiceClient +from .services.third_party_company_service import ThirdPartyCompanyServiceClient from .services.user_service import UserServiceClient from .types.ad_break_messages import AdBreak from .types.ad_break_service import ( @@ -288,6 +368,42 @@ SearchAdReviewCenterAdsRequest, SearchAdReviewCenterAdsResponse, ) +from .types.ad_rule_enums import AdRuleFrequencyCapBehaviorEnum, AdRuleStatusEnum +from .types.ad_rule_messages import AdRule, AdRuleSlot +from .types.ad_rule_service import ( + BatchActivateAdRulesRequest, + BatchActivateAdRulesResponse, + BatchCreateAdRulesRequest, + BatchCreateAdRulesResponse, + BatchDeactivateAdRulesRequest, + BatchDeactivateAdRulesResponse, + BatchDeleteAdRulesRequest, + BatchUpdateAdRulesRequest, + BatchUpdateAdRulesResponse, + CreateAdRuleRequest, + GetAdRuleRequest, + ListAdRulesRequest, + ListAdRulesResponse, + UpdateAdRuleRequest, +) +from .types.ad_rule_slot_behavior_enum import AdRuleSlotBehaviorEnum +from .types.ad_rule_slot_bumper_enum import AdRuleSlotBumperEnum +from .types.ad_rule_slot_midroll_frequency_type_enum import ( + AdRuleSlotMidrollFrequencyTypeEnum, +) +from .types.ad_spot_messages import AdSpot +from .types.ad_spot_service import ( + BatchCreateAdSpotsRequest, + BatchCreateAdSpotsResponse, + BatchUpdateAdSpotsRequest, + BatchUpdateAdSpotsResponse, + CreateAdSpotRequest, + GetAdSpotRequest, + ListAdSpotsRequest, + ListAdSpotsResponse, + UpdateAdSpotRequest, +) +from .types.ad_spot_targeting_type_enum import AdSpotTargetingTypeEnum from .types.ad_unit_enums import AdUnitStatusEnum, SmartSizeModeEnum, TargetWindowEnum from .types.ad_unit_messages import AdUnit, AdUnitParent, AdUnitSize, LabelFrequencyCap from .types.ad_unit_service import ( @@ -345,6 +461,7 @@ ListBandwidthGroupsRequest, ListBandwidthGroupsResponse, ) +from .types.brand_lift_partner_enum import BrandLiftPartnerEnum from .types.browser_language_messages import BrowserLanguage from .types.browser_language_service import ( GetBrowserLanguageRequest, @@ -357,6 +474,35 @@ ListBrowsersRequest, ListBrowsersResponse, ) +from .types.cdn_config_messages import ( + AdMediaDeliveryConfig, + CdnConfig, + CdnSecurityPolicy, + MediaLocation, + SourceContentConfig, +) +from .types.cdn_config_service import ( + BatchActivateCdnConfigsRequest, + BatchActivateCdnConfigsResponse, + BatchArchiveCdnConfigsRequest, + BatchArchiveCdnConfigsResponse, + BatchCreateCdnConfigsRequest, + BatchCreateCdnConfigsResponse, + BatchUpdateCdnConfigsRequest, + BatchUpdateCdnConfigsResponse, + CreateCdnConfigRequest, + GetCdnConfigRequest, + ListCdnConfigsRequest, + ListCdnConfigsResponse, + UpdateCdnConfigRequest, +) +from .types.cdn_config_status_enum import CdnConfigStatusEnum +from .types.cdn_config_type_enum import CdnConfigTypeEnum +from .types.cdn_security_policy_enum import CdnSecurityPolicyTypeEnum +from .types.cdn_security_policy_origin_forwarding_enum import ( + CdnSecurityPolicyOriginForwardingEnum, +) +from .types.child_content_eligibility_enum import ChildContentEligibilityEnum from .types.child_publisher_messages import ChildPublisher from .types.cms_metadata_key_enums import CmsMetadataKeyStatusEnum from .types.cms_metadata_key_messages import CmsMetadataKey @@ -400,24 +546,49 @@ ListContactsResponse, UpdateContactRequest, ) +from .types.content_bundle_enums import ContentBundleStatusEnum from .types.content_bundle_messages import ContentBundle from .types.content_bundle_service import ( + BatchActivateContentBundlesRequest, + BatchActivateContentBundlesResponse, + BatchDeactivateContentBundlesRequest, + BatchDeactivateContentBundlesResponse, GetContentBundleRequest, ListContentBundlesRequest, ListContentBundlesResponse, ) +from .types.content_enums import ( + ContentStatusEnum, + ContentStatusSourceEnum, + DaiIngestErrorReasonEnum, + DaiIngestStatusEnum, +) from .types.content_label_messages import ContentLabel from .types.content_label_service import ( GetContentLabelRequest, ListContentLabelsRequest, ListContentLabelsResponse, ) -from .types.content_messages import Content +from .types.content_messages import CmsContent, Content, DaiIngestError from .types.content_service import ( GetContentRequest, ListContentRequest, ListContentResponse, ) +from .types.creative_messages import Creative +from .types.creative_placeholder import ( + CreativePlaceholder, + CreativePlaceholderCompanion, +) +from .types.creative_set_messages import CreativeSet +from .types.creative_set_service import ( + CreateCreativeSetRequest, + GetCreativeSetRequest, + ListCreativeSetsRequest, + ListCreativeSetsResponse, + UpdateCreativeSetRequest, +) +from .types.creative_targeting import CreativeTargeting from .types.creative_template_enums import ( CreativeTemplateStatusEnum, CreativeTemplateTypeEnum, @@ -454,6 +625,8 @@ UpdateCustomFieldRequest, ) from .types.custom_field_value import CustomFieldValue +from .types.custom_pacing_curve import CustomPacingCurve, CustomPacingGoal +from .types.custom_pacing_goal_unit_enum import CustomPacingGoalUnitEnum from .types.custom_targeting_key_enums import ( CustomTargetingKeyReportableTypeEnum, CustomTargetingKeyStatusEnum, @@ -481,11 +654,31 @@ ) from .types.custom_targeting_value_messages import CustomTargetingValue from .types.custom_targeting_value_service import ( + ActivateCustomTargetingValueRequest, + BatchActivateCustomTargetingValuesRequest, + BatchActivateCustomTargetingValuesResponse, + BatchCreateCustomTargetingValuesRequest, + BatchCreateCustomTargetingValuesResponse, + BatchDeactivateCustomTargetingValuesRequest, + BatchDeactivateCustomTargetingValuesResponse, + BatchUpdateCustomTargetingValuesRequest, + BatchUpdateCustomTargetingValuesResponse, + CreateCustomTargetingValueRequest, + DeactivateCustomTargetingValueRequest, GetCustomTargetingValueRequest, ListCustomTargetingValuesRequest, ListCustomTargetingValuesResponse, + UpdateCustomTargetingValueRequest, ) from .types.deal_buyer_permission_type_enum import DealBuyerPermissionTypeEnum +from .types.deal_priority_tier_enum import DealPriorityTierEnum +from .types.delivery_enums import ( + CompanionDeliveryOptionEnum, + CreativeRotationTypeEnum, + LineItemDeliveryRateTypeEnum, + RoadblockingTypeEnum, +) +from .types.delivery_indicator import DeliveryIndicator from .types.device_capability_messages import DeviceCapability from .types.device_capability_service import ( GetDeviceCapabilityRequest, @@ -504,6 +697,7 @@ ListDeviceManufacturersRequest, ListDeviceManufacturersResponse, ) +from .types.discount_type_enum import DiscountTypeEnum from .types.early_ad_break_notification_enums import AdBreakStateEnum from .types.entity_signals_mapping_messages import EntitySignalsMapping from .types.entity_signals_mapping_service import ( @@ -519,6 +713,7 @@ ) from .types.environment_type_enum import EnvironmentTypeEnum from .types.exchange_syndication_product_enum import ExchangeSyndicationProductEnum +from .types.exclusion_scope_enum import ExclusionScopeEnum from .types.frequency_cap import FrequencyCap from .types.geo_target_messages import GeoTarget from .types.geo_target_service import ( @@ -528,6 +723,9 @@ ) from .types.goal import Goal from .types.goal_enums import GoalTypeEnum, UnitTypeEnum +from .types.grp_provider_enum import GrpProviderEnum +from .types.grp_settings import GrpSettings +from .types.grp_target_gender_enum import GrpTargetGenderEnum from .types.label_enums import LabelTypeEnum from .types.label_messages import Label from .types.label_service import ( @@ -545,13 +743,25 @@ ListLabelsResponse, UpdateLabelRequest, ) -from .types.line_item_enums import LineItemTypeEnum +from .types.line_item_allowed_format_enum import LineItemAllowedFormatEnum +from .types.line_item_deal_info import LineItemDealInfo +from .types.line_item_delivery_forecast_source_enum import ( + LineItemDeliveryForecastSourceEnum, +) +from .types.line_item_discount import LineItemDiscount +from .types.line_item_enums import ( + LineItemComputedStatusEnum, + LineItemCostTypeEnum, + LineItemReservationStatusEnum, + LineItemTypeEnum, +) from .types.line_item_messages import LineItem from .types.line_item_service import ( GetLineItemRequest, ListLineItemsRequest, ListLineItemsResponse, ) +from .types.line_item_stats import LineItemStats from .types.linked_device_enums import LinkedDeviceVisibilityEnum from .types.linked_device_messages import LinkedDevice from .types.linked_device_service import ( @@ -559,7 +769,48 @@ ListLinkedDevicesRequest, ListLinkedDevicesResponse, ) +from .types.live_stream_event_enums import ( + AdBreakFillTypeEnum, + AdBreakMarkupTypeEnum, + DynamicAdInsertionTypeEnum, + HlsMasterPlaylistRefreshTypeEnum, + HlsSettingsPlaylistTypeEnum, + LiveStreamEventStatusEnum, + LiveStreamEventStreamingFormatEnum, + SlateStatusEnum, +) from .types.live_stream_event_messages import LiveStreamEvent +from .types.live_stream_messages import ( + AuxiliaryAdSettings, + DashBridge, + HlsSettings, + LiveStream, + LiveStreamConditioning, + MasterPlaylistSettings, + PrefetchSettings, + PrerollSettings, +) +from .types.live_stream_service import ( + BatchActivateLiveStreamsRequest, + BatchActivateLiveStreamsResponse, + BatchArchiveLiveStreamsRequest, + BatchArchiveLiveStreamsResponse, + BatchCreateLiveStreamsRequest, + BatchCreateLiveStreamsResponse, + BatchPauseAdsLiveStreamsRequest, + BatchPauseAdsLiveStreamsResponse, + BatchPauseLiveStreamsRequest, + BatchPauseLiveStreamsResponse, + BatchRefreshMasterPlaylistsRequest, + BatchRefreshMasterPlaylistsResponse, + BatchUpdateLiveStreamsRequest, + BatchUpdateLiveStreamsResponse, + CreateLiveStreamRequest, + GetLiveStreamRequest, + ListLiveStreamsRequest, + ListLiveStreamsResponse, + UpdateLiveStreamRequest, +) from .types.mcm_earnings_messages import EarningsProductBreakdown, McmEarnings from .types.mcm_earnings_service import ( FetchMcmEarningsRequest, @@ -590,6 +841,8 @@ ListNetworksRequest, ListNetworksResponse, ) +from .types.nielsen_ctv_pacing_enum import NielsenCtvPacingEnum +from .types.non_guaranteed_deal_priority import NonGuaranteedDealPriority from .types.operating_system_messages import OperatingSystem from .types.operating_system_service import ( GetOperatingSystemRequest, @@ -604,7 +857,50 @@ ) from .types.order_enums import OrderStatusEnum from .types.order_messages import Order -from .types.order_service import GetOrderRequest, ListOrdersRequest, ListOrdersResponse +from .types.order_service import ( + BatchApproveAndOverbookOrdersRequest, + BatchApproveAndOverbookOrdersResponse, + BatchApproveOrdersRequest, + BatchApproveOrdersResponse, + BatchApproveOrdersWithoutReservationRequest, + BatchApproveOrdersWithoutReservationResponse, + BatchArchiveOrdersRequest, + BatchArchiveOrdersResponse, + BatchCreateOrdersRequest, + BatchCreateOrdersResponse, + BatchDeleteOrdersRequest, + BatchDeleteOrdersResponse, + BatchDisapproveOrdersRequest, + BatchDisapproveOrdersResponse, + BatchDisapproveOrdersWithoutReservationChangesRequest, + BatchDisapproveOrdersWithoutReservationChangesResponse, + BatchPauseOrdersRequest, + BatchPauseOrdersResponse, + BatchResumeAndOverbookOrdersRequest, + BatchResumeAndOverbookOrdersResponse, + BatchResumeOrdersRequest, + BatchResumeOrdersResponse, + BatchRetractOrdersRequest, + BatchRetractOrdersResponse, + BatchRetractOrdersWithoutReservationChangesRequest, + BatchRetractOrdersWithoutReservationChangesResponse, + BatchSubmitOrdersForApprovalAndOverbookRequest, + BatchSubmitOrdersForApprovalAndOverbookResponse, + BatchSubmitOrdersForApprovalRequest, + BatchSubmitOrdersForApprovalResponse, + BatchSubmitOrdersForApprovalWithoutReservationChangesRequest, + BatchSubmitOrdersForApprovalWithoutReservationChangesResponse, + BatchUnarchiveOrdersRequest, + BatchUnarchiveOrdersResponse, + BatchUpdateOrdersRequest, + BatchUpdateOrdersResponse, + CreateOrderRequest, + GetOrderRequest, + ListOrdersRequest, + ListOrdersResponse, + UpdateOrderRequest, +) +from .types.pacing_device_categorization_enum import PacingDeviceCategorizationEnum from .types.placement_enums import PlacementStatusEnum from .types.placement_messages import Placement from .types.placement_service import ( @@ -647,8 +943,10 @@ ListProgrammaticBuyersRequest, ListProgrammaticBuyersResponse, ) +from .types.reach_partner_enum import ReachPartnerEnum from .types.report_definition import ReportDefinition -from .types.report_messages import Report, ReportDataTable, ScheduleOptions +from .types.report_delivery import ScheduleOptions +from .types.report_messages import Report, ReportDataTable from .types.report_service import ( CreateReportRequest, FetchReportResultRowsRequest, @@ -692,6 +990,32 @@ ) from .types.size import Size from .types.size_type_enum import SizeTypeEnum +from .types.skippable_ad_type_enum import SkippableAdTypeEnum +from .types.slate_messages import Slate +from .types.slate_service import ( + BatchArchiveSlatesRequest, + BatchArchiveSlatesResponse, + BatchCreateSlatesRequest, + BatchCreateSlatesResponse, + BatchUnarchiveSlatesRequest, + BatchUnarchiveSlatesResponse, + BatchUpdateSlatesRequest, + BatchUpdateSlatesResponse, + CreateSlateRequest, + GetSlateRequest, + ListSlatesRequest, + ListSlatesResponse, + UpdateSlateRequest, +) +from .types.suggested_ad_unit_messages import SuggestedAdUnit +from .types.suggested_ad_unit_service import ( + BatchApproveSuggestedAdUnitsRequest, + BatchApproveSuggestedAdUnitsResponse, + GetSuggestedAdUnitRequest, + ListSuggestedAdUnitsRequest, + ListSuggestedAdUnitsResponse, +) +from .types.target_platform_enum import TargetPlatformEnum from .types.targeted_video_bumper_type_enum import TargetedVideoBumperTypeEnum from .types.targeting import ( AdUnitTargeting, @@ -714,6 +1038,7 @@ MobileApplicationTargeting, MobileCarrierTargeting, OperatingSystemTargeting, + RequestFormatTargeting, RequestPlatformTargeting, Targeting, TechnologyTargeting, @@ -721,6 +1046,22 @@ VideoPosition, VideoPositionTargeting, ) +from .types.targeting_preset_enums import TargetingPresetStatusEnum +from .types.targeting_preset_messages import TargetingPreset +from .types.targeting_preset_service import ( + BatchCreateTargetingPresetsRequest, + BatchCreateTargetingPresetsResponse, + BatchDeactivateTargetingPresetsRequest, + BatchDeactivateTargetingPresetsResponse, + BatchUpdateTargetingPresetsRequest, + BatchUpdateTargetingPresetsResponse, + CreateTargetingPresetRequest, + DeactivateTargetingPresetRequest, + GetTargetingPresetRequest, + ListTargetingPresetsRequest, + ListTargetingPresetsResponse, + UpdateTargetingPresetRequest, +) from .types.taxonomy_category_messages import TaxonomyCategory from .types.taxonomy_category_service import ( GetTaxonomyCategoryRequest, @@ -745,10 +1086,23 @@ ListTeamsResponse, UpdateTeamRequest, ) +from .types.third_party_company_enums import ( + ThirdPartyCompanyStatusEnum, + ThirdPartyCompanyTypeEnum, +) +from .types.third_party_company_messages import ThirdPartyCompany +from .types.third_party_company_service import ( + GetThirdPartyCompanyRequest, + ListThirdPartyCompaniesRequest, + ListThirdPartyCompaniesResponse, +) +from .types.third_party_measurement_settings import ThirdPartyMeasurementSettings from .types.time_unit_enum import TimeUnitEnum from .types.user_messages import User from .types.user_service import GetUserRequest from .types.video_position_enum import VideoPositionEnum +from .types.video_transcode_status_enum import VideoTranscodeStatusEnum +from .types.viewability_partner_enum import ViewabilityPartnerEnum from .types.web_property import WebProperty if hasattr(api_core, "check_python_version") and hasattr( @@ -835,13 +1189,28 @@ def _get_version(dependency_name): ) __all__ = ( + "ActivateCustomTargetingValueRequest", "AdBreak", + "AdBreakFillTypeEnum", + "AdBreakMarkupTypeEnum", "AdBreakServiceClient", "AdBreakStateEnum", "AdManagerError", + "AdMediaDeliveryConfig", "AdReviewCenterAd", "AdReviewCenterAdServiceClient", "AdReviewCenterAdStatusEnum", + "AdRule", + "AdRuleFrequencyCapBehaviorEnum", + "AdRuleServiceClient", + "AdRuleSlot", + "AdRuleSlotBehaviorEnum", + "AdRuleSlotBumperEnum", + "AdRuleSlotMidrollFrequencyTypeEnum", + "AdRuleStatusEnum", + "AdSpot", + "AdSpotServiceClient", + "AdSpotTargetingTypeEnum", "AdUnit", "AdUnitParent", "AdUnitServiceClient", @@ -857,21 +1226,32 @@ def _get_version(dependency_name): "AudienceSegment", "AudienceSegmentServiceClient", "AudienceSegmentTargeting", + "AuxiliaryAdSettings", "BandwidthGroup", "BandwidthGroupServiceClient", "BandwidthTargeting", + "BatchActivateAdRulesRequest", + "BatchActivateAdRulesResponse", "BatchActivateAdUnitsRequest", "BatchActivateAdUnitsResponse", + "BatchActivateCdnConfigsRequest", + "BatchActivateCdnConfigsResponse", "BatchActivateCmsMetadataKeysRequest", "BatchActivateCmsMetadataKeysResponse", "BatchActivateCmsMetadataValuesRequest", "BatchActivateCmsMetadataValuesResponse", + "BatchActivateContentBundlesRequest", + "BatchActivateContentBundlesResponse", "BatchActivateCustomFieldsRequest", "BatchActivateCustomFieldsResponse", "BatchActivateCustomTargetingKeysRequest", "BatchActivateCustomTargetingKeysResponse", + "BatchActivateCustomTargetingValuesRequest", + "BatchActivateCustomTargetingValuesResponse", "BatchActivateLabelsRequest", "BatchActivateLabelsResponse", + "BatchActivateLiveStreamsRequest", + "BatchActivateLiveStreamsResponse", "BatchActivatePlacementsRequest", "BatchActivatePlacementsResponse", "BatchActivateTeamsRequest", @@ -879,83 +1259,182 @@ def _get_version(dependency_name): "BatchAdReviewCenterAdsOperationMetadata", "BatchAllowAdReviewCenterAdsRequest", "BatchAllowAdReviewCenterAdsResponse", + "BatchApproveAndOverbookOrdersRequest", + "BatchApproveAndOverbookOrdersResponse", + "BatchApproveOrdersRequest", + "BatchApproveOrdersResponse", + "BatchApproveOrdersWithoutReservationRequest", + "BatchApproveOrdersWithoutReservationResponse", + "BatchApproveSuggestedAdUnitsRequest", + "BatchApproveSuggestedAdUnitsResponse", "BatchArchiveAdUnitsRequest", "BatchArchiveAdUnitsResponse", "BatchArchiveApplicationsRequest", "BatchArchiveApplicationsResponse", + "BatchArchiveCdnConfigsRequest", + "BatchArchiveCdnConfigsResponse", + "BatchArchiveLiveStreamsRequest", + "BatchArchiveLiveStreamsResponse", + "BatchArchiveOrdersRequest", + "BatchArchiveOrdersResponse", "BatchArchivePlacementsRequest", "BatchArchivePlacementsResponse", + "BatchArchiveSlatesRequest", + "BatchArchiveSlatesResponse", "BatchBlockAdReviewCenterAdsRequest", "BatchBlockAdReviewCenterAdsResponse", + "BatchCreateAdRulesRequest", + "BatchCreateAdRulesResponse", + "BatchCreateAdSpotsRequest", + "BatchCreateAdSpotsResponse", "BatchCreateAdUnitsRequest", "BatchCreateAdUnitsResponse", "BatchCreateApplicationsRequest", "BatchCreateApplicationsResponse", + "BatchCreateCdnConfigsRequest", + "BatchCreateCdnConfigsResponse", "BatchCreateContactsRequest", "BatchCreateContactsResponse", "BatchCreateCustomFieldsRequest", "BatchCreateCustomFieldsResponse", "BatchCreateCustomTargetingKeysRequest", "BatchCreateCustomTargetingKeysResponse", + "BatchCreateCustomTargetingValuesRequest", + "BatchCreateCustomTargetingValuesResponse", "BatchCreateEntitySignalsMappingsRequest", "BatchCreateEntitySignalsMappingsResponse", "BatchCreateLabelsRequest", "BatchCreateLabelsResponse", + "BatchCreateLiveStreamsRequest", + "BatchCreateLiveStreamsResponse", + "BatchCreateOrdersRequest", + "BatchCreateOrdersResponse", "BatchCreatePlacementsRequest", "BatchCreatePlacementsResponse", "BatchCreateSitesRequest", "BatchCreateSitesResponse", + "BatchCreateSlatesRequest", + "BatchCreateSlatesResponse", + "BatchCreateTargetingPresetsRequest", + "BatchCreateTargetingPresetsResponse", "BatchCreateTeamsRequest", "BatchCreateTeamsResponse", + "BatchDeactivateAdRulesRequest", + "BatchDeactivateAdRulesResponse", "BatchDeactivateAdUnitsRequest", "BatchDeactivateAdUnitsResponse", "BatchDeactivateCmsMetadataKeysRequest", "BatchDeactivateCmsMetadataKeysResponse", "BatchDeactivateCmsMetadataValuesRequest", "BatchDeactivateCmsMetadataValuesResponse", + "BatchDeactivateContentBundlesRequest", + "BatchDeactivateContentBundlesResponse", "BatchDeactivateCustomFieldsRequest", "BatchDeactivateCustomFieldsResponse", "BatchDeactivateCustomTargetingKeysRequest", "BatchDeactivateCustomTargetingKeysResponse", + "BatchDeactivateCustomTargetingValuesRequest", + "BatchDeactivateCustomTargetingValuesResponse", "BatchDeactivateLabelsRequest", "BatchDeactivateLabelsResponse", "BatchDeactivatePlacementsRequest", "BatchDeactivatePlacementsResponse", "BatchDeactivateSitesRequest", "BatchDeactivateSitesResponse", + "BatchDeactivateTargetingPresetsRequest", + "BatchDeactivateTargetingPresetsResponse", "BatchDeactivateTeamsRequest", "BatchDeactivateTeamsResponse", + "BatchDeleteAdRulesRequest", + "BatchDeleteOrdersRequest", + "BatchDeleteOrdersResponse", + "BatchDisapproveOrdersRequest", + "BatchDisapproveOrdersResponse", + "BatchDisapproveOrdersWithoutReservationChangesRequest", + "BatchDisapproveOrdersWithoutReservationChangesResponse", + "BatchPauseAdsLiveStreamsRequest", + "BatchPauseAdsLiveStreamsResponse", + "BatchPauseLiveStreamsRequest", + "BatchPauseLiveStreamsResponse", + "BatchPauseOrdersRequest", + "BatchPauseOrdersResponse", + "BatchRefreshMasterPlaylistsRequest", + "BatchRefreshMasterPlaylistsResponse", + "BatchResumeAndOverbookOrdersRequest", + "BatchResumeAndOverbookOrdersResponse", + "BatchResumeOrdersRequest", + "BatchResumeOrdersResponse", + "BatchRetractOrdersRequest", + "BatchRetractOrdersResponse", + "BatchRetractOrdersWithoutReservationChangesRequest", + "BatchRetractOrdersWithoutReservationChangesResponse", + "BatchSubmitOrdersForApprovalAndOverbookRequest", + "BatchSubmitOrdersForApprovalAndOverbookResponse", + "BatchSubmitOrdersForApprovalRequest", + "BatchSubmitOrdersForApprovalResponse", + "BatchSubmitOrdersForApprovalWithoutReservationChangesRequest", + "BatchSubmitOrdersForApprovalWithoutReservationChangesResponse", "BatchSubmitSitesForApprovalRequest", "BatchSubmitSitesForApprovalResponse", "BatchUnarchiveApplicationsRequest", "BatchUnarchiveApplicationsResponse", + "BatchUnarchiveOrdersRequest", + "BatchUnarchiveOrdersResponse", + "BatchUnarchiveSlatesRequest", + "BatchUnarchiveSlatesResponse", + "BatchUpdateAdRulesRequest", + "BatchUpdateAdRulesResponse", + "BatchUpdateAdSpotsRequest", + "BatchUpdateAdSpotsResponse", "BatchUpdateAdUnitsRequest", "BatchUpdateAdUnitsResponse", "BatchUpdateApplicationsRequest", "BatchUpdateApplicationsResponse", + "BatchUpdateCdnConfigsRequest", + "BatchUpdateCdnConfigsResponse", "BatchUpdateContactsRequest", "BatchUpdateContactsResponse", "BatchUpdateCustomFieldsRequest", "BatchUpdateCustomFieldsResponse", "BatchUpdateCustomTargetingKeysRequest", "BatchUpdateCustomTargetingKeysResponse", + "BatchUpdateCustomTargetingValuesRequest", + "BatchUpdateCustomTargetingValuesResponse", "BatchUpdateEntitySignalsMappingsRequest", "BatchUpdateEntitySignalsMappingsResponse", "BatchUpdateLabelsRequest", "BatchUpdateLabelsResponse", + "BatchUpdateLiveStreamsRequest", + "BatchUpdateLiveStreamsResponse", + "BatchUpdateOrdersRequest", + "BatchUpdateOrdersResponse", "BatchUpdatePlacementsRequest", "BatchUpdatePlacementsResponse", "BatchUpdateSitesRequest", "BatchUpdateSitesResponse", + "BatchUpdateSlatesRequest", + "BatchUpdateSlatesResponse", + "BatchUpdateTargetingPresetsRequest", + "BatchUpdateTargetingPresetsResponse", "BatchUpdateTeamsRequest", "BatchUpdateTeamsResponse", + "BrandLiftPartnerEnum", "Browser", "BrowserLanguage", "BrowserLanguageServiceClient", "BrowserLanguageTargeting", "BrowserServiceClient", "BrowserTargeting", + "CdnConfig", + "CdnConfigServiceClient", + "CdnConfigStatusEnum", + "CdnConfigTypeEnum", + "CdnSecurityPolicy", + "CdnSecurityPolicyOriginForwardingEnum", + "CdnSecurityPolicyTypeEnum", + "ChildContentEligibilityEnum", "ChildPublisher", + "CmsContent", "CmsMetadataKey", "CmsMetadataKeyServiceClient", "CmsMetadataKeyStatusEnum", @@ -963,6 +1442,7 @@ def _get_version(dependency_name): "CmsMetadataValue", "CmsMetadataValueServiceClient", "CmsMetadataValueStatusEnum", + "CompanionDeliveryOptionEnum", "Company", "CompanyCreditStatusEnum", "CompanyServiceClient", @@ -973,24 +1453,43 @@ def _get_version(dependency_name): "Content", "ContentBundle", "ContentBundleServiceClient", + "ContentBundleStatusEnum", "ContentLabel", "ContentLabelServiceClient", "ContentServiceClient", + "ContentStatusEnum", + "ContentStatusSourceEnum", "ContentTargeting", "CreateAdBreakRequest", + "CreateAdRuleRequest", + "CreateAdSpotRequest", "CreateAdUnitRequest", "CreateApplicationRequest", + "CreateCdnConfigRequest", "CreateContactRequest", + "CreateCreativeSetRequest", "CreateCustomFieldRequest", "CreateCustomTargetingKeyRequest", + "CreateCustomTargetingValueRequest", "CreateEntitySignalsMappingRequest", "CreateLabelRequest", + "CreateLiveStreamRequest", + "CreateOrderRequest", "CreatePlacementRequest", "CreatePrivateAuctionDealRequest", "CreatePrivateAuctionRequest", "CreateReportRequest", "CreateSiteRequest", + "CreateSlateRequest", + "CreateTargetingPresetRequest", "CreateTeamRequest", + "Creative", + "CreativePlaceholder", + "CreativePlaceholderCompanion", + "CreativeRotationTypeEnum", + "CreativeSet", + "CreativeSetServiceClient", + "CreativeTargeting", "CreativeTemplate", "CreativeTemplateServiceClient", "CreativeTemplateStatusEnum", @@ -1005,6 +1504,9 @@ def _get_version(dependency_name): "CustomFieldStatusEnum", "CustomFieldValue", "CustomFieldVisibilityEnum", + "CustomPacingCurve", + "CustomPacingGoal", + "CustomPacingGoalUnitEnum", "CustomTargeting", "CustomTargetingClause", "CustomTargetingKey", @@ -1017,10 +1519,18 @@ def _get_version(dependency_name): "CustomTargetingValueMatchTypeEnum", "CustomTargetingValueServiceClient", "CustomTargetingValueStatusEnum", + "DaiIngestError", + "DaiIngestErrorReasonEnum", + "DaiIngestStatusEnum", + "DashBridge", "DataSegmentTargeting", + "DeactivateCustomTargetingValueRequest", + "DeactivateTargetingPresetRequest", "DealBuyerPermissionTypeEnum", + "DealPriorityTierEnum", "DelegationTypeEnum", "DeleteAdBreakRequest", + "DeliveryIndicator", "DeviceCapability", "DeviceCapabilityServiceClient", "DeviceCapabilityTargeting", @@ -1031,11 +1541,14 @@ def _get_version(dependency_name): "DeviceManufacturerServiceClient", "DeviceManufacturerTargeting", "DisapprovalReason", + "DiscountTypeEnum", + "DynamicAdInsertionTypeEnum", "EarningsProductBreakdown", "EntitySignalsMapping", "EntitySignalsMappingServiceClient", "EnvironmentTypeEnum", "ExchangeSyndicationProductEnum", + "ExclusionScopeEnum", "FetchMcmEarningsRequest", "FetchMcmEarningsResponse", "FetchReportResultRowsRequest", @@ -1046,12 +1559,15 @@ def _get_version(dependency_name): "GeoTargetServiceClient", "GeoTargeting", "GetAdBreakRequest", + "GetAdRuleRequest", + "GetAdSpotRequest", "GetAdUnitRequest", "GetApplicationRequest", "GetAudienceSegmentRequest", "GetBandwidthGroupRequest", "GetBrowserLanguageRequest", "GetBrowserRequest", + "GetCdnConfigRequest", "GetCmsMetadataKeyRequest", "GetCmsMetadataValueRequest", "GetCompanyRequest", @@ -1059,6 +1575,7 @@ def _get_version(dependency_name): "GetContentBundleRequest", "GetContentLabelRequest", "GetContentRequest", + "GetCreativeSetRequest", "GetCreativeTemplateRequest", "GetCustomFieldRequest", "GetCustomTargetingKeyRequest", @@ -1071,6 +1588,7 @@ def _get_version(dependency_name): "GetLabelRequest", "GetLineItemRequest", "GetLinkedDeviceRequest", + "GetLiveStreamRequest", "GetMobileCarrierRequest", "GetMobileDeviceRequest", "GetMobileDeviceSubmodelRequest", @@ -1086,24 +1604,47 @@ def _get_version(dependency_name): "GetRichMediaAdsCompanyRequest", "GetRoleRequest", "GetSiteRequest", + "GetSlateRequest", + "GetSuggestedAdUnitRequest", + "GetTargetingPresetRequest", "GetTaxonomyCategoryRequest", "GetTeamRequest", + "GetThirdPartyCompanyRequest", "GetUserRequest", "Goal", "GoalTypeEnum", + "GrpProviderEnum", + "GrpSettings", + "GrpTargetGenderEnum", + "HlsMasterPlaylistRefreshTypeEnum", + "HlsSettings", + "HlsSettingsPlaylistTypeEnum", "InventoryTargeting", "Label", "LabelFrequencyCap", "LabelServiceClient", "LabelTypeEnum", "LineItem", + "LineItemAllowedFormatEnum", + "LineItemComputedStatusEnum", + "LineItemCostTypeEnum", + "LineItemDealInfo", + "LineItemDeliveryForecastSourceEnum", + "LineItemDeliveryRateTypeEnum", + "LineItemDiscount", + "LineItemReservationStatusEnum", "LineItemServiceClient", + "LineItemStats", "LineItemTypeEnum", "LinkedDevice", "LinkedDeviceServiceClient", "LinkedDeviceVisibilityEnum", "ListAdBreaksRequest", "ListAdBreaksResponse", + "ListAdRulesRequest", + "ListAdRulesResponse", + "ListAdSpotsRequest", + "ListAdSpotsResponse", "ListAdUnitSizesRequest", "ListAdUnitSizesResponse", "ListAdUnitsRequest", @@ -1118,6 +1659,8 @@ def _get_version(dependency_name): "ListBrowserLanguagesResponse", "ListBrowsersRequest", "ListBrowsersResponse", + "ListCdnConfigsRequest", + "ListCdnConfigsResponse", "ListCmsMetadataKeysRequest", "ListCmsMetadataKeysResponse", "ListCmsMetadataValuesRequest", @@ -1132,6 +1675,8 @@ def _get_version(dependency_name): "ListContentLabelsResponse", "ListContentRequest", "ListContentResponse", + "ListCreativeSetsRequest", + "ListCreativeSetsResponse", "ListCreativeTemplatesRequest", "ListCreativeTemplatesResponse", "ListCustomFieldsRequest", @@ -1156,6 +1701,8 @@ def _get_version(dependency_name): "ListLineItemsResponse", "ListLinkedDevicesRequest", "ListLinkedDevicesResponse", + "ListLiveStreamsRequest", + "ListLiveStreamsResponse", "ListMobileCarriersRequest", "ListMobileCarriersResponse", "ListMobileDeviceSubmodelsRequest", @@ -1186,15 +1733,30 @@ def _get_version(dependency_name): "ListRolesResponse", "ListSitesRequest", "ListSitesResponse", + "ListSlatesRequest", + "ListSlatesResponse", + "ListSuggestedAdUnitsRequest", + "ListSuggestedAdUnitsResponse", + "ListTargetingPresetsRequest", + "ListTargetingPresetsResponse", "ListTaxonomyCategoriesRequest", "ListTaxonomyCategoriesResponse", "ListTeamsRequest", "ListTeamsResponse", + "ListThirdPartyCompaniesRequest", + "ListThirdPartyCompaniesResponse", + "LiveStream", + "LiveStreamConditioning", "LiveStreamEvent", + "LiveStreamEventStatusEnum", + "LiveStreamEventStreamingFormatEnum", + "LiveStreamServiceClient", "ManualAdReviewCenterAdStatusEnum", + "MasterPlaylistSettings", "McmEarnings", "McmEarningsProductTypeEnum", "McmEarningsServiceClient", + "MediaLocation", "MobileApplicationTargeting", "MobileCarrier", "MobileCarrierServiceClient", @@ -1205,6 +1767,8 @@ def _get_version(dependency_name): "MobileDeviceSubmodelServiceClient", "Network", "NetworkServiceClient", + "NielsenCtvPacingEnum", + "NonGuaranteedDealPriority", "OperatingSystem", "OperatingSystemServiceClient", "OperatingSystemTargeting", @@ -1213,9 +1777,12 @@ def _get_version(dependency_name): "Order", "OrderServiceClient", "OrderStatusEnum", + "PacingDeviceCategorizationEnum", "Placement", "PlacementServiceClient", "PlacementStatusEnum", + "PrefetchSettings", + "PrerollSettings", "PrivateAuction", "PrivateAuctionDeal", "PrivateAuctionDealServiceClient", @@ -1223,16 +1790,19 @@ def _get_version(dependency_name): "PrivateMarketplaceDealStatusEnum", "ProgrammaticBuyer", "ProgrammaticBuyerServiceClient", + "ReachPartnerEnum", "Report", "ReportDataTable", "ReportDefinition", "ReportServiceClient", "ReportValue", + "RequestFormatTargeting", "RequestPlatformEnum", "RequestPlatformTargeting", "RichMediaAdsCompany", "RichMediaAdsCompanyGdprStatusEnum", "RichMediaAdsCompanyServiceClient", + "RoadblockingTypeEnum", "Role", "RoleServiceClient", "RoleStatusEnum", @@ -1248,10 +1818,21 @@ def _get_version(dependency_name): "SiteServiceClient", "Size", "SizeTypeEnum", + "SkippableAdTypeEnum", + "Slate", + "SlateServiceClient", + "SlateStatusEnum", "SmartSizeModeEnum", + "SourceContentConfig", + "SuggestedAdUnit", + "SuggestedAdUnitServiceClient", + "TargetPlatformEnum", "TargetWindowEnum", "TargetedVideoBumperTypeEnum", "Targeting", + "TargetingPreset", + "TargetingPresetServiceClient", + "TargetingPresetStatusEnum", "TaxonomyCategory", "TaxonomyCategoryServiceClient", "TaxonomyTypeEnum", @@ -1260,21 +1841,35 @@ def _get_version(dependency_name): "TeamServiceClient", "TeamStatusEnum", "TechnologyTargeting", + "ThirdPartyCompany", + "ThirdPartyCompanyServiceClient", + "ThirdPartyCompanyStatusEnum", + "ThirdPartyCompanyTypeEnum", + "ThirdPartyMeasurementSettings", "TimeUnitEnum", "UnitTypeEnum", "UpdateAdBreakRequest", + "UpdateAdRuleRequest", + "UpdateAdSpotRequest", "UpdateAdUnitRequest", "UpdateApplicationRequest", + "UpdateCdnConfigRequest", "UpdateContactRequest", + "UpdateCreativeSetRequest", "UpdateCustomFieldRequest", "UpdateCustomTargetingKeyRequest", + "UpdateCustomTargetingValueRequest", "UpdateEntitySignalsMappingRequest", "UpdateLabelRequest", + "UpdateLiveStreamRequest", + "UpdateOrderRequest", "UpdatePlacementRequest", "UpdatePrivateAuctionDealRequest", "UpdatePrivateAuctionRequest", "UpdateReportRequest", "UpdateSiteRequest", + "UpdateSlateRequest", + "UpdateTargetingPresetRequest", "UpdateTeamRequest", "User", "UserDomainTargeting", @@ -1282,6 +1877,8 @@ def _get_version(dependency_name): "VideoPosition", "VideoPositionEnum", "VideoPositionTargeting", + "VideoTranscodeStatusEnum", + "ViewabilityPartnerEnum", "WebProperty", "WebviewClaimingStatusEnum", ) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/gapic_metadata.json b/packages/google-ads-admanager/google/ads/admanager_v1/gapic_metadata.json index a2ef49d1ad1b..2c5cae6716e8 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/gapic_metadata.json +++ b/packages/google-ads-admanager/google/ads/admanager_v1/gapic_metadata.json @@ -63,6 +63,99 @@ } } }, + "AdRuleService": { + "clients": { + "rest": { + "libraryClient": "AdRuleServiceClient", + "rpcs": { + "BatchActivateAdRules": { + "methods": [ + "batch_activate_ad_rules" + ] + }, + "BatchCreateAdRules": { + "methods": [ + "batch_create_ad_rules" + ] + }, + "BatchDeactivateAdRules": { + "methods": [ + "batch_deactivate_ad_rules" + ] + }, + "BatchDeleteAdRules": { + "methods": [ + "batch_delete_ad_rules" + ] + }, + "BatchUpdateAdRules": { + "methods": [ + "batch_update_ad_rules" + ] + }, + "CreateAdRule": { + "methods": [ + "create_ad_rule" + ] + }, + "GetAdRule": { + "methods": [ + "get_ad_rule" + ] + }, + "ListAdRules": { + "methods": [ + "list_ad_rules" + ] + }, + "UpdateAdRule": { + "methods": [ + "update_ad_rule" + ] + } + } + } + } + }, + "AdSpotService": { + "clients": { + "rest": { + "libraryClient": "AdSpotServiceClient", + "rpcs": { + "BatchCreateAdSpots": { + "methods": [ + "batch_create_ad_spots" + ] + }, + "BatchUpdateAdSpots": { + "methods": [ + "batch_update_ad_spots" + ] + }, + "CreateAdSpot": { + "methods": [ + "create_ad_spot" + ] + }, + "GetAdSpot": { + "methods": [ + "get_ad_spot" + ] + }, + "ListAdSpots": { + "methods": [ + "list_ad_spots" + ] + }, + "UpdateAdSpot": { + "methods": [ + "update_ad_spot" + ] + } + } + } + } + }, "AdUnitService": { "clients": { "rest": { @@ -247,6 +340,55 @@ } } }, + "CdnConfigService": { + "clients": { + "rest": { + "libraryClient": "CdnConfigServiceClient", + "rpcs": { + "BatchActivateCdnConfigs": { + "methods": [ + "batch_activate_cdn_configs" + ] + }, + "BatchArchiveCdnConfigs": { + "methods": [ + "batch_archive_cdn_configs" + ] + }, + "BatchCreateCdnConfigs": { + "methods": [ + "batch_create_cdn_configs" + ] + }, + "BatchUpdateCdnConfigs": { + "methods": [ + "batch_update_cdn_configs" + ] + }, + "CreateCdnConfig": { + "methods": [ + "create_cdn_config" + ] + }, + "GetCdnConfig": { + "methods": [ + "get_cdn_config" + ] + }, + "ListCdnConfigs": { + "methods": [ + "list_cdn_configs" + ] + }, + "UpdateCdnConfig": { + "methods": [ + "update_cdn_config" + ] + } + } + } + } + }, "CmsMetadataKeyService": { "clients": { "rest": { @@ -368,6 +510,16 @@ "rest": { "libraryClient": "ContentBundleServiceClient", "rpcs": { + "BatchActivateContentBundles": { + "methods": [ + "batch_activate_content_bundles" + ] + }, + "BatchDeactivateContentBundles": { + "methods": [ + "batch_deactivate_content_bundles" + ] + }, "GetContentBundle": { "methods": [ "get_content_bundle" @@ -420,6 +572,35 @@ } } }, + "CreativeSetService": { + "clients": { + "rest": { + "libraryClient": "CreativeSetServiceClient", + "rpcs": { + "CreateCreativeSet": { + "methods": [ + "create_creative_set" + ] + }, + "GetCreativeSet": { + "methods": [ + "get_creative_set" + ] + }, + "ListCreativeSets": { + "methods": [ + "list_creative_sets" + ] + }, + "UpdateCreativeSet": { + "methods": [ + "update_creative_set" + ] + } + } + } + } + }, "CreativeTemplateService": { "clients": { "rest": { @@ -542,6 +723,31 @@ "rest": { "libraryClient": "CustomTargetingValueServiceClient", "rpcs": { + "BatchActivateCustomTargetingValues": { + "methods": [ + "batch_activate_custom_targeting_values" + ] + }, + "BatchCreateCustomTargetingValues": { + "methods": [ + "batch_create_custom_targeting_values" + ] + }, + "BatchDeactivateCustomTargetingValues": { + "methods": [ + "batch_deactivate_custom_targeting_values" + ] + }, + "BatchUpdateCustomTargetingValues": { + "methods": [ + "batch_update_custom_targeting_values" + ] + }, + "CreateCustomTargetingValue": { + "methods": [ + "create_custom_targeting_value" + ] + }, "GetCustomTargetingValue": { "methods": [ "get_custom_targeting_value" @@ -551,6 +757,11 @@ "methods": [ "list_custom_targeting_values" ] + }, + "UpdateCustomTargetingValue": { + "methods": [ + "update_custom_targeting_value" + ] } } } @@ -758,6 +969,70 @@ } } }, + "LiveStreamService": { + "clients": { + "rest": { + "libraryClient": "LiveStreamServiceClient", + "rpcs": { + "BatchActivateLiveStreams": { + "methods": [ + "batch_activate_live_streams" + ] + }, + "BatchArchiveLiveStreams": { + "methods": [ + "batch_archive_live_streams" + ] + }, + "BatchCreateLiveStreams": { + "methods": [ + "batch_create_live_streams" + ] + }, + "BatchPauseAdsLiveStreams": { + "methods": [ + "batch_pause_ads_live_streams" + ] + }, + "BatchPauseLiveStreams": { + "methods": [ + "batch_pause_live_streams" + ] + }, + "BatchRefreshMasterPlaylists": { + "methods": [ + "batch_refresh_master_playlists" + ] + }, + "BatchUpdateLiveStreams": { + "methods": [ + "batch_update_live_streams" + ] + }, + "CreateLiveStream": { + "methods": [ + "create_live_stream" + ] + }, + "GetLiveStream": { + "methods": [ + "get_live_stream" + ] + }, + "ListLiveStreams": { + "methods": [ + "list_live_streams" + ] + }, + "UpdateLiveStream": { + "methods": [ + "update_live_stream" + ] + } + } + } + } + }, "McmEarningsService": { "clients": { "rest": { @@ -891,6 +1166,96 @@ "rest": { "libraryClient": "OrderServiceClient", "rpcs": { + "BatchApproveAndOverbookOrders": { + "methods": [ + "batch_approve_and_overbook_orders" + ] + }, + "BatchApproveOrders": { + "methods": [ + "batch_approve_orders" + ] + }, + "BatchApproveOrdersWithoutReservation": { + "methods": [ + "batch_approve_orders_without_reservation" + ] + }, + "BatchArchiveOrders": { + "methods": [ + "batch_archive_orders" + ] + }, + "BatchCreateOrders": { + "methods": [ + "batch_create_orders" + ] + }, + "BatchDeleteOrders": { + "methods": [ + "batch_delete_orders" + ] + }, + "BatchDisapproveOrders": { + "methods": [ + "batch_disapprove_orders" + ] + }, + "BatchDisapproveOrdersWithoutReservationChanges": { + "methods": [ + "batch_disapprove_orders_without_reservation_changes" + ] + }, + "BatchPauseOrders": { + "methods": [ + "batch_pause_orders" + ] + }, + "BatchResumeAndOverbookOrders": { + "methods": [ + "batch_resume_and_overbook_orders" + ] + }, + "BatchResumeOrders": { + "methods": [ + "batch_resume_orders" + ] + }, + "BatchRetractOrders": { + "methods": [ + "batch_retract_orders" + ] + }, + "BatchRetractOrdersWithoutReservationChanges": { + "methods": [ + "batch_retract_orders_without_reservation_changes" + ] + }, + "BatchSubmitOrdersForApproval": { + "methods": [ + "batch_submit_orders_for_approval" + ] + }, + "BatchSubmitOrdersForApprovalAndOverbook": { + "methods": [ + "batch_submit_orders_for_approval_and_overbook" + ] + }, + "BatchSubmitOrdersForApprovalWithoutReservationChanges": { + "methods": [ + "batch_submit_orders_for_approval_without_reservation_changes" + ] + }, + "BatchUnarchiveOrders": { + "methods": [ + "batch_unarchive_orders" + ] + }, + "BatchUpdateOrders": { + "methods": [ + "batch_update_orders" + ] + }, "GetOrder": { "methods": [ "get_order" @@ -1162,6 +1527,123 @@ } } }, + "SlateService": { + "clients": { + "rest": { + "libraryClient": "SlateServiceClient", + "rpcs": { + "BatchArchiveSlates": { + "methods": [ + "batch_archive_slates" + ] + }, + "BatchCreateSlates": { + "methods": [ + "batch_create_slates" + ] + }, + "BatchUnarchiveSlates": { + "methods": [ + "batch_unarchive_slates" + ] + }, + "BatchUpdateSlates": { + "methods": [ + "batch_update_slates" + ] + }, + "CreateSlate": { + "methods": [ + "create_slate" + ] + }, + "GetSlate": { + "methods": [ + "get_slate" + ] + }, + "ListSlates": { + "methods": [ + "list_slates" + ] + }, + "UpdateSlate": { + "methods": [ + "update_slate" + ] + } + } + } + } + }, + "SuggestedAdUnitService": { + "clients": { + "rest": { + "libraryClient": "SuggestedAdUnitServiceClient", + "rpcs": { + "BatchApproveSuggestedAdUnits": { + "methods": [ + "batch_approve_suggested_ad_units" + ] + }, + "GetSuggestedAdUnit": { + "methods": [ + "get_suggested_ad_unit" + ] + }, + "ListSuggestedAdUnits": { + "methods": [ + "list_suggested_ad_units" + ] + } + } + } + } + }, + "TargetingPresetService": { + "clients": { + "rest": { + "libraryClient": "TargetingPresetServiceClient", + "rpcs": { + "BatchCreateTargetingPresets": { + "methods": [ + "batch_create_targeting_presets" + ] + }, + "BatchDeactivateTargetingPresets": { + "methods": [ + "batch_deactivate_targeting_presets" + ] + }, + "BatchUpdateTargetingPresets": { + "methods": [ + "batch_update_targeting_presets" + ] + }, + "CreateTargetingPreset": { + "methods": [ + "create_targeting_preset" + ] + }, + "GetTargetingPreset": { + "methods": [ + "get_targeting_preset" + ] + }, + "ListTargetingPresets": { + "methods": [ + "list_targeting_presets" + ] + }, + "UpdateTargetingPreset": { + "methods": [ + "update_targeting_preset" + ] + } + } + } + } + }, "TaxonomyCategoryService": { "clients": { "rest": { @@ -1230,6 +1712,25 @@ } } }, + "ThirdPartyCompanyService": { + "clients": { + "rest": { + "libraryClient": "ThirdPartyCompanyServiceClient", + "rpcs": { + "GetThirdPartyCompany": { + "methods": [ + "get_third_party_company" + ] + }, + "ListThirdPartyCompanies": { + "methods": [ + "list_third_party_companies" + ] + } + } + } + } + }, "UserService": { "clients": { "rest": { diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_break_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_break_service/client.py index c37e385aa175..e4f1540999bc 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_break_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_break_service/client.py @@ -761,7 +761,7 @@ def get_ad_break( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> ad_break_messages.AdBreak: - r"""API to retrieve an ``AdBreak`` object. + r"""Retrieves an ``AdBreak`` object. Query an ad break by its resource name or custom asset key. Check the resource's ``breakState`` field to determine its @@ -874,7 +874,7 @@ def list_ad_breaks( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListAdBreaksPager: - r"""API to retrieve a list of ``AdBreak`` objects. + r"""Lists ``AdBreak`` objects. By default, when no ``orderBy`` query parameter is specified, ad breaks are ordered reverse chronologically. However, ad breaks @@ -1006,7 +1006,7 @@ def create_ad_break( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> ad_break_messages.AdBreak: - r"""API to create an ``AdBreak`` object. + r"""Creates an ``AdBreak`` object. Informs DAI of an upcoming ad break for a live stream event, with an optional expected start time. DAI will begin decisioning @@ -1149,7 +1149,7 @@ def update_ad_break( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> ad_break_messages.AdBreak: - r"""API to update an ``AdBreak`` object. + r"""Updates an ``AdBreak`` object. Modify an ad break when its state is [``SCHEDULED``][google.ads.admanager.v1.AdBreakStateEnum.AdBreakState.SCHEDULED]. @@ -1269,7 +1269,7 @@ def delete_ad_break( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> None: - r"""API to delete an ``AdBreak`` object. + r"""Deletes an ``AdBreak`` object. Deletes and cancels an incomplete ad break, mitigating the need to wait for the current break to serve before recreating an ad diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_review_center_ad_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_review_center_ad_service/client.py index c5cf89452a45..7ec62e264604 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_review_center_ad_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_review_center_ad_service/client.py @@ -770,7 +770,7 @@ def search_ad_review_center_ads( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.SearchAdReviewCenterAdsPager: - r"""API to search for AdReviewCenterAds. + r"""Searches for AdReviewCenterAds. .. code-block:: python @@ -914,7 +914,7 @@ def batch_allow_ad_review_center_ads( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation.Operation: - r"""API to batch allow AdReviewCenterAds. + r"""Batch allows AdReviewCenterAds. This method supports partial success. Some operations may succeed while others fail. Callers should check the failedRequests field in the response to determine which @@ -1064,7 +1064,7 @@ def batch_block_ad_review_center_ads( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation.Operation: - r"""API to batch block AdReviewCenterAds. + r"""Batch blocks AdReviewCenterAds. This method supports partial success. Some operations may succeed while others fail. Callers should check the failedRequests field in the response to determine which diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_rule_service/__init__.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_rule_service/__init__.py new file mode 100644 index 000000000000..9ee19046f8af --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_rule_service/__init__.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +from .client import AdRuleServiceClient + +__all__ = ("AdRuleServiceClient",) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_rule_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_rule_service/client.py new file mode 100644 index 000000000000..00f32d65f549 --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_rule_service/client.py @@ -0,0 +1,2347 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +import json +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.ads.admanager_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.ads.admanager_v1.services.ad_rule_service import pagers +from google.ads.admanager_v1.types import ( + ad_rule_enums, + ad_rule_messages, + ad_rule_service, + targeting, +) + +from .transports.base import DEFAULT_CLIENT_INFO, AdRuleServiceTransport +from .transports.rest import AdRuleServiceRestTransport + + +class AdRuleServiceClientMeta(type): + """Metaclass for the AdRuleService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[AdRuleServiceTransport]] + _transport_registry["rest"] = AdRuleServiceRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[AdRuleServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class AdRuleServiceClient(metaclass=AdRuleServiceClientMeta): + """Provides methods for handling ``AdRule`` objects.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + Optional[str]: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # Could not parse api_endpoint; return as-is. + return api_endpoint + + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "admanager.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "admanager.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + AdRuleServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + AdRuleServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> AdRuleServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AdRuleServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def ad_rule_path( + network_code: str, + ad_rule: str, + ) -> str: + """Returns a fully-qualified ad_rule string.""" + return "networks/{network_code}/adRules/{ad_rule}".format( + network_code=network_code, + ad_rule=ad_rule, + ) + + @staticmethod + def parse_ad_rule_path(path: str) -> Dict[str, str]: + """Parses a ad_rule path into its component segments.""" + m = re.match(r"^networks/(?P.+?)/adRules/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def ad_unit_path( + network_code: str, + ad_unit: str, + ) -> str: + """Returns a fully-qualified ad_unit string.""" + return "networks/{network_code}/adUnits/{ad_unit}".format( + network_code=network_code, + ad_unit=ad_unit, + ) + + @staticmethod + def parse_ad_unit_path(path: str) -> Dict[str, str]: + """Parses a ad_unit path into its component segments.""" + m = re.match(r"^networks/(?P.+?)/adUnits/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def application_path( + network_code: str, + application: str, + ) -> str: + """Returns a fully-qualified application string.""" + return "networks/{network_code}/applications/{application}".format( + network_code=network_code, + application=application, + ) + + @staticmethod + def parse_application_path(path: str) -> Dict[str, str]: + """Parses a application path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/applications/(?P.+?)$", path + ) + return m.groupdict() if m else {} + + @staticmethod + def audience_segment_path( + network_code: str, + audience_segment: str, + ) -> str: + """Returns a fully-qualified audience_segment string.""" + return "networks/{network_code}/audienceSegments/{audience_segment}".format( + network_code=network_code, + audience_segment=audience_segment, + ) + + @staticmethod + def parse_audience_segment_path(path: str) -> Dict[str, str]: + """Parses a audience_segment path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/audienceSegments/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def bandwidth_group_path( + network_code: str, + bandwidth_group: str, + ) -> str: + """Returns a fully-qualified bandwidth_group string.""" + return "networks/{network_code}/bandwidthGroups/{bandwidth_group}".format( + network_code=network_code, + bandwidth_group=bandwidth_group, + ) + + @staticmethod + def parse_bandwidth_group_path(path: str) -> Dict[str, str]: + """Parses a bandwidth_group path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/bandwidthGroups/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def browser_path( + network_code: str, + browser: str, + ) -> str: + """Returns a fully-qualified browser string.""" + return "networks/{network_code}/browsers/{browser}".format( + network_code=network_code, + browser=browser, + ) + + @staticmethod + def parse_browser_path(path: str) -> Dict[str, str]: + """Parses a browser path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/browsers/(?P.+?)$", path + ) + return m.groupdict() if m else {} + + @staticmethod + def browser_language_path( + network_code: str, + browser_language: str, + ) -> str: + """Returns a fully-qualified browser_language string.""" + return "networks/{network_code}/browserLanguages/{browser_language}".format( + network_code=network_code, + browser_language=browser_language, + ) + + @staticmethod + def parse_browser_language_path(path: str) -> Dict[str, str]: + """Parses a browser_language path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/browserLanguages/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def cms_metadata_value_path( + network_code: str, + cms_metadata_value: str, + ) -> str: + """Returns a fully-qualified cms_metadata_value string.""" + return "networks/{network_code}/cmsMetadataValues/{cms_metadata_value}".format( + network_code=network_code, + cms_metadata_value=cms_metadata_value, + ) + + @staticmethod + def parse_cms_metadata_value_path(path: str) -> Dict[str, str]: + """Parses a cms_metadata_value path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/cmsMetadataValues/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def content_path( + network_code: str, + content: str, + ) -> str: + """Returns a fully-qualified content string.""" + return "networks/{network_code}/content/{content}".format( + network_code=network_code, + content=content, + ) + + @staticmethod + def parse_content_path(path: str) -> Dict[str, str]: + """Parses a content path into its component segments.""" + m = re.match(r"^networks/(?P.+?)/content/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def content_bundle_path( + network_code: str, + content_bundle: str, + ) -> str: + """Returns a fully-qualified content_bundle string.""" + return "networks/{network_code}/contentBundles/{content_bundle}".format( + network_code=network_code, + content_bundle=content_bundle, + ) + + @staticmethod + def parse_content_bundle_path(path: str) -> Dict[str, str]: + """Parses a content_bundle path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/contentBundles/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def custom_targeting_key_path( + network_code: str, + custom_targeting_key: str, + ) -> str: + """Returns a fully-qualified custom_targeting_key string.""" + return ( + "networks/{network_code}/customTargetingKeys/{custom_targeting_key}".format( + network_code=network_code, + custom_targeting_key=custom_targeting_key, + ) + ) + + @staticmethod + def parse_custom_targeting_key_path(path: str) -> Dict[str, str]: + """Parses a custom_targeting_key path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/customTargetingKeys/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def custom_targeting_value_path( + network_code: str, + custom_targeting_value: str, + ) -> str: + """Returns a fully-qualified custom_targeting_value string.""" + return "networks/{network_code}/customTargetingValues/{custom_targeting_value}".format( + network_code=network_code, + custom_targeting_value=custom_targeting_value, + ) + + @staticmethod + def parse_custom_targeting_value_path(path: str) -> Dict[str, str]: + """Parses a custom_targeting_value path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/customTargetingValues/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def device_capability_path( + network_code: str, + device_capability: str, + ) -> str: + """Returns a fully-qualified device_capability string.""" + return "networks/{network_code}/deviceCapabilities/{device_capability}".format( + network_code=network_code, + device_capability=device_capability, + ) + + @staticmethod + def parse_device_capability_path(path: str) -> Dict[str, str]: + """Parses a device_capability path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/deviceCapabilities/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def device_category_path( + network_code: str, + device_category: str, + ) -> str: + """Returns a fully-qualified device_category string.""" + return "networks/{network_code}/deviceCategories/{device_category}".format( + network_code=network_code, + device_category=device_category, + ) + + @staticmethod + def parse_device_category_path(path: str) -> Dict[str, str]: + """Parses a device_category path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/deviceCategories/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def device_manufacturer_path( + network_code: str, + device_manufacturer: str, + ) -> str: + """Returns a fully-qualified device_manufacturer string.""" + return ( + "networks/{network_code}/deviceManufacturers/{device_manufacturer}".format( + network_code=network_code, + device_manufacturer=device_manufacturer, + ) + ) + + @staticmethod + def parse_device_manufacturer_path(path: str) -> Dict[str, str]: + """Parses a device_manufacturer path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/deviceManufacturers/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def geo_target_path( + network_code: str, + geo_target: str, + ) -> str: + """Returns a fully-qualified geo_target string.""" + return "networks/{network_code}/geoTargets/{geo_target}".format( + network_code=network_code, + geo_target=geo_target, + ) + + @staticmethod + def parse_geo_target_path(path: str) -> Dict[str, str]: + """Parses a geo_target path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/geoTargets/(?P.+?)$", path + ) + return m.groupdict() if m else {} + + @staticmethod + def mobile_carrier_path( + network_code: str, + mobile_carrier: str, + ) -> str: + """Returns a fully-qualified mobile_carrier string.""" + return "networks/{network_code}/mobileCarriers/{mobile_carrier}".format( + network_code=network_code, + mobile_carrier=mobile_carrier, + ) + + @staticmethod + def parse_mobile_carrier_path(path: str) -> Dict[str, str]: + """Parses a mobile_carrier path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/mobileCarriers/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def mobile_device_path( + network_code: str, + mobile_device: str, + ) -> str: + """Returns a fully-qualified mobile_device string.""" + return "networks/{network_code}/mobileDevices/{mobile_device}".format( + network_code=network_code, + mobile_device=mobile_device, + ) + + @staticmethod + def parse_mobile_device_path(path: str) -> Dict[str, str]: + """Parses a mobile_device path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/mobileDevices/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def mobile_device_submodel_path( + network_code: str, + mobile_device_submodel: str, + ) -> str: + """Returns a fully-qualified mobile_device_submodel string.""" + return "networks/{network_code}/mobileDeviceSubmodels/{mobile_device_submodel}".format( + network_code=network_code, + mobile_device_submodel=mobile_device_submodel, + ) + + @staticmethod + def parse_mobile_device_submodel_path(path: str) -> Dict[str, str]: + """Parses a mobile_device_submodel path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/mobileDeviceSubmodels/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def network_path( + network_code: str, + ) -> str: + """Returns a fully-qualified network string.""" + return "networks/{network_code}".format( + network_code=network_code, + ) + + @staticmethod + def parse_network_path(path: str) -> Dict[str, str]: + """Parses a network path into its component segments.""" + m = re.match(r"^networks/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def operating_system_path( + network_code: str, + operating_system: str, + ) -> str: + """Returns a fully-qualified operating_system string.""" + return "networks/{network_code}/operatingSystems/{operating_system}".format( + network_code=network_code, + operating_system=operating_system, + ) + + @staticmethod + def parse_operating_system_path(path: str) -> Dict[str, str]: + """Parses a operating_system path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/operatingSystems/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def operating_system_version_path( + network_code: str, + operating_system_version: str, + ) -> str: + """Returns a fully-qualified operating_system_version string.""" + return "networks/{network_code}/operatingSystemVersions/{operating_system_version}".format( + network_code=network_code, + operating_system_version=operating_system_version, + ) + + @staticmethod + def parse_operating_system_version_path(path: str) -> Dict[str, str]: + """Parses a operating_system_version path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/operatingSystemVersions/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def placement_path( + network_code: str, + placement: str, + ) -> str: + """Returns a fully-qualified placement string.""" + return "networks/{network_code}/placements/{placement}".format( + network_code=network_code, + placement=placement, + ) + + @staticmethod + def parse_placement_path(path: str) -> Dict[str, str]: + """Parses a placement path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/placements/(?P.+?)$", path + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = AdRuleServiceClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = AdRuleServiceClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = AdRuleServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = AdRuleServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = AdRuleServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = AdRuleServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, AdRuleServiceTransport, Callable[..., AdRuleServiceTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the ad rule service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,AdRuleServiceTransport,Callable[..., AdRuleServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the AdRuleServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + AdRuleServiceClient._read_environment_variables() + ) + self._client_cert_source = AdRuleServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = AdRuleServiceClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, AdRuleServiceTransport) + if transport_provided: + # transport is a AdRuleServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(AdRuleServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or AdRuleServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[AdRuleServiceTransport], Callable[..., AdRuleServiceTransport] + ] = ( + AdRuleServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., AdRuleServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.ads.admanager_v1.AdRuleServiceClient`.", + extra={ + "serviceName": "google.ads.admanager.v1.AdRuleService", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.ads.admanager.v1.AdRuleService", + "credentialsType": None, + }, + ) + + def get_ad_rule( + self, + request: Optional[Union[ad_rule_service.GetAdRuleRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> ad_rule_messages.AdRule: + r"""Retrieves an ``AdRule`` object. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_get_ad_rule(): + # Create a client + client = admanager_v1.AdRuleServiceClient() + + # Initialize request argument(s) + request = admanager_v1.GetAdRuleRequest( + name="name_value", + ) + + # Make the request + response = client.get_ad_rule(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.GetAdRuleRequest, dict]): + The request object. Request object for ``GetAdRule`` method. + name (str): + Required. The resource name of the AdRule. Format: + ``networks/{network_code}/adRules/{ad_rule_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.admanager_v1.types.AdRule: + An AdRule contains data that the ad + server will use to generate a playlist + of video ads. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, ad_rule_service.GetAdRuleRequest): + request = ad_rule_service.GetAdRuleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_ad_rule] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_ad_rules( + self, + request: Optional[Union[ad_rule_service.ListAdRulesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAdRulesPager: + r"""Lists ``AdRule`` objects. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_list_ad_rules(): + # Create a client + client = admanager_v1.AdRuleServiceClient() + + # Initialize request argument(s) + request = admanager_v1.ListAdRulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_ad_rules(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.ListAdRulesRequest, dict]): + The request object. Request object for ``ListAdRules`` method. + parent (str): + Required. The parent, which owns this collection of + AdRules. Format: ``networks/{network_code}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.admanager_v1.services.ad_rule_service.pagers.ListAdRulesPager: + Response object for ListAdRulesRequest containing matching AdRule + objects. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, ad_rule_service.ListAdRulesRequest): + request = ad_rule_service.ListAdRulesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_ad_rules] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListAdRulesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_ad_rule( + self, + request: Optional[Union[ad_rule_service.CreateAdRuleRequest, dict]] = None, + *, + parent: Optional[str] = None, + ad_rule: Optional[ad_rule_messages.AdRule] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> ad_rule_messages.AdRule: + r"""Creates a ``AdRule`` object. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_create_ad_rule(): + # Create a client + client = admanager_v1.AdRuleServiceClient() + + # Initialize request argument(s) + request = admanager_v1.CreateAdRuleRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_ad_rule(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.CreateAdRuleRequest, dict]): + The request object. Request object for ``CreateAdRule`` method. + parent (str): + Required. The parent resource where this ``AdRule`` will + be created. Format: ``networks/{network_code}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ad_rule (google.ads.admanager_v1.types.AdRule): + Required. The ``AdRule`` to create. + This corresponds to the ``ad_rule`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.admanager_v1.types.AdRule: + An AdRule contains data that the ad + server will use to generate a playlist + of video ads. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, ad_rule] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, ad_rule_service.CreateAdRuleRequest): + request = ad_rule_service.CreateAdRuleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if ad_rule is not None: + request.ad_rule = ad_rule + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_ad_rule] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_create_ad_rules( + self, + request: Optional[ + Union[ad_rule_service.BatchCreateAdRulesRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + requests: Optional[MutableSequence[ad_rule_service.CreateAdRuleRequest]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> ad_rule_service.BatchCreateAdRulesResponse: + r"""Batch creates ``AdRule`` objects. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_batch_create_ad_rules(): + # Create a client + client = admanager_v1.AdRuleServiceClient() + + # Initialize request argument(s) + requests = admanager_v1.CreateAdRuleRequest() + requests.parent = "parent_value" + + request = admanager_v1.BatchCreateAdRulesRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = client.batch_create_ad_rules(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.BatchCreateAdRulesRequest, dict]): + The request object. Request object for ``BatchCreateAdRules`` method. + parent (str): + Required. The parent resource where ``AdRules`` will be + created. Format: ``networks/{network_code}`` The parent + field in the CreateAdRuleRequest must match this field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + requests (MutableSequence[google.ads.admanager_v1.types.CreateAdRuleRequest]): + Required. The ``AdRule`` objects to create. A maximum of + 100 objects can be created in a batch. + + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.admanager_v1.types.BatchCreateAdRulesResponse: + Response object for BatchCreateAdRules method. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, requests] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, ad_rule_service.BatchCreateAdRulesRequest): + request = ad_rule_service.BatchCreateAdRulesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_create_ad_rules] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_ad_rule( + self, + request: Optional[Union[ad_rule_service.UpdateAdRuleRequest, dict]] = None, + *, + ad_rule: Optional[ad_rule_messages.AdRule] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> ad_rule_messages.AdRule: + r"""Updates a ``AdRule`` object. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_update_ad_rule(): + # Create a client + client = admanager_v1.AdRuleServiceClient() + + # Initialize request argument(s) + request = admanager_v1.UpdateAdRuleRequest( + ) + + # Make the request + response = client.update_ad_rule(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.UpdateAdRuleRequest, dict]): + The request object. Request object for ``UpdateAdRule`` method. + ad_rule (google.ads.admanager_v1.types.AdRule): + Required. The ``AdRule`` to update. + + The ``AdRule``'s ``name`` is used to identify the + ``AdRule`` to update. + + This corresponds to the ``ad_rule`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to + update. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.admanager_v1.types.AdRule: + An AdRule contains data that the ad + server will use to generate a playlist + of video ads. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [ad_rule, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, ad_rule_service.UpdateAdRuleRequest): + request = ad_rule_service.UpdateAdRuleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if ad_rule is not None: + request.ad_rule = ad_rule + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_ad_rule] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("ad_rule.name", request.ad_rule.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_update_ad_rules( + self, + request: Optional[ + Union[ad_rule_service.BatchUpdateAdRulesRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + requests: Optional[MutableSequence[ad_rule_service.UpdateAdRuleRequest]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> ad_rule_service.BatchUpdateAdRulesResponse: + r"""Batch updates ``AdRule`` objects. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_batch_update_ad_rules(): + # Create a client + client = admanager_v1.AdRuleServiceClient() + + # Initialize request argument(s) + request = admanager_v1.BatchUpdateAdRulesRequest( + parent="parent_value", + ) + + # Make the request + response = client.batch_update_ad_rules(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.BatchUpdateAdRulesRequest, dict]): + The request object. Request object for ``BatchUpdateAdRules`` method. + parent (str): + Required. The parent resource where ``AdRules`` will be + updated. Format: ``networks/{network_code}`` The parent + field in the UpdateAdRuleRequest must match this field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + requests (MutableSequence[google.ads.admanager_v1.types.UpdateAdRuleRequest]): + Required. The ``AdRule`` objects to update. A maximum of + 100 objects can be updated in a batch. + + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.admanager_v1.types.BatchUpdateAdRulesResponse: + Response object for BatchUpdateAdRules method. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, requests] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, ad_rule_service.BatchUpdateAdRulesRequest): + request = ad_rule_service.BatchUpdateAdRulesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_update_ad_rules] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_activate_ad_rules( + self, + request: Optional[ + Union[ad_rule_service.BatchActivateAdRulesRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + names: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> ad_rule_service.BatchActivateAdRulesResponse: + r"""Activates a list of ``AdRule`` objects. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_batch_activate_ad_rules(): + # Create a client + client = admanager_v1.AdRuleServiceClient() + + # Initialize request argument(s) + request = admanager_v1.BatchActivateAdRulesRequest( + parent="parent_value", + names=['names_value1', 'names_value2'], + ) + + # Make the request + response = client.batch_activate_ad_rules(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.BatchActivateAdRulesRequest, dict]): + The request object. Request object for ``BatchActivateAdRules`` method. + parent (str): + Required. Format: ``networks/{network_code}`` + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + names (MutableSequence[str]): + Required. Resource names for the AdRule. Format: + ``networks/{network_code}/adRules/{ad_rule}`` + + This corresponds to the ``names`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.admanager_v1.types.BatchActivateAdRulesResponse: + Response object for BatchActivateAdRules method. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, names] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, ad_rule_service.BatchActivateAdRulesRequest): + request = ad_rule_service.BatchActivateAdRulesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if names is not None: + request.names = names + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_activate_ad_rules] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_deactivate_ad_rules( + self, + request: Optional[ + Union[ad_rule_service.BatchDeactivateAdRulesRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + names: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> ad_rule_service.BatchDeactivateAdRulesResponse: + r"""Deactivates a list of ``AdRule`` objects. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_batch_deactivate_ad_rules(): + # Create a client + client = admanager_v1.AdRuleServiceClient() + + # Initialize request argument(s) + request = admanager_v1.BatchDeactivateAdRulesRequest( + parent="parent_value", + names=['names_value1', 'names_value2'], + ) + + # Make the request + response = client.batch_deactivate_ad_rules(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.BatchDeactivateAdRulesRequest, dict]): + The request object. Request object for ``BatchDeactivateAdRules`` method. + parent (str): + Required. Format: ``networks/{network_code}`` + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + names (MutableSequence[str]): + Required. Resource names for the AdRule. Format: + ``networks/{network_code}/adRules/{ad_rule}`` + + This corresponds to the ``names`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.admanager_v1.types.BatchDeactivateAdRulesResponse: + Response object for BatchDeactivateAdRules method. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, names] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, ad_rule_service.BatchDeactivateAdRulesRequest): + request = ad_rule_service.BatchDeactivateAdRulesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if names is not None: + request.names = names + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.batch_deactivate_ad_rules + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_delete_ad_rules( + self, + request: Optional[ + Union[ad_rule_service.BatchDeleteAdRulesRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + names: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a list of ``AdRule`` objects. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_batch_delete_ad_rules(): + # Create a client + client = admanager_v1.AdRuleServiceClient() + + # Initialize request argument(s) + request = admanager_v1.BatchDeleteAdRulesRequest( + parent="parent_value", + names=['names_value1', 'names_value2'], + ) + + # Make the request + client.batch_delete_ad_rules(request=request) + + Args: + request (Union[google.ads.admanager_v1.types.BatchDeleteAdRulesRequest, dict]): + The request object. Request object for ``BatchDeleteAdRules`` method. + parent (str): + Required. Format: ``networks/{network_code}`` + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + names (MutableSequence[str]): + Required. Resource names for the AdRule. Format: + ``networks/{network_code}/adRules/{ad_rule}`` + + This corresponds to the ``names`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, names] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, ad_rule_service.BatchDeleteAdRulesRequest): + request = ad_rule_service.BatchDeleteAdRulesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if names is not None: + request.names = names + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_delete_ad_rules] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def __enter__(self) -> "AdRuleServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("AdRuleServiceClient",) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_rule_service/pagers.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_rule_service/pagers.py new file mode 100644 index 000000000000..e5e543da60f8 --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_rule_service/pagers.py @@ -0,0 +1,117 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.ads.admanager_v1.types import ad_rule_messages, ad_rule_service + + +class ListAdRulesPager: + """A pager for iterating through ``list_ad_rules`` requests. + + This class thinly wraps an initial + :class:`google.ads.admanager_v1.types.ListAdRulesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``ad_rules`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAdRules`` requests and continue to iterate + through the ``ad_rules`` field on the + corresponding responses. + + All the usual :class:`google.ads.admanager_v1.types.ListAdRulesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., ad_rule_service.ListAdRulesResponse], + request: ad_rule_service.ListAdRulesRequest, + response: ad_rule_service.ListAdRulesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.ads.admanager_v1.types.ListAdRulesRequest): + The initial request object. + response (google.ads.admanager_v1.types.ListAdRulesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = ad_rule_service.ListAdRulesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[ad_rule_service.ListAdRulesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[ad_rule_messages.AdRule]: + for page in self.pages: + yield from page.ad_rules + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_rule_service/transports/README.rst b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_rule_service/transports/README.rst new file mode 100644 index 000000000000..9e5ddfd9f201 --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_rule_service/transports/README.rst @@ -0,0 +1,10 @@ + +transport inheritance structure +_______________________________ + +``AdRuleServiceTransport`` is the ABC for all transports. + +- public child ``AdRuleServiceGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``). +- public child ``AdRuleServiceGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``). +- private child ``_BaseAdRuleServiceRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``). +- public child ``AdRuleServiceRestTransport`` for sync REST transport with inner classes ``METHOD`` derived from the parent's corresponding ``_BaseMETHOD`` classes (defined in ``rest.py``). diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_rule_service/transports/__init__.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_rule_service/transports/__init__.py new file mode 100644 index 000000000000..bd354d4e86e6 --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_rule_service/transports/__init__.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import AdRuleServiceTransport +from .rest import AdRuleServiceRestInterceptor, AdRuleServiceRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AdRuleServiceTransport]] +_transport_registry["rest"] = AdRuleServiceRestTransport + +__all__ = ( + "AdRuleServiceTransport", + "AdRuleServiceRestTransport", + "AdRuleServiceRestInterceptor", +) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_rule_service/transports/base.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_rule_service/transports/base.py new file mode 100644 index 000000000000..eae0b5672e34 --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_rule_service/transports/base.py @@ -0,0 +1,333 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.protobuf +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.ads.admanager_v1 import gapic_version as package_version +from google.ads.admanager_v1.types import ad_rule_messages, ad_rule_service + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class AdRuleServiceTransport(abc.ABC): + """Abstract transport class for AdRuleService.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/admanager", + "https://www.googleapis.com/auth/admanager.readonly", + ) + + DEFAULT_HOST: str = "admanager.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'admanager.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_ad_rule: gapic_v1.method.wrap_method( + self.get_ad_rule, + default_timeout=None, + client_info=client_info, + ), + self.list_ad_rules: gapic_v1.method.wrap_method( + self.list_ad_rules, + default_timeout=None, + client_info=client_info, + ), + self.create_ad_rule: gapic_v1.method.wrap_method( + self.create_ad_rule, + default_timeout=None, + client_info=client_info, + ), + self.batch_create_ad_rules: gapic_v1.method.wrap_method( + self.batch_create_ad_rules, + default_timeout=None, + client_info=client_info, + ), + self.update_ad_rule: gapic_v1.method.wrap_method( + self.update_ad_rule, + default_timeout=None, + client_info=client_info, + ), + self.batch_update_ad_rules: gapic_v1.method.wrap_method( + self.batch_update_ad_rules, + default_timeout=None, + client_info=client_info, + ), + self.batch_activate_ad_rules: gapic_v1.method.wrap_method( + self.batch_activate_ad_rules, + default_timeout=None, + client_info=client_info, + ), + self.batch_deactivate_ad_rules: gapic_v1.method.wrap_method( + self.batch_deactivate_ad_rules, + default_timeout=None, + client_info=client_info, + ), + self.batch_delete_ad_rules: gapic_v1.method.wrap_method( + self.batch_delete_ad_rules, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def get_ad_rule( + self, + ) -> Callable[ + [ad_rule_service.GetAdRuleRequest], + Union[ad_rule_messages.AdRule, Awaitable[ad_rule_messages.AdRule]], + ]: + raise NotImplementedError() + + @property + def list_ad_rules( + self, + ) -> Callable[ + [ad_rule_service.ListAdRulesRequest], + Union[ + ad_rule_service.ListAdRulesResponse, + Awaitable[ad_rule_service.ListAdRulesResponse], + ], + ]: + raise NotImplementedError() + + @property + def create_ad_rule( + self, + ) -> Callable[ + [ad_rule_service.CreateAdRuleRequest], + Union[ad_rule_messages.AdRule, Awaitable[ad_rule_messages.AdRule]], + ]: + raise NotImplementedError() + + @property + def batch_create_ad_rules( + self, + ) -> Callable[ + [ad_rule_service.BatchCreateAdRulesRequest], + Union[ + ad_rule_service.BatchCreateAdRulesResponse, + Awaitable[ad_rule_service.BatchCreateAdRulesResponse], + ], + ]: + raise NotImplementedError() + + @property + def update_ad_rule( + self, + ) -> Callable[ + [ad_rule_service.UpdateAdRuleRequest], + Union[ad_rule_messages.AdRule, Awaitable[ad_rule_messages.AdRule]], + ]: + raise NotImplementedError() + + @property + def batch_update_ad_rules( + self, + ) -> Callable[ + [ad_rule_service.BatchUpdateAdRulesRequest], + Union[ + ad_rule_service.BatchUpdateAdRulesResponse, + Awaitable[ad_rule_service.BatchUpdateAdRulesResponse], + ], + ]: + raise NotImplementedError() + + @property + def batch_activate_ad_rules( + self, + ) -> Callable[ + [ad_rule_service.BatchActivateAdRulesRequest], + Union[ + ad_rule_service.BatchActivateAdRulesResponse, + Awaitable[ad_rule_service.BatchActivateAdRulesResponse], + ], + ]: + raise NotImplementedError() + + @property + def batch_deactivate_ad_rules( + self, + ) -> Callable[ + [ad_rule_service.BatchDeactivateAdRulesRequest], + Union[ + ad_rule_service.BatchDeactivateAdRulesResponse, + Awaitable[ad_rule_service.BatchDeactivateAdRulesResponse], + ], + ]: + raise NotImplementedError() + + @property + def batch_delete_ad_rules( + self, + ) -> Callable[ + [ad_rule_service.BatchDeleteAdRulesRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("AdRuleServiceTransport",) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_rule_service/transports/rest.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_rule_service/transports/rest.py new file mode 100644 index 000000000000..f9c0759ab743 --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_rule_service/transports/rest.py @@ -0,0 +1,2387 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +import dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.ads.admanager_v1.types import ad_rule_messages, ad_rule_service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseAdRuleServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class AdRuleServiceRestInterceptor: + """Interceptor for AdRuleService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the AdRuleServiceRestTransport. + + .. code-block:: python + class MyCustomAdRuleServiceInterceptor(AdRuleServiceRestInterceptor): + def pre_batch_activate_ad_rules(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_activate_ad_rules(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_batch_create_ad_rules(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_create_ad_rules(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_batch_deactivate_ad_rules(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_deactivate_ad_rules(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_batch_delete_ad_rules(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_batch_update_ad_rules(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_update_ad_rules(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_ad_rule(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_ad_rule(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_ad_rule(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_ad_rule(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_ad_rules(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_ad_rules(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_ad_rule(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_ad_rule(self, response): + logging.log(f"Received response: {response}") + return response + + transport = AdRuleServiceRestTransport(interceptor=MyCustomAdRuleServiceInterceptor()) + client = AdRuleServiceClient(transport=transport) + + + """ + + def pre_batch_activate_ad_rules( + self, + request: ad_rule_service.BatchActivateAdRulesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + ad_rule_service.BatchActivateAdRulesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_activate_ad_rules + + Override in a subclass to manipulate the request or metadata + before they are sent to the AdRuleService server. + """ + return request, metadata + + def post_batch_activate_ad_rules( + self, response: ad_rule_service.BatchActivateAdRulesResponse + ) -> ad_rule_service.BatchActivateAdRulesResponse: + """Post-rpc interceptor for batch_activate_ad_rules + + DEPRECATED. Please use the `post_batch_activate_ad_rules_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AdRuleService server but before + it is returned to user code. This `post_batch_activate_ad_rules` interceptor runs + before the `post_batch_activate_ad_rules_with_metadata` interceptor. + """ + return response + + def post_batch_activate_ad_rules_with_metadata( + self, + response: ad_rule_service.BatchActivateAdRulesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + ad_rule_service.BatchActivateAdRulesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for batch_activate_ad_rules + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AdRuleService server but before it is returned to user code. + + We recommend only using this `post_batch_activate_ad_rules_with_metadata` + interceptor in new development instead of the `post_batch_activate_ad_rules` interceptor. + When both interceptors are used, this `post_batch_activate_ad_rules_with_metadata` interceptor runs after the + `post_batch_activate_ad_rules` interceptor. The (possibly modified) response returned by + `post_batch_activate_ad_rules` will be passed to + `post_batch_activate_ad_rules_with_metadata`. + """ + return response, metadata + + def pre_batch_create_ad_rules( + self, + request: ad_rule_service.BatchCreateAdRulesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + ad_rule_service.BatchCreateAdRulesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_create_ad_rules + + Override in a subclass to manipulate the request or metadata + before they are sent to the AdRuleService server. + """ + return request, metadata + + def post_batch_create_ad_rules( + self, response: ad_rule_service.BatchCreateAdRulesResponse + ) -> ad_rule_service.BatchCreateAdRulesResponse: + """Post-rpc interceptor for batch_create_ad_rules + + DEPRECATED. Please use the `post_batch_create_ad_rules_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AdRuleService server but before + it is returned to user code. This `post_batch_create_ad_rules` interceptor runs + before the `post_batch_create_ad_rules_with_metadata` interceptor. + """ + return response + + def post_batch_create_ad_rules_with_metadata( + self, + response: ad_rule_service.BatchCreateAdRulesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + ad_rule_service.BatchCreateAdRulesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for batch_create_ad_rules + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AdRuleService server but before it is returned to user code. + + We recommend only using this `post_batch_create_ad_rules_with_metadata` + interceptor in new development instead of the `post_batch_create_ad_rules` interceptor. + When both interceptors are used, this `post_batch_create_ad_rules_with_metadata` interceptor runs after the + `post_batch_create_ad_rules` interceptor. The (possibly modified) response returned by + `post_batch_create_ad_rules` will be passed to + `post_batch_create_ad_rules_with_metadata`. + """ + return response, metadata + + def pre_batch_deactivate_ad_rules( + self, + request: ad_rule_service.BatchDeactivateAdRulesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + ad_rule_service.BatchDeactivateAdRulesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_deactivate_ad_rules + + Override in a subclass to manipulate the request or metadata + before they are sent to the AdRuleService server. + """ + return request, metadata + + def post_batch_deactivate_ad_rules( + self, response: ad_rule_service.BatchDeactivateAdRulesResponse + ) -> ad_rule_service.BatchDeactivateAdRulesResponse: + """Post-rpc interceptor for batch_deactivate_ad_rules + + DEPRECATED. Please use the `post_batch_deactivate_ad_rules_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AdRuleService server but before + it is returned to user code. This `post_batch_deactivate_ad_rules` interceptor runs + before the `post_batch_deactivate_ad_rules_with_metadata` interceptor. + """ + return response + + def post_batch_deactivate_ad_rules_with_metadata( + self, + response: ad_rule_service.BatchDeactivateAdRulesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + ad_rule_service.BatchDeactivateAdRulesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for batch_deactivate_ad_rules + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AdRuleService server but before it is returned to user code. + + We recommend only using this `post_batch_deactivate_ad_rules_with_metadata` + interceptor in new development instead of the `post_batch_deactivate_ad_rules` interceptor. + When both interceptors are used, this `post_batch_deactivate_ad_rules_with_metadata` interceptor runs after the + `post_batch_deactivate_ad_rules` interceptor. The (possibly modified) response returned by + `post_batch_deactivate_ad_rules` will be passed to + `post_batch_deactivate_ad_rules_with_metadata`. + """ + return response, metadata + + def pre_batch_delete_ad_rules( + self, + request: ad_rule_service.BatchDeleteAdRulesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + ad_rule_service.BatchDeleteAdRulesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_delete_ad_rules + + Override in a subclass to manipulate the request or metadata + before they are sent to the AdRuleService server. + """ + return request, metadata + + def pre_batch_update_ad_rules( + self, + request: ad_rule_service.BatchUpdateAdRulesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + ad_rule_service.BatchUpdateAdRulesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_update_ad_rules + + Override in a subclass to manipulate the request or metadata + before they are sent to the AdRuleService server. + """ + return request, metadata + + def post_batch_update_ad_rules( + self, response: ad_rule_service.BatchUpdateAdRulesResponse + ) -> ad_rule_service.BatchUpdateAdRulesResponse: + """Post-rpc interceptor for batch_update_ad_rules + + DEPRECATED. Please use the `post_batch_update_ad_rules_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AdRuleService server but before + it is returned to user code. This `post_batch_update_ad_rules` interceptor runs + before the `post_batch_update_ad_rules_with_metadata` interceptor. + """ + return response + + def post_batch_update_ad_rules_with_metadata( + self, + response: ad_rule_service.BatchUpdateAdRulesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + ad_rule_service.BatchUpdateAdRulesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for batch_update_ad_rules + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AdRuleService server but before it is returned to user code. + + We recommend only using this `post_batch_update_ad_rules_with_metadata` + interceptor in new development instead of the `post_batch_update_ad_rules` interceptor. + When both interceptors are used, this `post_batch_update_ad_rules_with_metadata` interceptor runs after the + `post_batch_update_ad_rules` interceptor. The (possibly modified) response returned by + `post_batch_update_ad_rules` will be passed to + `post_batch_update_ad_rules_with_metadata`. + """ + return response, metadata + + def pre_create_ad_rule( + self, + request: ad_rule_service.CreateAdRuleRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + ad_rule_service.CreateAdRuleRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_ad_rule + + Override in a subclass to manipulate the request or metadata + before they are sent to the AdRuleService server. + """ + return request, metadata + + def post_create_ad_rule( + self, response: ad_rule_messages.AdRule + ) -> ad_rule_messages.AdRule: + """Post-rpc interceptor for create_ad_rule + + DEPRECATED. Please use the `post_create_ad_rule_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AdRuleService server but before + it is returned to user code. This `post_create_ad_rule` interceptor runs + before the `post_create_ad_rule_with_metadata` interceptor. + """ + return response + + def post_create_ad_rule_with_metadata( + self, + response: ad_rule_messages.AdRule, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ad_rule_messages.AdRule, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_ad_rule + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AdRuleService server but before it is returned to user code. + + We recommend only using this `post_create_ad_rule_with_metadata` + interceptor in new development instead of the `post_create_ad_rule` interceptor. + When both interceptors are used, this `post_create_ad_rule_with_metadata` interceptor runs after the + `post_create_ad_rule` interceptor. The (possibly modified) response returned by + `post_create_ad_rule` will be passed to + `post_create_ad_rule_with_metadata`. + """ + return response, metadata + + def pre_get_ad_rule( + self, + request: ad_rule_service.GetAdRuleRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + ad_rule_service.GetAdRuleRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_ad_rule + + Override in a subclass to manipulate the request or metadata + before they are sent to the AdRuleService server. + """ + return request, metadata + + def post_get_ad_rule( + self, response: ad_rule_messages.AdRule + ) -> ad_rule_messages.AdRule: + """Post-rpc interceptor for get_ad_rule + + DEPRECATED. Please use the `post_get_ad_rule_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AdRuleService server but before + it is returned to user code. This `post_get_ad_rule` interceptor runs + before the `post_get_ad_rule_with_metadata` interceptor. + """ + return response + + def post_get_ad_rule_with_metadata( + self, + response: ad_rule_messages.AdRule, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ad_rule_messages.AdRule, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_ad_rule + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AdRuleService server but before it is returned to user code. + + We recommend only using this `post_get_ad_rule_with_metadata` + interceptor in new development instead of the `post_get_ad_rule` interceptor. + When both interceptors are used, this `post_get_ad_rule_with_metadata` interceptor runs after the + `post_get_ad_rule` interceptor. The (possibly modified) response returned by + `post_get_ad_rule` will be passed to + `post_get_ad_rule_with_metadata`. + """ + return response, metadata + + def pre_list_ad_rules( + self, + request: ad_rule_service.ListAdRulesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + ad_rule_service.ListAdRulesRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_ad_rules + + Override in a subclass to manipulate the request or metadata + before they are sent to the AdRuleService server. + """ + return request, metadata + + def post_list_ad_rules( + self, response: ad_rule_service.ListAdRulesResponse + ) -> ad_rule_service.ListAdRulesResponse: + """Post-rpc interceptor for list_ad_rules + + DEPRECATED. Please use the `post_list_ad_rules_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AdRuleService server but before + it is returned to user code. This `post_list_ad_rules` interceptor runs + before the `post_list_ad_rules_with_metadata` interceptor. + """ + return response + + def post_list_ad_rules_with_metadata( + self, + response: ad_rule_service.ListAdRulesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + ad_rule_service.ListAdRulesResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_ad_rules + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AdRuleService server but before it is returned to user code. + + We recommend only using this `post_list_ad_rules_with_metadata` + interceptor in new development instead of the `post_list_ad_rules` interceptor. + When both interceptors are used, this `post_list_ad_rules_with_metadata` interceptor runs after the + `post_list_ad_rules` interceptor. The (possibly modified) response returned by + `post_list_ad_rules` will be passed to + `post_list_ad_rules_with_metadata`. + """ + return response, metadata + + def pre_update_ad_rule( + self, + request: ad_rule_service.UpdateAdRuleRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + ad_rule_service.UpdateAdRuleRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_ad_rule + + Override in a subclass to manipulate the request or metadata + before they are sent to the AdRuleService server. + """ + return request, metadata + + def post_update_ad_rule( + self, response: ad_rule_messages.AdRule + ) -> ad_rule_messages.AdRule: + """Post-rpc interceptor for update_ad_rule + + DEPRECATED. Please use the `post_update_ad_rule_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AdRuleService server but before + it is returned to user code. This `post_update_ad_rule` interceptor runs + before the `post_update_ad_rule_with_metadata` interceptor. + """ + return response + + def post_update_ad_rule_with_metadata( + self, + response: ad_rule_messages.AdRule, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ad_rule_messages.AdRule, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_ad_rule + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AdRuleService server but before it is returned to user code. + + We recommend only using this `post_update_ad_rule_with_metadata` + interceptor in new development instead of the `post_update_ad_rule` interceptor. + When both interceptors are used, this `post_update_ad_rule_with_metadata` interceptor runs after the + `post_update_ad_rule` interceptor. The (possibly modified) response returned by + `post_update_ad_rule` will be passed to + `post_update_ad_rule_with_metadata`. + """ + return response, metadata + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the AdRuleService server. + """ + return request, metadata + + def post_cancel_operation(self, response: None) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the AdRuleService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the AdRuleService server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the AdRuleService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class AdRuleServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AdRuleServiceRestInterceptor + + +class AdRuleServiceRestTransport(_BaseAdRuleServiceRestTransport): + """REST backend synchronous transport for AdRuleService. + + Provides methods for handling ``AdRule`` objects. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "admanager.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[AdRuleServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'admanager.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[AdRuleServiceRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or AdRuleServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _BatchActivateAdRules( + _BaseAdRuleServiceRestTransport._BaseBatchActivateAdRules, AdRuleServiceRestStub + ): + def __hash__(self): + return hash("AdRuleServiceRestTransport.BatchActivateAdRules") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: ad_rule_service.BatchActivateAdRulesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> ad_rule_service.BatchActivateAdRulesResponse: + r"""Call the batch activate ad rules method over HTTP. + + Args: + request (~.ad_rule_service.BatchActivateAdRulesRequest): + The request object. Request object for ``BatchActivateAdRules`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.ad_rule_service.BatchActivateAdRulesResponse: + Response object for ``BatchActivateAdRules`` method. + """ + + http_options = _BaseAdRuleServiceRestTransport._BaseBatchActivateAdRules._get_http_options() + + request, metadata = self._interceptor.pre_batch_activate_ad_rules( + request, metadata + ) + transcoded_request = _BaseAdRuleServiceRestTransport._BaseBatchActivateAdRules._get_transcoded_request( + http_options, request + ) + + body = _BaseAdRuleServiceRestTransport._BaseBatchActivateAdRules._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseAdRuleServiceRestTransport._BaseBatchActivateAdRules._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.AdRuleServiceClient.BatchActivateAdRules", + extra={ + "serviceName": "google.ads.admanager.v1.AdRuleService", + "rpcName": "BatchActivateAdRules", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdRuleServiceRestTransport._BatchActivateAdRules._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = ad_rule_service.BatchActivateAdRulesResponse() + pb_resp = ad_rule_service.BatchActivateAdRulesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_activate_ad_rules(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_batch_activate_ad_rules_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + ad_rule_service.BatchActivateAdRulesResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.AdRuleServiceClient.batch_activate_ad_rules", + extra={ + "serviceName": "google.ads.admanager.v1.AdRuleService", + "rpcName": "BatchActivateAdRules", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _BatchCreateAdRules( + _BaseAdRuleServiceRestTransport._BaseBatchCreateAdRules, AdRuleServiceRestStub + ): + def __hash__(self): + return hash("AdRuleServiceRestTransport.BatchCreateAdRules") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: ad_rule_service.BatchCreateAdRulesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> ad_rule_service.BatchCreateAdRulesResponse: + r"""Call the batch create ad rules method over HTTP. + + Args: + request (~.ad_rule_service.BatchCreateAdRulesRequest): + The request object. Request object for ``BatchCreateAdRules`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.ad_rule_service.BatchCreateAdRulesResponse: + Response object for ``BatchCreateAdRules`` method. + """ + + http_options = _BaseAdRuleServiceRestTransport._BaseBatchCreateAdRules._get_http_options() + + request, metadata = self._interceptor.pre_batch_create_ad_rules( + request, metadata + ) + transcoded_request = _BaseAdRuleServiceRestTransport._BaseBatchCreateAdRules._get_transcoded_request( + http_options, request + ) + + body = _BaseAdRuleServiceRestTransport._BaseBatchCreateAdRules._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseAdRuleServiceRestTransport._BaseBatchCreateAdRules._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.AdRuleServiceClient.BatchCreateAdRules", + extra={ + "serviceName": "google.ads.admanager.v1.AdRuleService", + "rpcName": "BatchCreateAdRules", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdRuleServiceRestTransport._BatchCreateAdRules._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = ad_rule_service.BatchCreateAdRulesResponse() + pb_resp = ad_rule_service.BatchCreateAdRulesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_create_ad_rules(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_batch_create_ad_rules_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + ad_rule_service.BatchCreateAdRulesResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.AdRuleServiceClient.batch_create_ad_rules", + extra={ + "serviceName": "google.ads.admanager.v1.AdRuleService", + "rpcName": "BatchCreateAdRules", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _BatchDeactivateAdRules( + _BaseAdRuleServiceRestTransport._BaseBatchDeactivateAdRules, + AdRuleServiceRestStub, + ): + def __hash__(self): + return hash("AdRuleServiceRestTransport.BatchDeactivateAdRules") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: ad_rule_service.BatchDeactivateAdRulesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> ad_rule_service.BatchDeactivateAdRulesResponse: + r"""Call the batch deactivate ad rules method over HTTP. + + Args: + request (~.ad_rule_service.BatchDeactivateAdRulesRequest): + The request object. Request object for ``BatchDeactivateAdRules`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.ad_rule_service.BatchDeactivateAdRulesResponse: + Response object for ``BatchDeactivateAdRules`` method. + """ + + http_options = _BaseAdRuleServiceRestTransport._BaseBatchDeactivateAdRules._get_http_options() + + request, metadata = self._interceptor.pre_batch_deactivate_ad_rules( + request, metadata + ) + transcoded_request = _BaseAdRuleServiceRestTransport._BaseBatchDeactivateAdRules._get_transcoded_request( + http_options, request + ) + + body = _BaseAdRuleServiceRestTransport._BaseBatchDeactivateAdRules._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseAdRuleServiceRestTransport._BaseBatchDeactivateAdRules._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.AdRuleServiceClient.BatchDeactivateAdRules", + extra={ + "serviceName": "google.ads.admanager.v1.AdRuleService", + "rpcName": "BatchDeactivateAdRules", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdRuleServiceRestTransport._BatchDeactivateAdRules._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = ad_rule_service.BatchDeactivateAdRulesResponse() + pb_resp = ad_rule_service.BatchDeactivateAdRulesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_deactivate_ad_rules(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_batch_deactivate_ad_rules_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + ad_rule_service.BatchDeactivateAdRulesResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.AdRuleServiceClient.batch_deactivate_ad_rules", + extra={ + "serviceName": "google.ads.admanager.v1.AdRuleService", + "rpcName": "BatchDeactivateAdRules", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _BatchDeleteAdRules( + _BaseAdRuleServiceRestTransport._BaseBatchDeleteAdRules, AdRuleServiceRestStub + ): + def __hash__(self): + return hash("AdRuleServiceRestTransport.BatchDeleteAdRules") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: ad_rule_service.BatchDeleteAdRulesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the batch delete ad rules method over HTTP. + + Args: + request (~.ad_rule_service.BatchDeleteAdRulesRequest): + The request object. Request object for ``BatchDeleteAdRules`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseAdRuleServiceRestTransport._BaseBatchDeleteAdRules._get_http_options() + + request, metadata = self._interceptor.pre_batch_delete_ad_rules( + request, metadata + ) + transcoded_request = _BaseAdRuleServiceRestTransport._BaseBatchDeleteAdRules._get_transcoded_request( + http_options, request + ) + + body = _BaseAdRuleServiceRestTransport._BaseBatchDeleteAdRules._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseAdRuleServiceRestTransport._BaseBatchDeleteAdRules._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.AdRuleServiceClient.BatchDeleteAdRules", + extra={ + "serviceName": "google.ads.admanager.v1.AdRuleService", + "rpcName": "BatchDeleteAdRules", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdRuleServiceRestTransport._BatchDeleteAdRules._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _BatchUpdateAdRules( + _BaseAdRuleServiceRestTransport._BaseBatchUpdateAdRules, AdRuleServiceRestStub + ): + def __hash__(self): + return hash("AdRuleServiceRestTransport.BatchUpdateAdRules") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: ad_rule_service.BatchUpdateAdRulesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> ad_rule_service.BatchUpdateAdRulesResponse: + r"""Call the batch update ad rules method over HTTP. + + Args: + request (~.ad_rule_service.BatchUpdateAdRulesRequest): + The request object. Request object for ``BatchUpdateAdRules`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.ad_rule_service.BatchUpdateAdRulesResponse: + Response object for ``BatchUpdateAdRules`` method. + """ + + http_options = _BaseAdRuleServiceRestTransport._BaseBatchUpdateAdRules._get_http_options() + + request, metadata = self._interceptor.pre_batch_update_ad_rules( + request, metadata + ) + transcoded_request = _BaseAdRuleServiceRestTransport._BaseBatchUpdateAdRules._get_transcoded_request( + http_options, request + ) + + body = _BaseAdRuleServiceRestTransport._BaseBatchUpdateAdRules._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseAdRuleServiceRestTransport._BaseBatchUpdateAdRules._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.AdRuleServiceClient.BatchUpdateAdRules", + extra={ + "serviceName": "google.ads.admanager.v1.AdRuleService", + "rpcName": "BatchUpdateAdRules", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdRuleServiceRestTransport._BatchUpdateAdRules._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = ad_rule_service.BatchUpdateAdRulesResponse() + pb_resp = ad_rule_service.BatchUpdateAdRulesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_update_ad_rules(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_batch_update_ad_rules_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + ad_rule_service.BatchUpdateAdRulesResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.AdRuleServiceClient.batch_update_ad_rules", + extra={ + "serviceName": "google.ads.admanager.v1.AdRuleService", + "rpcName": "BatchUpdateAdRules", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateAdRule( + _BaseAdRuleServiceRestTransport._BaseCreateAdRule, AdRuleServiceRestStub + ): + def __hash__(self): + return hash("AdRuleServiceRestTransport.CreateAdRule") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: ad_rule_service.CreateAdRuleRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> ad_rule_messages.AdRule: + r"""Call the create ad rule method over HTTP. + + Args: + request (~.ad_rule_service.CreateAdRuleRequest): + The request object. Request object for ``CreateAdRule`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.ad_rule_messages.AdRule: + An AdRule contains data that the ad + server will use to generate a playlist + of video ads. + + """ + + http_options = ( + _BaseAdRuleServiceRestTransport._BaseCreateAdRule._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_ad_rule(request, metadata) + transcoded_request = _BaseAdRuleServiceRestTransport._BaseCreateAdRule._get_transcoded_request( + http_options, request + ) + + body = _BaseAdRuleServiceRestTransport._BaseCreateAdRule._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseAdRuleServiceRestTransport._BaseCreateAdRule._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.AdRuleServiceClient.CreateAdRule", + extra={ + "serviceName": "google.ads.admanager.v1.AdRuleService", + "rpcName": "CreateAdRule", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdRuleServiceRestTransport._CreateAdRule._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = ad_rule_messages.AdRule() + pb_resp = ad_rule_messages.AdRule.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_ad_rule(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_ad_rule_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ad_rule_messages.AdRule.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.AdRuleServiceClient.create_ad_rule", + extra={ + "serviceName": "google.ads.admanager.v1.AdRuleService", + "rpcName": "CreateAdRule", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetAdRule( + _BaseAdRuleServiceRestTransport._BaseGetAdRule, AdRuleServiceRestStub + ): + def __hash__(self): + return hash("AdRuleServiceRestTransport.GetAdRule") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: ad_rule_service.GetAdRuleRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> ad_rule_messages.AdRule: + r"""Call the get ad rule method over HTTP. + + Args: + request (~.ad_rule_service.GetAdRuleRequest): + The request object. Request object for ``GetAdRule`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.ad_rule_messages.AdRule: + An AdRule contains data that the ad + server will use to generate a playlist + of video ads. + + """ + + http_options = ( + _BaseAdRuleServiceRestTransport._BaseGetAdRule._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_ad_rule(request, metadata) + transcoded_request = ( + _BaseAdRuleServiceRestTransport._BaseGetAdRule._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseAdRuleServiceRestTransport._BaseGetAdRule._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.AdRuleServiceClient.GetAdRule", + extra={ + "serviceName": "google.ads.admanager.v1.AdRuleService", + "rpcName": "GetAdRule", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdRuleServiceRestTransport._GetAdRule._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = ad_rule_messages.AdRule() + pb_resp = ad_rule_messages.AdRule.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_ad_rule(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_ad_rule_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ad_rule_messages.AdRule.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.AdRuleServiceClient.get_ad_rule", + extra={ + "serviceName": "google.ads.admanager.v1.AdRuleService", + "rpcName": "GetAdRule", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListAdRules( + _BaseAdRuleServiceRestTransport._BaseListAdRules, AdRuleServiceRestStub + ): + def __hash__(self): + return hash("AdRuleServiceRestTransport.ListAdRules") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: ad_rule_service.ListAdRulesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> ad_rule_service.ListAdRulesResponse: + r"""Call the list ad rules method over HTTP. + + Args: + request (~.ad_rule_service.ListAdRulesRequest): + The request object. Request object for ``ListAdRules`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.ad_rule_service.ListAdRulesResponse: + Response object for ``ListAdRulesRequest`` containing + matching ``AdRule`` objects. + + """ + + http_options = ( + _BaseAdRuleServiceRestTransport._BaseListAdRules._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_ad_rules(request, metadata) + transcoded_request = _BaseAdRuleServiceRestTransport._BaseListAdRules._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = ( + _BaseAdRuleServiceRestTransport._BaseListAdRules._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.AdRuleServiceClient.ListAdRules", + extra={ + "serviceName": "google.ads.admanager.v1.AdRuleService", + "rpcName": "ListAdRules", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdRuleServiceRestTransport._ListAdRules._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = ad_rule_service.ListAdRulesResponse() + pb_resp = ad_rule_service.ListAdRulesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_ad_rules(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_ad_rules_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ad_rule_service.ListAdRulesResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.AdRuleServiceClient.list_ad_rules", + extra={ + "serviceName": "google.ads.admanager.v1.AdRuleService", + "rpcName": "ListAdRules", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateAdRule( + _BaseAdRuleServiceRestTransport._BaseUpdateAdRule, AdRuleServiceRestStub + ): + def __hash__(self): + return hash("AdRuleServiceRestTransport.UpdateAdRule") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: ad_rule_service.UpdateAdRuleRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> ad_rule_messages.AdRule: + r"""Call the update ad rule method over HTTP. + + Args: + request (~.ad_rule_service.UpdateAdRuleRequest): + The request object. Request object for ``UpdateAdRule`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.ad_rule_messages.AdRule: + An AdRule contains data that the ad + server will use to generate a playlist + of video ads. + + """ + + http_options = ( + _BaseAdRuleServiceRestTransport._BaseUpdateAdRule._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_ad_rule(request, metadata) + transcoded_request = _BaseAdRuleServiceRestTransport._BaseUpdateAdRule._get_transcoded_request( + http_options, request + ) + + body = _BaseAdRuleServiceRestTransport._BaseUpdateAdRule._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseAdRuleServiceRestTransport._BaseUpdateAdRule._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.AdRuleServiceClient.UpdateAdRule", + extra={ + "serviceName": "google.ads.admanager.v1.AdRuleService", + "rpcName": "UpdateAdRule", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdRuleServiceRestTransport._UpdateAdRule._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = ad_rule_messages.AdRule() + pb_resp = ad_rule_messages.AdRule.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_ad_rule(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_ad_rule_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ad_rule_messages.AdRule.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.AdRuleServiceClient.update_ad_rule", + extra={ + "serviceName": "google.ads.admanager.v1.AdRuleService", + "rpcName": "UpdateAdRule", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def batch_activate_ad_rules( + self, + ) -> Callable[ + [ad_rule_service.BatchActivateAdRulesRequest], + ad_rule_service.BatchActivateAdRulesResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchActivateAdRules(self._session, self._host, self._interceptor) # type: ignore + + @property + def batch_create_ad_rules( + self, + ) -> Callable[ + [ad_rule_service.BatchCreateAdRulesRequest], + ad_rule_service.BatchCreateAdRulesResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchCreateAdRules(self._session, self._host, self._interceptor) # type: ignore + + @property + def batch_deactivate_ad_rules( + self, + ) -> Callable[ + [ad_rule_service.BatchDeactivateAdRulesRequest], + ad_rule_service.BatchDeactivateAdRulesResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchDeactivateAdRules( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def batch_delete_ad_rules( + self, + ) -> Callable[[ad_rule_service.BatchDeleteAdRulesRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchDeleteAdRules(self._session, self._host, self._interceptor) # type: ignore + + @property + def batch_update_ad_rules( + self, + ) -> Callable[ + [ad_rule_service.BatchUpdateAdRulesRequest], + ad_rule_service.BatchUpdateAdRulesResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchUpdateAdRules(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_ad_rule( + self, + ) -> Callable[[ad_rule_service.CreateAdRuleRequest], ad_rule_messages.AdRule]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateAdRule(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_ad_rule( + self, + ) -> Callable[[ad_rule_service.GetAdRuleRequest], ad_rule_messages.AdRule]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetAdRule(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_ad_rules( + self, + ) -> Callable[ + [ad_rule_service.ListAdRulesRequest], ad_rule_service.ListAdRulesResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListAdRules(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_ad_rule( + self, + ) -> Callable[[ad_rule_service.UpdateAdRuleRequest], ad_rule_messages.AdRule]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateAdRule(self._session, self._host, self._interceptor) # type: ignore + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation( + _BaseAdRuleServiceRestTransport._BaseCancelOperation, AdRuleServiceRestStub + ): + def __hash__(self): + return hash("AdRuleServiceRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseAdRuleServiceRestTransport._BaseCancelOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request = _BaseAdRuleServiceRestTransport._BaseCancelOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseAdRuleServiceRestTransport._BaseCancelOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.AdRuleServiceClient.CancelOperation", + extra={ + "serviceName": "google.ads.admanager.v1.AdRuleService", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdRuleServiceRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation( + _BaseAdRuleServiceRestTransport._BaseGetOperation, AdRuleServiceRestStub + ): + def __hash__(self): + return hash("AdRuleServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = ( + _BaseAdRuleServiceRestTransport._BaseGetOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseAdRuleServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseAdRuleServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.AdRuleServiceClient.GetOperation", + extra={ + "serviceName": "google.ads.admanager.v1.AdRuleService", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdRuleServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.AdRuleServiceAsyncClient.GetOperation", + extra={ + "serviceName": "google.ads.admanager.v1.AdRuleService", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("AdRuleServiceRestTransport",) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_rule_service/transports/rest_base.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_rule_service/transports/rest_base.py new file mode 100644 index 000000000000..1952e95fd990 --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_rule_service/transports/rest_base.py @@ -0,0 +1,636 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import gapic_v1, path_template +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.ads.admanager_v1.types import ad_rule_messages, ad_rule_service + +from .base import DEFAULT_CLIENT_INFO, AdRuleServiceTransport + + +class _BaseAdRuleServiceRestTransport(AdRuleServiceTransport): + """Base REST backend transport for AdRuleService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "admanager.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'admanager.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseBatchActivateAdRules: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=networks/*}/adRules:batchActivate", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ad_rule_service.BatchActivateAdRulesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAdRuleServiceRestTransport._BaseBatchActivateAdRules._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseBatchCreateAdRules: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=networks/*}/adRules:batchCreate", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ad_rule_service.BatchCreateAdRulesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAdRuleServiceRestTransport._BaseBatchCreateAdRules._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseBatchDeactivateAdRules: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=networks/*}/adRules:batchDeactivate", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ad_rule_service.BatchDeactivateAdRulesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAdRuleServiceRestTransport._BaseBatchDeactivateAdRules._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseBatchDeleteAdRules: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=networks/*}/adRules:batchDelete", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ad_rule_service.BatchDeleteAdRulesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAdRuleServiceRestTransport._BaseBatchDeleteAdRules._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseBatchUpdateAdRules: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=networks/*}/adRules:batchUpdate", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ad_rule_service.BatchUpdateAdRulesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAdRuleServiceRestTransport._BaseBatchUpdateAdRules._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateAdRule: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=networks/*}/adRules", + "body": "ad_rule", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ad_rule_service.CreateAdRuleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAdRuleServiceRestTransport._BaseCreateAdRule._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetAdRule: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=networks/*/adRules/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ad_rule_service.GetAdRuleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAdRuleServiceRestTransport._BaseGetAdRule._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListAdRules: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=networks/*}/adRules", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ad_rule_service.ListAdRulesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAdRuleServiceRestTransport._BaseListAdRules._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateAdRule: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{ad_rule.name=networks/*/adRules/*}", + "body": "ad_rule", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ad_rule_service.UpdateAdRuleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAdRuleServiceRestTransport._BaseUpdateAdRule._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=networks/*/operations/reports/runs/*}:cancel", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=networks/*/operations/reports/runs/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseAdRuleServiceRestTransport",) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_spot_service/__init__.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_spot_service/__init__.py new file mode 100644 index 000000000000..3efbf6788e6a --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_spot_service/__init__.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +from .client import AdSpotServiceClient + +__all__ = ("AdSpotServiceClient",) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_spot_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_spot_service/client.py new file mode 100644 index 000000000000..ae22bab4a208 --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_spot_service/client.py @@ -0,0 +1,1602 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +import json +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.ads.admanager_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.ads.admanager_v1.services.ad_spot_service import pagers +from google.ads.admanager_v1.types import ( + ad_spot_messages, + ad_spot_service, + ad_spot_targeting_type_enum, + line_item_enums, +) + +from .transports.base import DEFAULT_CLIENT_INFO, AdSpotServiceTransport +from .transports.rest import AdSpotServiceRestTransport + + +class AdSpotServiceClientMeta(type): + """Metaclass for the AdSpotService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[AdSpotServiceTransport]] + _transport_registry["rest"] = AdSpotServiceRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[AdSpotServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class AdSpotServiceClient(metaclass=AdSpotServiceClientMeta): + """Provides methods for handling ``AdSpot`` objects.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + Optional[str]: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # Could not parse api_endpoint; return as-is. + return api_endpoint + + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "admanager.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "admanager.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + AdSpotServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + AdSpotServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> AdSpotServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AdSpotServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def ad_spot_path( + network_code: str, + ad_spot: str, + ) -> str: + """Returns a fully-qualified ad_spot string.""" + return "networks/{network_code}/adSpots/{ad_spot}".format( + network_code=network_code, + ad_spot=ad_spot, + ) + + @staticmethod + def parse_ad_spot_path(path: str) -> Dict[str, str]: + """Parses a ad_spot path into its component segments.""" + m = re.match(r"^networks/(?P.+?)/adSpots/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def network_path( + network_code: str, + ) -> str: + """Returns a fully-qualified network string.""" + return "networks/{network_code}".format( + network_code=network_code, + ) + + @staticmethod + def parse_network_path(path: str) -> Dict[str, str]: + """Parses a network path into its component segments.""" + m = re.match(r"^networks/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = AdSpotServiceClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = AdSpotServiceClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = AdSpotServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = AdSpotServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = AdSpotServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = AdSpotServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, AdSpotServiceTransport, Callable[..., AdSpotServiceTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the ad spot service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,AdSpotServiceTransport,Callable[..., AdSpotServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the AdSpotServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + AdSpotServiceClient._read_environment_variables() + ) + self._client_cert_source = AdSpotServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = AdSpotServiceClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, AdSpotServiceTransport) + if transport_provided: + # transport is a AdSpotServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(AdSpotServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or AdSpotServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[AdSpotServiceTransport], Callable[..., AdSpotServiceTransport] + ] = ( + AdSpotServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., AdSpotServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.ads.admanager_v1.AdSpotServiceClient`.", + extra={ + "serviceName": "google.ads.admanager.v1.AdSpotService", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.ads.admanager.v1.AdSpotService", + "credentialsType": None, + }, + ) + + def get_ad_spot( + self, + request: Optional[Union[ad_spot_service.GetAdSpotRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> ad_spot_messages.AdSpot: + r"""Retrieves an ``AdSpot`` object. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_get_ad_spot(): + # Create a client + client = admanager_v1.AdSpotServiceClient() + + # Initialize request argument(s) + request = admanager_v1.GetAdSpotRequest( + name="name_value", + ) + + # Make the request + response = client.get_ad_spot(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.GetAdSpotRequest, dict]): + The request object. Request object for ``GetAdSpot`` method. + name (str): + Required. The resource name of the AdSpot. Format: + ``networks/{network_code}/adSpots/{ad_spot_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.admanager_v1.types.AdSpot: + An AdSpot is a targetable entity used + in the creation of AdRule objects. A ad + spot contains a variable number of ads + and has constraints (ad duration, + reservation type, etc) on the ads that + can appear in it. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, ad_spot_service.GetAdSpotRequest): + request = ad_spot_service.GetAdSpotRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_ad_spot] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_ad_spots( + self, + request: Optional[Union[ad_spot_service.ListAdSpotsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAdSpotsPager: + r"""Lists ``AdSpot`` objects. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_list_ad_spots(): + # Create a client + client = admanager_v1.AdSpotServiceClient() + + # Initialize request argument(s) + request = admanager_v1.ListAdSpotsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_ad_spots(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.ListAdSpotsRequest, dict]): + The request object. Request object for ``ListAdSpots`` method. + parent (str): + Required. The parent, which owns this collection of + AdSpots. Format: ``networks/{network_code}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.admanager_v1.services.ad_spot_service.pagers.ListAdSpotsPager: + Response object for ListAdSpotsRequest containing matching AdSpot + objects. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, ad_spot_service.ListAdSpotsRequest): + request = ad_spot_service.ListAdSpotsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_ad_spots] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListAdSpotsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_ad_spot( + self, + request: Optional[Union[ad_spot_service.CreateAdSpotRequest, dict]] = None, + *, + parent: Optional[str] = None, + ad_spot: Optional[ad_spot_messages.AdSpot] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> ad_spot_messages.AdSpot: + r"""Creates an ``AdSpot`` object. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_create_ad_spot(): + # Create a client + client = admanager_v1.AdSpotServiceClient() + + # Initialize request argument(s) + request = admanager_v1.CreateAdSpotRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_ad_spot(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.CreateAdSpotRequest, dict]): + The request object. Request object for ``CreateAdSpot`` method. + parent (str): + Required. The parent resource where this ``AdSpot`` will + be created. Format: ``networks/{network_code}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ad_spot (google.ads.admanager_v1.types.AdSpot): + Required. The ``AdSpot`` to create. + This corresponds to the ``ad_spot`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.admanager_v1.types.AdSpot: + An AdSpot is a targetable entity used + in the creation of AdRule objects. A ad + spot contains a variable number of ads + and has constraints (ad duration, + reservation type, etc) on the ads that + can appear in it. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, ad_spot] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, ad_spot_service.CreateAdSpotRequest): + request = ad_spot_service.CreateAdSpotRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if ad_spot is not None: + request.ad_spot = ad_spot + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_ad_spot] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_create_ad_spots( + self, + request: Optional[ + Union[ad_spot_service.BatchCreateAdSpotsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + requests: Optional[MutableSequence[ad_spot_service.CreateAdSpotRequest]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> ad_spot_service.BatchCreateAdSpotsResponse: + r"""Batch creates ``AdSpot`` objects. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_batch_create_ad_spots(): + # Create a client + client = admanager_v1.AdSpotServiceClient() + + # Initialize request argument(s) + requests = admanager_v1.CreateAdSpotRequest() + requests.parent = "parent_value" + + request = admanager_v1.BatchCreateAdSpotsRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = client.batch_create_ad_spots(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.BatchCreateAdSpotsRequest, dict]): + The request object. Request object for ``BatchCreateAdSpots`` method. + parent (str): + Required. The parent resource where ``AdSpots`` will be + created. Format: ``networks/{network_code}`` The parent + field in the CreateAdSpotRequest must match this field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + requests (MutableSequence[google.ads.admanager_v1.types.CreateAdSpotRequest]): + Required. The ``AdSpot`` objects to create. A maximum of + 100 objects can be created in a batch. + + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.admanager_v1.types.BatchCreateAdSpotsResponse: + Response object for BatchCreateAdSpots method. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, requests] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, ad_spot_service.BatchCreateAdSpotsRequest): + request = ad_spot_service.BatchCreateAdSpotsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_create_ad_spots] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_ad_spot( + self, + request: Optional[Union[ad_spot_service.UpdateAdSpotRequest, dict]] = None, + *, + ad_spot: Optional[ad_spot_messages.AdSpot] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> ad_spot_messages.AdSpot: + r"""Updates an ``AdSpot`` object. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_update_ad_spot(): + # Create a client + client = admanager_v1.AdSpotServiceClient() + + # Initialize request argument(s) + request = admanager_v1.UpdateAdSpotRequest( + ) + + # Make the request + response = client.update_ad_spot(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.UpdateAdSpotRequest, dict]): + The request object. Request object for ``UpdateAdSpot`` method. + ad_spot (google.ads.admanager_v1.types.AdSpot): + Required. The ``AdSpot`` to update. + + The ``AdSpot``'s ``name`` is used to identify the + ``AdSpot`` to update. + + This corresponds to the ``ad_spot`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to + update. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.admanager_v1.types.AdSpot: + An AdSpot is a targetable entity used + in the creation of AdRule objects. A ad + spot contains a variable number of ads + and has constraints (ad duration, + reservation type, etc) on the ads that + can appear in it. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [ad_spot, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, ad_spot_service.UpdateAdSpotRequest): + request = ad_spot_service.UpdateAdSpotRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if ad_spot is not None: + request.ad_spot = ad_spot + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_ad_spot] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("ad_spot.name", request.ad_spot.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_update_ad_spots( + self, + request: Optional[ + Union[ad_spot_service.BatchUpdateAdSpotsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + requests: Optional[MutableSequence[ad_spot_service.UpdateAdSpotRequest]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> ad_spot_service.BatchUpdateAdSpotsResponse: + r"""Batch updates ``AdSpot`` objects. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_batch_update_ad_spots(): + # Create a client + client = admanager_v1.AdSpotServiceClient() + + # Initialize request argument(s) + request = admanager_v1.BatchUpdateAdSpotsRequest( + parent="parent_value", + ) + + # Make the request + response = client.batch_update_ad_spots(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.BatchUpdateAdSpotsRequest, dict]): + The request object. Request object for ``BatchUpdateAdSpots`` method. + parent (str): + Required. The parent resource where ``AdSpots`` will be + updated. Format: ``networks/{network_code}`` The parent + field in the UpdateAdSpotRequest must match this field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + requests (MutableSequence[google.ads.admanager_v1.types.UpdateAdSpotRequest]): + Required. The ``AdSpot`` objects to update. A maximum of + 100 objects can be updated in a batch. + + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.admanager_v1.types.BatchUpdateAdSpotsResponse: + Response object for BatchUpdateAdSpots method. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, requests] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, ad_spot_service.BatchUpdateAdSpotsRequest): + request = ad_spot_service.BatchUpdateAdSpotsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_update_ad_spots] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "AdSpotServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("AdSpotServiceClient",) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_spot_service/pagers.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_spot_service/pagers.py new file mode 100644 index 000000000000..9b2b84565028 --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_spot_service/pagers.py @@ -0,0 +1,117 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.ads.admanager_v1.types import ad_spot_messages, ad_spot_service + + +class ListAdSpotsPager: + """A pager for iterating through ``list_ad_spots`` requests. + + This class thinly wraps an initial + :class:`google.ads.admanager_v1.types.ListAdSpotsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``ad_spots`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAdSpots`` requests and continue to iterate + through the ``ad_spots`` field on the + corresponding responses. + + All the usual :class:`google.ads.admanager_v1.types.ListAdSpotsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., ad_spot_service.ListAdSpotsResponse], + request: ad_spot_service.ListAdSpotsRequest, + response: ad_spot_service.ListAdSpotsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.ads.admanager_v1.types.ListAdSpotsRequest): + The initial request object. + response (google.ads.admanager_v1.types.ListAdSpotsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = ad_spot_service.ListAdSpotsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[ad_spot_service.ListAdSpotsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[ad_spot_messages.AdSpot]: + for page in self.pages: + yield from page.ad_spots + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_spot_service/transports/README.rst b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_spot_service/transports/README.rst new file mode 100644 index 000000000000..a7747e2bcac9 --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_spot_service/transports/README.rst @@ -0,0 +1,10 @@ + +transport inheritance structure +_______________________________ + +``AdSpotServiceTransport`` is the ABC for all transports. + +- public child ``AdSpotServiceGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``). +- public child ``AdSpotServiceGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``). +- private child ``_BaseAdSpotServiceRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``). +- public child ``AdSpotServiceRestTransport`` for sync REST transport with inner classes ``METHOD`` derived from the parent's corresponding ``_BaseMETHOD`` classes (defined in ``rest.py``). diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_spot_service/transports/__init__.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_spot_service/transports/__init__.py new file mode 100644 index 000000000000..d7748e0afdf4 --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_spot_service/transports/__init__.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import AdSpotServiceTransport +from .rest import AdSpotServiceRestInterceptor, AdSpotServiceRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AdSpotServiceTransport]] +_transport_registry["rest"] = AdSpotServiceRestTransport + +__all__ = ( + "AdSpotServiceTransport", + "AdSpotServiceRestTransport", + "AdSpotServiceRestInterceptor", +) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_spot_service/transports/base.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_spot_service/transports/base.py new file mode 100644 index 000000000000..3c35f570024c --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_spot_service/transports/base.py @@ -0,0 +1,284 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.ads.admanager_v1 import gapic_version as package_version +from google.ads.admanager_v1.types import ad_spot_messages, ad_spot_service + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class AdSpotServiceTransport(abc.ABC): + """Abstract transport class for AdSpotService.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/admanager", + "https://www.googleapis.com/auth/admanager.readonly", + ) + + DEFAULT_HOST: str = "admanager.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'admanager.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_ad_spot: gapic_v1.method.wrap_method( + self.get_ad_spot, + default_timeout=None, + client_info=client_info, + ), + self.list_ad_spots: gapic_v1.method.wrap_method( + self.list_ad_spots, + default_timeout=None, + client_info=client_info, + ), + self.create_ad_spot: gapic_v1.method.wrap_method( + self.create_ad_spot, + default_timeout=None, + client_info=client_info, + ), + self.batch_create_ad_spots: gapic_v1.method.wrap_method( + self.batch_create_ad_spots, + default_timeout=None, + client_info=client_info, + ), + self.update_ad_spot: gapic_v1.method.wrap_method( + self.update_ad_spot, + default_timeout=None, + client_info=client_info, + ), + self.batch_update_ad_spots: gapic_v1.method.wrap_method( + self.batch_update_ad_spots, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def get_ad_spot( + self, + ) -> Callable[ + [ad_spot_service.GetAdSpotRequest], + Union[ad_spot_messages.AdSpot, Awaitable[ad_spot_messages.AdSpot]], + ]: + raise NotImplementedError() + + @property + def list_ad_spots( + self, + ) -> Callable[ + [ad_spot_service.ListAdSpotsRequest], + Union[ + ad_spot_service.ListAdSpotsResponse, + Awaitable[ad_spot_service.ListAdSpotsResponse], + ], + ]: + raise NotImplementedError() + + @property + def create_ad_spot( + self, + ) -> Callable[ + [ad_spot_service.CreateAdSpotRequest], + Union[ad_spot_messages.AdSpot, Awaitable[ad_spot_messages.AdSpot]], + ]: + raise NotImplementedError() + + @property + def batch_create_ad_spots( + self, + ) -> Callable[ + [ad_spot_service.BatchCreateAdSpotsRequest], + Union[ + ad_spot_service.BatchCreateAdSpotsResponse, + Awaitable[ad_spot_service.BatchCreateAdSpotsResponse], + ], + ]: + raise NotImplementedError() + + @property + def update_ad_spot( + self, + ) -> Callable[ + [ad_spot_service.UpdateAdSpotRequest], + Union[ad_spot_messages.AdSpot, Awaitable[ad_spot_messages.AdSpot]], + ]: + raise NotImplementedError() + + @property + def batch_update_ad_spots( + self, + ) -> Callable[ + [ad_spot_service.BatchUpdateAdSpotsRequest], + Union[ + ad_spot_service.BatchUpdateAdSpotsResponse, + Awaitable[ad_spot_service.BatchUpdateAdSpotsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("AdSpotServiceTransport",) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_spot_service/transports/rest.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_spot_service/transports/rest.py new file mode 100644 index 000000000000..9d446e7cd893 --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_spot_service/transports/rest.py @@ -0,0 +1,1807 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +import dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.ads.admanager_v1.types import ad_spot_messages, ad_spot_service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseAdSpotServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class AdSpotServiceRestInterceptor: + """Interceptor for AdSpotService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the AdSpotServiceRestTransport. + + .. code-block:: python + class MyCustomAdSpotServiceInterceptor(AdSpotServiceRestInterceptor): + def pre_batch_create_ad_spots(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_create_ad_spots(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_batch_update_ad_spots(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_update_ad_spots(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_ad_spot(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_ad_spot(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_ad_spot(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_ad_spot(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_ad_spots(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_ad_spots(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_ad_spot(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_ad_spot(self, response): + logging.log(f"Received response: {response}") + return response + + transport = AdSpotServiceRestTransport(interceptor=MyCustomAdSpotServiceInterceptor()) + client = AdSpotServiceClient(transport=transport) + + + """ + + def pre_batch_create_ad_spots( + self, + request: ad_spot_service.BatchCreateAdSpotsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + ad_spot_service.BatchCreateAdSpotsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_create_ad_spots + + Override in a subclass to manipulate the request or metadata + before they are sent to the AdSpotService server. + """ + return request, metadata + + def post_batch_create_ad_spots( + self, response: ad_spot_service.BatchCreateAdSpotsResponse + ) -> ad_spot_service.BatchCreateAdSpotsResponse: + """Post-rpc interceptor for batch_create_ad_spots + + DEPRECATED. Please use the `post_batch_create_ad_spots_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AdSpotService server but before + it is returned to user code. This `post_batch_create_ad_spots` interceptor runs + before the `post_batch_create_ad_spots_with_metadata` interceptor. + """ + return response + + def post_batch_create_ad_spots_with_metadata( + self, + response: ad_spot_service.BatchCreateAdSpotsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + ad_spot_service.BatchCreateAdSpotsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for batch_create_ad_spots + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AdSpotService server but before it is returned to user code. + + We recommend only using this `post_batch_create_ad_spots_with_metadata` + interceptor in new development instead of the `post_batch_create_ad_spots` interceptor. + When both interceptors are used, this `post_batch_create_ad_spots_with_metadata` interceptor runs after the + `post_batch_create_ad_spots` interceptor. The (possibly modified) response returned by + `post_batch_create_ad_spots` will be passed to + `post_batch_create_ad_spots_with_metadata`. + """ + return response, metadata + + def pre_batch_update_ad_spots( + self, + request: ad_spot_service.BatchUpdateAdSpotsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + ad_spot_service.BatchUpdateAdSpotsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_update_ad_spots + + Override in a subclass to manipulate the request or metadata + before they are sent to the AdSpotService server. + """ + return request, metadata + + def post_batch_update_ad_spots( + self, response: ad_spot_service.BatchUpdateAdSpotsResponse + ) -> ad_spot_service.BatchUpdateAdSpotsResponse: + """Post-rpc interceptor for batch_update_ad_spots + + DEPRECATED. Please use the `post_batch_update_ad_spots_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AdSpotService server but before + it is returned to user code. This `post_batch_update_ad_spots` interceptor runs + before the `post_batch_update_ad_spots_with_metadata` interceptor. + """ + return response + + def post_batch_update_ad_spots_with_metadata( + self, + response: ad_spot_service.BatchUpdateAdSpotsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + ad_spot_service.BatchUpdateAdSpotsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for batch_update_ad_spots + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AdSpotService server but before it is returned to user code. + + We recommend only using this `post_batch_update_ad_spots_with_metadata` + interceptor in new development instead of the `post_batch_update_ad_spots` interceptor. + When both interceptors are used, this `post_batch_update_ad_spots_with_metadata` interceptor runs after the + `post_batch_update_ad_spots` interceptor. The (possibly modified) response returned by + `post_batch_update_ad_spots` will be passed to + `post_batch_update_ad_spots_with_metadata`. + """ + return response, metadata + + def pre_create_ad_spot( + self, + request: ad_spot_service.CreateAdSpotRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + ad_spot_service.CreateAdSpotRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_ad_spot + + Override in a subclass to manipulate the request or metadata + before they are sent to the AdSpotService server. + """ + return request, metadata + + def post_create_ad_spot( + self, response: ad_spot_messages.AdSpot + ) -> ad_spot_messages.AdSpot: + """Post-rpc interceptor for create_ad_spot + + DEPRECATED. Please use the `post_create_ad_spot_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AdSpotService server but before + it is returned to user code. This `post_create_ad_spot` interceptor runs + before the `post_create_ad_spot_with_metadata` interceptor. + """ + return response + + def post_create_ad_spot_with_metadata( + self, + response: ad_spot_messages.AdSpot, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ad_spot_messages.AdSpot, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_ad_spot + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AdSpotService server but before it is returned to user code. + + We recommend only using this `post_create_ad_spot_with_metadata` + interceptor in new development instead of the `post_create_ad_spot` interceptor. + When both interceptors are used, this `post_create_ad_spot_with_metadata` interceptor runs after the + `post_create_ad_spot` interceptor. The (possibly modified) response returned by + `post_create_ad_spot` will be passed to + `post_create_ad_spot_with_metadata`. + """ + return response, metadata + + def pre_get_ad_spot( + self, + request: ad_spot_service.GetAdSpotRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + ad_spot_service.GetAdSpotRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_ad_spot + + Override in a subclass to manipulate the request or metadata + before they are sent to the AdSpotService server. + """ + return request, metadata + + def post_get_ad_spot( + self, response: ad_spot_messages.AdSpot + ) -> ad_spot_messages.AdSpot: + """Post-rpc interceptor for get_ad_spot + + DEPRECATED. Please use the `post_get_ad_spot_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AdSpotService server but before + it is returned to user code. This `post_get_ad_spot` interceptor runs + before the `post_get_ad_spot_with_metadata` interceptor. + """ + return response + + def post_get_ad_spot_with_metadata( + self, + response: ad_spot_messages.AdSpot, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ad_spot_messages.AdSpot, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_ad_spot + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AdSpotService server but before it is returned to user code. + + We recommend only using this `post_get_ad_spot_with_metadata` + interceptor in new development instead of the `post_get_ad_spot` interceptor. + When both interceptors are used, this `post_get_ad_spot_with_metadata` interceptor runs after the + `post_get_ad_spot` interceptor. The (possibly modified) response returned by + `post_get_ad_spot` will be passed to + `post_get_ad_spot_with_metadata`. + """ + return response, metadata + + def pre_list_ad_spots( + self, + request: ad_spot_service.ListAdSpotsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + ad_spot_service.ListAdSpotsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_ad_spots + + Override in a subclass to manipulate the request or metadata + before they are sent to the AdSpotService server. + """ + return request, metadata + + def post_list_ad_spots( + self, response: ad_spot_service.ListAdSpotsResponse + ) -> ad_spot_service.ListAdSpotsResponse: + """Post-rpc interceptor for list_ad_spots + + DEPRECATED. Please use the `post_list_ad_spots_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AdSpotService server but before + it is returned to user code. This `post_list_ad_spots` interceptor runs + before the `post_list_ad_spots_with_metadata` interceptor. + """ + return response + + def post_list_ad_spots_with_metadata( + self, + response: ad_spot_service.ListAdSpotsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + ad_spot_service.ListAdSpotsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_ad_spots + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AdSpotService server but before it is returned to user code. + + We recommend only using this `post_list_ad_spots_with_metadata` + interceptor in new development instead of the `post_list_ad_spots` interceptor. + When both interceptors are used, this `post_list_ad_spots_with_metadata` interceptor runs after the + `post_list_ad_spots` interceptor. The (possibly modified) response returned by + `post_list_ad_spots` will be passed to + `post_list_ad_spots_with_metadata`. + """ + return response, metadata + + def pre_update_ad_spot( + self, + request: ad_spot_service.UpdateAdSpotRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + ad_spot_service.UpdateAdSpotRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_ad_spot + + Override in a subclass to manipulate the request or metadata + before they are sent to the AdSpotService server. + """ + return request, metadata + + def post_update_ad_spot( + self, response: ad_spot_messages.AdSpot + ) -> ad_spot_messages.AdSpot: + """Post-rpc interceptor for update_ad_spot + + DEPRECATED. Please use the `post_update_ad_spot_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AdSpotService server but before + it is returned to user code. This `post_update_ad_spot` interceptor runs + before the `post_update_ad_spot_with_metadata` interceptor. + """ + return response + + def post_update_ad_spot_with_metadata( + self, + response: ad_spot_messages.AdSpot, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ad_spot_messages.AdSpot, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_ad_spot + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AdSpotService server but before it is returned to user code. + + We recommend only using this `post_update_ad_spot_with_metadata` + interceptor in new development instead of the `post_update_ad_spot` interceptor. + When both interceptors are used, this `post_update_ad_spot_with_metadata` interceptor runs after the + `post_update_ad_spot` interceptor. The (possibly modified) response returned by + `post_update_ad_spot` will be passed to + `post_update_ad_spot_with_metadata`. + """ + return response, metadata + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the AdSpotService server. + """ + return request, metadata + + def post_cancel_operation(self, response: None) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the AdSpotService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the AdSpotService server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the AdSpotService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class AdSpotServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AdSpotServiceRestInterceptor + + +class AdSpotServiceRestTransport(_BaseAdSpotServiceRestTransport): + """REST backend synchronous transport for AdSpotService. + + Provides methods for handling ``AdSpot`` objects. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "admanager.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[AdSpotServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'admanager.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[AdSpotServiceRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or AdSpotServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _BatchCreateAdSpots( + _BaseAdSpotServiceRestTransport._BaseBatchCreateAdSpots, AdSpotServiceRestStub + ): + def __hash__(self): + return hash("AdSpotServiceRestTransport.BatchCreateAdSpots") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: ad_spot_service.BatchCreateAdSpotsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> ad_spot_service.BatchCreateAdSpotsResponse: + r"""Call the batch create ad spots method over HTTP. + + Args: + request (~.ad_spot_service.BatchCreateAdSpotsRequest): + The request object. Request object for ``BatchCreateAdSpots`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.ad_spot_service.BatchCreateAdSpotsResponse: + Response object for ``BatchCreateAdSpots`` method. + """ + + http_options = _BaseAdSpotServiceRestTransport._BaseBatchCreateAdSpots._get_http_options() + + request, metadata = self._interceptor.pre_batch_create_ad_spots( + request, metadata + ) + transcoded_request = _BaseAdSpotServiceRestTransport._BaseBatchCreateAdSpots._get_transcoded_request( + http_options, request + ) + + body = _BaseAdSpotServiceRestTransport._BaseBatchCreateAdSpots._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseAdSpotServiceRestTransport._BaseBatchCreateAdSpots._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.AdSpotServiceClient.BatchCreateAdSpots", + extra={ + "serviceName": "google.ads.admanager.v1.AdSpotService", + "rpcName": "BatchCreateAdSpots", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdSpotServiceRestTransport._BatchCreateAdSpots._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = ad_spot_service.BatchCreateAdSpotsResponse() + pb_resp = ad_spot_service.BatchCreateAdSpotsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_create_ad_spots(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_batch_create_ad_spots_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + ad_spot_service.BatchCreateAdSpotsResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.AdSpotServiceClient.batch_create_ad_spots", + extra={ + "serviceName": "google.ads.admanager.v1.AdSpotService", + "rpcName": "BatchCreateAdSpots", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _BatchUpdateAdSpots( + _BaseAdSpotServiceRestTransport._BaseBatchUpdateAdSpots, AdSpotServiceRestStub + ): + def __hash__(self): + return hash("AdSpotServiceRestTransport.BatchUpdateAdSpots") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: ad_spot_service.BatchUpdateAdSpotsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> ad_spot_service.BatchUpdateAdSpotsResponse: + r"""Call the batch update ad spots method over HTTP. + + Args: + request (~.ad_spot_service.BatchUpdateAdSpotsRequest): + The request object. Request object for ``BatchUpdateAdSpots`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.ad_spot_service.BatchUpdateAdSpotsResponse: + Response object for ``BatchUpdateAdSpots`` method. + """ + + http_options = _BaseAdSpotServiceRestTransport._BaseBatchUpdateAdSpots._get_http_options() + + request, metadata = self._interceptor.pre_batch_update_ad_spots( + request, metadata + ) + transcoded_request = _BaseAdSpotServiceRestTransport._BaseBatchUpdateAdSpots._get_transcoded_request( + http_options, request + ) + + body = _BaseAdSpotServiceRestTransport._BaseBatchUpdateAdSpots._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseAdSpotServiceRestTransport._BaseBatchUpdateAdSpots._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.AdSpotServiceClient.BatchUpdateAdSpots", + extra={ + "serviceName": "google.ads.admanager.v1.AdSpotService", + "rpcName": "BatchUpdateAdSpots", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdSpotServiceRestTransport._BatchUpdateAdSpots._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = ad_spot_service.BatchUpdateAdSpotsResponse() + pb_resp = ad_spot_service.BatchUpdateAdSpotsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_update_ad_spots(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_batch_update_ad_spots_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + ad_spot_service.BatchUpdateAdSpotsResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.AdSpotServiceClient.batch_update_ad_spots", + extra={ + "serviceName": "google.ads.admanager.v1.AdSpotService", + "rpcName": "BatchUpdateAdSpots", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateAdSpot( + _BaseAdSpotServiceRestTransport._BaseCreateAdSpot, AdSpotServiceRestStub + ): + def __hash__(self): + return hash("AdSpotServiceRestTransport.CreateAdSpot") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: ad_spot_service.CreateAdSpotRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> ad_spot_messages.AdSpot: + r"""Call the create ad spot method over HTTP. + + Args: + request (~.ad_spot_service.CreateAdSpotRequest): + The request object. Request object for ``CreateAdSpot`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.ad_spot_messages.AdSpot: + An AdSpot is a targetable entity used + in the creation of AdRule objects. A ad + spot contains a variable number of ads + and has constraints (ad duration, + reservation type, etc) on the ads that + can appear in it. + + """ + + http_options = ( + _BaseAdSpotServiceRestTransport._BaseCreateAdSpot._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_ad_spot(request, metadata) + transcoded_request = _BaseAdSpotServiceRestTransport._BaseCreateAdSpot._get_transcoded_request( + http_options, request + ) + + body = _BaseAdSpotServiceRestTransport._BaseCreateAdSpot._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseAdSpotServiceRestTransport._BaseCreateAdSpot._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.AdSpotServiceClient.CreateAdSpot", + extra={ + "serviceName": "google.ads.admanager.v1.AdSpotService", + "rpcName": "CreateAdSpot", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdSpotServiceRestTransport._CreateAdSpot._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = ad_spot_messages.AdSpot() + pb_resp = ad_spot_messages.AdSpot.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_ad_spot(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_ad_spot_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ad_spot_messages.AdSpot.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.AdSpotServiceClient.create_ad_spot", + extra={ + "serviceName": "google.ads.admanager.v1.AdSpotService", + "rpcName": "CreateAdSpot", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetAdSpot( + _BaseAdSpotServiceRestTransport._BaseGetAdSpot, AdSpotServiceRestStub + ): + def __hash__(self): + return hash("AdSpotServiceRestTransport.GetAdSpot") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: ad_spot_service.GetAdSpotRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> ad_spot_messages.AdSpot: + r"""Call the get ad spot method over HTTP. + + Args: + request (~.ad_spot_service.GetAdSpotRequest): + The request object. Request object for ``GetAdSpot`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.ad_spot_messages.AdSpot: + An AdSpot is a targetable entity used + in the creation of AdRule objects. A ad + spot contains a variable number of ads + and has constraints (ad duration, + reservation type, etc) on the ads that + can appear in it. + + """ + + http_options = ( + _BaseAdSpotServiceRestTransport._BaseGetAdSpot._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_ad_spot(request, metadata) + transcoded_request = ( + _BaseAdSpotServiceRestTransport._BaseGetAdSpot._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseAdSpotServiceRestTransport._BaseGetAdSpot._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.AdSpotServiceClient.GetAdSpot", + extra={ + "serviceName": "google.ads.admanager.v1.AdSpotService", + "rpcName": "GetAdSpot", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdSpotServiceRestTransport._GetAdSpot._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = ad_spot_messages.AdSpot() + pb_resp = ad_spot_messages.AdSpot.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_ad_spot(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_ad_spot_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ad_spot_messages.AdSpot.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.AdSpotServiceClient.get_ad_spot", + extra={ + "serviceName": "google.ads.admanager.v1.AdSpotService", + "rpcName": "GetAdSpot", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListAdSpots( + _BaseAdSpotServiceRestTransport._BaseListAdSpots, AdSpotServiceRestStub + ): + def __hash__(self): + return hash("AdSpotServiceRestTransport.ListAdSpots") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: ad_spot_service.ListAdSpotsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> ad_spot_service.ListAdSpotsResponse: + r"""Call the list ad spots method over HTTP. + + Args: + request (~.ad_spot_service.ListAdSpotsRequest): + The request object. Request object for ``ListAdSpots`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.ad_spot_service.ListAdSpotsResponse: + Response object for ``ListAdSpotsRequest`` containing + matching ``AdSpot`` objects. + + """ + + http_options = ( + _BaseAdSpotServiceRestTransport._BaseListAdSpots._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_ad_spots(request, metadata) + transcoded_request = _BaseAdSpotServiceRestTransport._BaseListAdSpots._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = ( + _BaseAdSpotServiceRestTransport._BaseListAdSpots._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.AdSpotServiceClient.ListAdSpots", + extra={ + "serviceName": "google.ads.admanager.v1.AdSpotService", + "rpcName": "ListAdSpots", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdSpotServiceRestTransport._ListAdSpots._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = ad_spot_service.ListAdSpotsResponse() + pb_resp = ad_spot_service.ListAdSpotsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_ad_spots(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_ad_spots_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ad_spot_service.ListAdSpotsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.AdSpotServiceClient.list_ad_spots", + extra={ + "serviceName": "google.ads.admanager.v1.AdSpotService", + "rpcName": "ListAdSpots", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateAdSpot( + _BaseAdSpotServiceRestTransport._BaseUpdateAdSpot, AdSpotServiceRestStub + ): + def __hash__(self): + return hash("AdSpotServiceRestTransport.UpdateAdSpot") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: ad_spot_service.UpdateAdSpotRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> ad_spot_messages.AdSpot: + r"""Call the update ad spot method over HTTP. + + Args: + request (~.ad_spot_service.UpdateAdSpotRequest): + The request object. Request object for ``UpdateAdSpot`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.ad_spot_messages.AdSpot: + An AdSpot is a targetable entity used + in the creation of AdRule objects. A ad + spot contains a variable number of ads + and has constraints (ad duration, + reservation type, etc) on the ads that + can appear in it. + + """ + + http_options = ( + _BaseAdSpotServiceRestTransport._BaseUpdateAdSpot._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_ad_spot(request, metadata) + transcoded_request = _BaseAdSpotServiceRestTransport._BaseUpdateAdSpot._get_transcoded_request( + http_options, request + ) + + body = _BaseAdSpotServiceRestTransport._BaseUpdateAdSpot._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseAdSpotServiceRestTransport._BaseUpdateAdSpot._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.AdSpotServiceClient.UpdateAdSpot", + extra={ + "serviceName": "google.ads.admanager.v1.AdSpotService", + "rpcName": "UpdateAdSpot", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdSpotServiceRestTransport._UpdateAdSpot._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = ad_spot_messages.AdSpot() + pb_resp = ad_spot_messages.AdSpot.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_ad_spot(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_ad_spot_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ad_spot_messages.AdSpot.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.AdSpotServiceClient.update_ad_spot", + extra={ + "serviceName": "google.ads.admanager.v1.AdSpotService", + "rpcName": "UpdateAdSpot", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def batch_create_ad_spots( + self, + ) -> Callable[ + [ad_spot_service.BatchCreateAdSpotsRequest], + ad_spot_service.BatchCreateAdSpotsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchCreateAdSpots(self._session, self._host, self._interceptor) # type: ignore + + @property + def batch_update_ad_spots( + self, + ) -> Callable[ + [ad_spot_service.BatchUpdateAdSpotsRequest], + ad_spot_service.BatchUpdateAdSpotsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchUpdateAdSpots(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_ad_spot( + self, + ) -> Callable[[ad_spot_service.CreateAdSpotRequest], ad_spot_messages.AdSpot]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateAdSpot(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_ad_spot( + self, + ) -> Callable[[ad_spot_service.GetAdSpotRequest], ad_spot_messages.AdSpot]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetAdSpot(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_ad_spots( + self, + ) -> Callable[ + [ad_spot_service.ListAdSpotsRequest], ad_spot_service.ListAdSpotsResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListAdSpots(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_ad_spot( + self, + ) -> Callable[[ad_spot_service.UpdateAdSpotRequest], ad_spot_messages.AdSpot]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateAdSpot(self._session, self._host, self._interceptor) # type: ignore + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation( + _BaseAdSpotServiceRestTransport._BaseCancelOperation, AdSpotServiceRestStub + ): + def __hash__(self): + return hash("AdSpotServiceRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseAdSpotServiceRestTransport._BaseCancelOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request = _BaseAdSpotServiceRestTransport._BaseCancelOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseAdSpotServiceRestTransport._BaseCancelOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.AdSpotServiceClient.CancelOperation", + extra={ + "serviceName": "google.ads.admanager.v1.AdSpotService", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdSpotServiceRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation( + _BaseAdSpotServiceRestTransport._BaseGetOperation, AdSpotServiceRestStub + ): + def __hash__(self): + return hash("AdSpotServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = ( + _BaseAdSpotServiceRestTransport._BaseGetOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseAdSpotServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseAdSpotServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.AdSpotServiceClient.GetOperation", + extra={ + "serviceName": "google.ads.admanager.v1.AdSpotService", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AdSpotServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.AdSpotServiceAsyncClient.GetOperation", + extra={ + "serviceName": "google.ads.admanager.v1.AdSpotService", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("AdSpotServiceRestTransport",) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_spot_service/transports/rest_base.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_spot_service/transports/rest_base.py new file mode 100644 index 000000000000..4e5de1f40c6b --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_spot_service/transports/rest_base.py @@ -0,0 +1,464 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.ads.admanager_v1.types import ad_spot_messages, ad_spot_service + +from .base import DEFAULT_CLIENT_INFO, AdSpotServiceTransport + + +class _BaseAdSpotServiceRestTransport(AdSpotServiceTransport): + """Base REST backend transport for AdSpotService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "admanager.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'admanager.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseBatchCreateAdSpots: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=networks/*}/adSpots:batchCreate", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ad_spot_service.BatchCreateAdSpotsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAdSpotServiceRestTransport._BaseBatchCreateAdSpots._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseBatchUpdateAdSpots: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=networks/*}/adSpots:batchUpdate", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ad_spot_service.BatchUpdateAdSpotsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAdSpotServiceRestTransport._BaseBatchUpdateAdSpots._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateAdSpot: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=networks/*}/adSpots", + "body": "ad_spot", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ad_spot_service.CreateAdSpotRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAdSpotServiceRestTransport._BaseCreateAdSpot._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetAdSpot: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=networks/*/adSpots/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ad_spot_service.GetAdSpotRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAdSpotServiceRestTransport._BaseGetAdSpot._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListAdSpots: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=networks/*}/adSpots", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ad_spot_service.ListAdSpotsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAdSpotServiceRestTransport._BaseListAdSpots._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateAdSpot: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{ad_spot.name=networks/*/adSpots/*}", + "body": "ad_spot", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ad_spot_service.UpdateAdSpotRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAdSpotServiceRestTransport._BaseUpdateAdSpot._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=networks/*/operations/reports/runs/*}:cancel", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=networks/*/operations/reports/runs/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseAdSpotServiceRestTransport",) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_unit_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_unit_service/client.py index 8e39878d933b..1c43205aad05 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_unit_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_unit_service/client.py @@ -786,7 +786,7 @@ def get_ad_unit( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> ad_unit_messages.AdUnit: - r"""API to retrieve an AdUnit object. + r"""Retrieves an ``AdUnit`` object. .. code-block:: python @@ -891,7 +891,7 @@ def list_ad_units( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListAdUnitsPager: - r"""API to retrieve a list of AdUnit objects. + r"""Lists ``AdUnit`` objects. .. code-block:: python @@ -1014,7 +1014,7 @@ def list_ad_unit_sizes( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListAdUnitSizesPager: - r"""API to retrieve a list of AdUnitSize objects. + r"""Lists ``AdUnitSize`` objects. .. code-block:: python @@ -1138,7 +1138,7 @@ def create_ad_unit( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> ad_unit_messages.AdUnit: - r"""API to create an ``AdUnit`` object. + r"""Creates an ``AdUnit`` object. .. code-block:: python @@ -1251,7 +1251,7 @@ def update_ad_unit( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> ad_unit_messages.AdUnit: - r"""API to update an ``AdUnit`` object. + r"""Updates an ``AdUnit`` object. .. code-block:: python @@ -1372,7 +1372,7 @@ def batch_create_ad_units( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> ad_unit_service.BatchCreateAdUnitsResponse: - r"""API to batch create ``AdUnit`` objects. + r"""Creates ``AdUnit`` objects. .. code-block:: python @@ -1494,7 +1494,7 @@ def batch_update_ad_units( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> ad_unit_service.BatchUpdateAdUnitsResponse: - r"""API to batch update ``AdUnit`` objects. + r"""Batch updates ``AdUnit`` objects. .. code-block:: python @@ -1612,7 +1612,7 @@ def batch_activate_ad_units( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> ad_unit_service.BatchActivateAdUnitsResponse: - r"""API to batch activate ``AdUnit`` objects. + r"""Batch activates ``AdUnit`` objects. .. code-block:: python diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/application_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/application_service/client.py index 81e2b0e44efa..aef00f1b74a6 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/application_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/application_service/client.py @@ -758,7 +758,7 @@ def get_application( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> application_messages.Application: - r"""API to retrieve a ``Application`` object. + r"""Retrieves a ``Application`` object. .. code-block:: python @@ -869,7 +869,7 @@ def list_applications( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListApplicationsPager: - r"""API to retrieve a list of ``Application`` objects. + r"""Lists ``Application`` objects. .. code-block:: python @@ -994,7 +994,7 @@ def create_application( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> application_messages.Application: - r"""API to create a ``Application`` object. + r"""Creates a ``Application`` object. .. code-block:: python @@ -1115,7 +1115,7 @@ def batch_create_applications( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> application_service.BatchCreateApplicationsResponse: - r"""API to batch create ``Application`` objects. + r"""Creates ``Application`` objects. .. code-block:: python @@ -1238,7 +1238,7 @@ def update_application( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> application_messages.Application: - r"""API to update a ``Application`` object. + r"""Updates a ``Application`` object. .. code-block:: python @@ -1364,7 +1364,7 @@ def batch_update_applications( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> application_service.BatchUpdateApplicationsResponse: - r"""API to batch update ``Application`` objects. + r"""Batch updates ``Application`` objects. .. code-block:: python @@ -1483,7 +1483,7 @@ def batch_archive_applications( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> application_service.BatchArchiveApplicationsResponse: - r"""/ API to batch archive ``Application`` objects. + r"""Batch archives ``Application`` objects. .. code-block:: python @@ -1602,7 +1602,7 @@ def batch_unarchive_applications( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> application_service.BatchUnarchiveApplicationsResponse: - r"""/ API to batch unarchive ``Application`` objects. + r"""Batch unarchives ``Application`` objects. .. code-block:: python diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/bandwidth_group_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/bandwidth_group_service/client.py index a51e0297b378..21603d270c0f 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/bandwidth_group_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/bandwidth_group_service/client.py @@ -759,7 +759,7 @@ def get_bandwidth_group( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> bandwidth_group_messages.BandwidthGroup: - r"""API to retrieve a ``BandwidthGroup`` object. + r"""Retrieves a ``BandwidthGroup`` object. .. code-block:: python @@ -871,7 +871,7 @@ def list_bandwidth_groups( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListBandwidthGroupsPager: - r"""API to retrieve a list of ``BandwidthGroup`` objects. + r"""Lists ``BandwidthGroup`` objects. .. code-block:: python diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/browser_language_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/browser_language_service/client.py index d82b5cb64b9b..a9d13884e901 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/browser_language_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/browser_language_service/client.py @@ -759,7 +759,7 @@ def get_browser_language( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> browser_language_messages.BrowserLanguage: - r"""API to retrieve a ``BrowserLanguage`` object. + r"""Retrieves a ``BrowserLanguage`` object. .. code-block:: python @@ -867,7 +867,7 @@ def list_browser_languages( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListBrowserLanguagesPager: - r"""API to retrieve a list of ``BrowserLanguage`` objects. + r"""Lists ``BrowserLanguage`` objects. .. code-block:: python diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/browser_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/browser_service/client.py index 7a2eff04bec9..094a0657d5fb 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/browser_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/browser_service/client.py @@ -746,7 +746,7 @@ def get_browser( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> browser_messages.Browser: - r"""API to retrieve a ``Browser`` object. + r"""Retrieves a ``Browser`` object. .. code-block:: python @@ -853,7 +853,7 @@ def list_browsers( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListBrowsersPager: - r"""API to retrieve a list of ``Browser`` objects. + r"""Lists ``Browser`` objects. .. code-block:: python diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/cdn_config_service/__init__.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/cdn_config_service/__init__.py new file mode 100644 index 000000000000..5181074e22e2 --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/cdn_config_service/__init__.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +from .client import CdnConfigServiceClient + +__all__ = ("CdnConfigServiceClient",) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/cdn_config_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/cdn_config_service/client.py new file mode 100644 index 000000000000..e44dec0d2078 --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/cdn_config_service/client.py @@ -0,0 +1,1848 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +import json +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.ads.admanager_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.ads.admanager_v1.services.cdn_config_service import pagers +from google.ads.admanager_v1.types import ( + cdn_config_messages, + cdn_config_service, + cdn_config_status_enum, + cdn_config_type_enum, +) + +from .transports.base import DEFAULT_CLIENT_INFO, CdnConfigServiceTransport +from .transports.rest import CdnConfigServiceRestTransport + + +class CdnConfigServiceClientMeta(type): + """Metaclass for the CdnConfigService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[CdnConfigServiceTransport]] + _transport_registry["rest"] = CdnConfigServiceRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[CdnConfigServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class CdnConfigServiceClient(metaclass=CdnConfigServiceClientMeta): + """Provides methods for handling ``CdnConfig`` objects.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + Optional[str]: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # Could not parse api_endpoint; return as-is. + return api_endpoint + + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "admanager.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "admanager.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CdnConfigServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CdnConfigServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> CdnConfigServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CdnConfigServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def cdn_config_path( + network_code: str, + cdn_config: str, + ) -> str: + """Returns a fully-qualified cdn_config string.""" + return "networks/{network_code}/cdnConfigs/{cdn_config}".format( + network_code=network_code, + cdn_config=cdn_config, + ) + + @staticmethod + def parse_cdn_config_path(path: str) -> Dict[str, str]: + """Parses a cdn_config path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/cdnConfigs/(?P.+?)$", path + ) + return m.groupdict() if m else {} + + @staticmethod + def network_path( + network_code: str, + ) -> str: + """Returns a fully-qualified network string.""" + return "networks/{network_code}".format( + network_code=network_code, + ) + + @staticmethod + def parse_network_path(path: str) -> Dict[str, str]: + """Parses a network path into its component segments.""" + m = re.match(r"^networks/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = CdnConfigServiceClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = CdnConfigServiceClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = CdnConfigServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = CdnConfigServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = CdnConfigServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = CdnConfigServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, CdnConfigServiceTransport, Callable[..., CdnConfigServiceTransport] + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the cdn config service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,CdnConfigServiceTransport,Callable[..., CdnConfigServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the CdnConfigServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + CdnConfigServiceClient._read_environment_variables() + ) + self._client_cert_source = CdnConfigServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = CdnConfigServiceClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, CdnConfigServiceTransport) + if transport_provided: + # transport is a CdnConfigServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(CdnConfigServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or CdnConfigServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[CdnConfigServiceTransport], + Callable[..., CdnConfigServiceTransport], + ] = ( + CdnConfigServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., CdnConfigServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.ads.admanager_v1.CdnConfigServiceClient`.", + extra={ + "serviceName": "google.ads.admanager.v1.CdnConfigService", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.ads.admanager.v1.CdnConfigService", + "credentialsType": None, + }, + ) + + def get_cdn_config( + self, + request: Optional[Union[cdn_config_service.GetCdnConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cdn_config_messages.CdnConfig: + r"""Retrieves a ``CdnConfig`` object. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_get_cdn_config(): + # Create a client + client = admanager_v1.CdnConfigServiceClient() + + # Initialize request argument(s) + request = admanager_v1.GetCdnConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_cdn_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.GetCdnConfigRequest, dict]): + The request object. Request object for ``GetCdnConfig`` method. + name (str): + Required. The resource name of the CdnConfig. Format: + ``networks/{network_code}/cdnConfigs/{cdn_config_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.admanager_v1.types.CdnConfig: + A CdnConfig encapsulates information + about where and how to ingest and + deliver content enabled for DAI (Dynamic + Ad Insertion). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, cdn_config_service.GetCdnConfigRequest): + request = cdn_config_service.GetCdnConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_cdn_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_cdn_configs( + self, + request: Optional[Union[cdn_config_service.ListCdnConfigsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListCdnConfigsPager: + r"""Lists ``CdnConfig`` objects. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_list_cdn_configs(): + # Create a client + client = admanager_v1.CdnConfigServiceClient() + + # Initialize request argument(s) + request = admanager_v1.ListCdnConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_cdn_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.ListCdnConfigsRequest, dict]): + The request object. Request object for ``ListCdnConfigs`` method. + parent (str): + Required. The parent, which owns this collection of + CdnConfigs. Format: ``networks/{network_code}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.admanager_v1.services.cdn_config_service.pagers.ListCdnConfigsPager: + Response object for ListCdnConfigsRequest containing matching + CdnConfig objects. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, cdn_config_service.ListCdnConfigsRequest): + request = cdn_config_service.ListCdnConfigsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_cdn_configs] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListCdnConfigsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_cdn_config( + self, + request: Optional[ + Union[cdn_config_service.CreateCdnConfigRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + cdn_config: Optional[cdn_config_messages.CdnConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cdn_config_messages.CdnConfig: + r"""Creates a ``CdnConfig`` object. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_create_cdn_config(): + # Create a client + client = admanager_v1.CdnConfigServiceClient() + + # Initialize request argument(s) + request = admanager_v1.CreateCdnConfigRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_cdn_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.CreateCdnConfigRequest, dict]): + The request object. Request object for ``CreateCdnConfig`` method. + parent (str): + Required. The parent resource where this ``CdnConfig`` + will be created. Format: ``networks/{network_code}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + cdn_config (google.ads.admanager_v1.types.CdnConfig): + Required. The ``CdnConfig`` to create. + This corresponds to the ``cdn_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.admanager_v1.types.CdnConfig: + A CdnConfig encapsulates information + about where and how to ingest and + deliver content enabled for DAI (Dynamic + Ad Insertion). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, cdn_config] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, cdn_config_service.CreateCdnConfigRequest): + request = cdn_config_service.CreateCdnConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if cdn_config is not None: + request.cdn_config = cdn_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_cdn_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_create_cdn_configs( + self, + request: Optional[ + Union[cdn_config_service.BatchCreateCdnConfigsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + requests: Optional[ + MutableSequence[cdn_config_service.CreateCdnConfigRequest] + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cdn_config_service.BatchCreateCdnConfigsResponse: + r"""Batch creates ``CdnConfig`` objects. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_batch_create_cdn_configs(): + # Create a client + client = admanager_v1.CdnConfigServiceClient() + + # Initialize request argument(s) + requests = admanager_v1.CreateCdnConfigRequest() + requests.parent = "parent_value" + + request = admanager_v1.BatchCreateCdnConfigsRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = client.batch_create_cdn_configs(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.BatchCreateCdnConfigsRequest, dict]): + The request object. Request object for ``BatchCreateCdnConfigs`` method. + parent (str): + Required. The parent resource where ``CdnConfigs`` will + be created. Format: ``networks/{network_code}`` The + parent field in the CreateCdnConfigRequest must match + this field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + requests (MutableSequence[google.ads.admanager_v1.types.CreateCdnConfigRequest]): + Required. The ``CdnConfig`` objects to create. A maximum + of 100 objects can be created in a batch. + + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.admanager_v1.types.BatchCreateCdnConfigsResponse: + Response object for BatchCreateCdnConfigs method. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, requests] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, cdn_config_service.BatchCreateCdnConfigsRequest): + request = cdn_config_service.BatchCreateCdnConfigsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_create_cdn_configs] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_cdn_config( + self, + request: Optional[ + Union[cdn_config_service.UpdateCdnConfigRequest, dict] + ] = None, + *, + cdn_config: Optional[cdn_config_messages.CdnConfig] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cdn_config_messages.CdnConfig: + r"""Updates a ``CdnConfig`` object. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_update_cdn_config(): + # Create a client + client = admanager_v1.CdnConfigServiceClient() + + # Initialize request argument(s) + request = admanager_v1.UpdateCdnConfigRequest( + ) + + # Make the request + response = client.update_cdn_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.UpdateCdnConfigRequest, dict]): + The request object. Request object for ``UpdateCdnConfig`` method. + cdn_config (google.ads.admanager_v1.types.CdnConfig): + Required. The ``CdnConfig`` to update. + + The ``CdnConfig``'s ``name`` is used to identify the + ``CdnConfig`` to update. + + This corresponds to the ``cdn_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to + update. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.admanager_v1.types.CdnConfig: + A CdnConfig encapsulates information + about where and how to ingest and + deliver content enabled for DAI (Dynamic + Ad Insertion). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [cdn_config, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, cdn_config_service.UpdateCdnConfigRequest): + request = cdn_config_service.UpdateCdnConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if cdn_config is not None: + request.cdn_config = cdn_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_cdn_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("cdn_config.name", request.cdn_config.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_update_cdn_configs( + self, + request: Optional[ + Union[cdn_config_service.BatchUpdateCdnConfigsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + requests: Optional[ + MutableSequence[cdn_config_service.UpdateCdnConfigRequest] + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cdn_config_service.BatchUpdateCdnConfigsResponse: + r"""Batch updates ``CdnConfig`` objects. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_batch_update_cdn_configs(): + # Create a client + client = admanager_v1.CdnConfigServiceClient() + + # Initialize request argument(s) + request = admanager_v1.BatchUpdateCdnConfigsRequest( + parent="parent_value", + ) + + # Make the request + response = client.batch_update_cdn_configs(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.BatchUpdateCdnConfigsRequest, dict]): + The request object. Request object for ``BatchUpdateCdnConfigs`` method. + parent (str): + Required. The parent resource where ``CdnConfigs`` will + be updated. Format: ``networks/{network_code}`` The + parent field in the UpdateCdnConfigRequest must match + this field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + requests (MutableSequence[google.ads.admanager_v1.types.UpdateCdnConfigRequest]): + Required. The ``CdnConfig`` objects to update. A maximum + of 100 objects can be updated in a batch. + + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.admanager_v1.types.BatchUpdateCdnConfigsResponse: + Response object for BatchUpdateCdnConfigs method. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, requests] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, cdn_config_service.BatchUpdateCdnConfigsRequest): + request = cdn_config_service.BatchUpdateCdnConfigsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_update_cdn_configs] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_activate_cdn_configs( + self, + request: Optional[ + Union[cdn_config_service.BatchActivateCdnConfigsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + names: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cdn_config_service.BatchActivateCdnConfigsResponse: + r"""Batch activates ``CdnConfig`` objects. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_batch_activate_cdn_configs(): + # Create a client + client = admanager_v1.CdnConfigServiceClient() + + # Initialize request argument(s) + request = admanager_v1.BatchActivateCdnConfigsRequest( + parent="parent_value", + names=['names_value1', 'names_value2'], + ) + + # Make the request + response = client.batch_activate_cdn_configs(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.BatchActivateCdnConfigsRequest, dict]): + The request object. Request message to activate ``CdnConfig`` objects. + parent (str): + Required. Format: ``networks/{network_code}`` + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + names (MutableSequence[str]): + Required. The resource names of the ``CdnConfig`` + objects to activate. Format: + ``networks/{network_code}/cdnConfigs/{cdn_config_id}`` + + This corresponds to the ``names`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.admanager_v1.types.BatchActivateCdnConfigsResponse: + Response message for BatchActivateCdnConfigs method. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, names] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, cdn_config_service.BatchActivateCdnConfigsRequest): + request = cdn_config_service.BatchActivateCdnConfigsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if names is not None: + request.names = names + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.batch_activate_cdn_configs + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_archive_cdn_configs( + self, + request: Optional[ + Union[cdn_config_service.BatchArchiveCdnConfigsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + names: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cdn_config_service.BatchArchiveCdnConfigsResponse: + r"""Batch archives ``CdnConfig`` objects. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_batch_archive_cdn_configs(): + # Create a client + client = admanager_v1.CdnConfigServiceClient() + + # Initialize request argument(s) + request = admanager_v1.BatchArchiveCdnConfigsRequest( + parent="parent_value", + names=['names_value1', 'names_value2'], + ) + + # Make the request + response = client.batch_archive_cdn_configs(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.BatchArchiveCdnConfigsRequest, dict]): + The request object. Request message to archive ``CdnConfig`` objects. + parent (str): + Required. Format: ``networks/{network_code}`` + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + names (MutableSequence[str]): + Required. The resource names of the ``CdnConfig`` + objects to archive. Format: + ``networks/{network_code}/cdnConfigs/{cdn_config_id}`` + + This corresponds to the ``names`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.admanager_v1.types.BatchArchiveCdnConfigsResponse: + Response object for BatchArchiveCdnConfigs method. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, names] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, cdn_config_service.BatchArchiveCdnConfigsRequest): + request = cdn_config_service.BatchArchiveCdnConfigsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if names is not None: + request.names = names + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.batch_archive_cdn_configs + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "CdnConfigServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("CdnConfigServiceClient",) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/cdn_config_service/pagers.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/cdn_config_service/pagers.py new file mode 100644 index 000000000000..effc9595db25 --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/cdn_config_service/pagers.py @@ -0,0 +1,117 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.ads.admanager_v1.types import cdn_config_messages, cdn_config_service + + +class ListCdnConfigsPager: + """A pager for iterating through ``list_cdn_configs`` requests. + + This class thinly wraps an initial + :class:`google.ads.admanager_v1.types.ListCdnConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``cdn_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListCdnConfigs`` requests and continue to iterate + through the ``cdn_configs`` field on the + corresponding responses. + + All the usual :class:`google.ads.admanager_v1.types.ListCdnConfigsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., cdn_config_service.ListCdnConfigsResponse], + request: cdn_config_service.ListCdnConfigsRequest, + response: cdn_config_service.ListCdnConfigsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.ads.admanager_v1.types.ListCdnConfigsRequest): + The initial request object. + response (google.ads.admanager_v1.types.ListCdnConfigsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = cdn_config_service.ListCdnConfigsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[cdn_config_service.ListCdnConfigsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[cdn_config_messages.CdnConfig]: + for page in self.pages: + yield from page.cdn_configs + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/cdn_config_service/transports/README.rst b/packages/google-ads-admanager/google/ads/admanager_v1/services/cdn_config_service/transports/README.rst new file mode 100644 index 000000000000..2d86b74d71af --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/cdn_config_service/transports/README.rst @@ -0,0 +1,10 @@ + +transport inheritance structure +_______________________________ + +``CdnConfigServiceTransport`` is the ABC for all transports. + +- public child ``CdnConfigServiceGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``). +- public child ``CdnConfigServiceGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``). +- private child ``_BaseCdnConfigServiceRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``). +- public child ``CdnConfigServiceRestTransport`` for sync REST transport with inner classes ``METHOD`` derived from the parent's corresponding ``_BaseMETHOD`` classes (defined in ``rest.py``). diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/cdn_config_service/transports/__init__.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/cdn_config_service/transports/__init__.py new file mode 100644 index 000000000000..1ba6d78b7828 --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/cdn_config_service/transports/__init__.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import CdnConfigServiceTransport +from .rest import CdnConfigServiceRestInterceptor, CdnConfigServiceRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[CdnConfigServiceTransport]] +_transport_registry["rest"] = CdnConfigServiceRestTransport + +__all__ = ( + "CdnConfigServiceTransport", + "CdnConfigServiceRestTransport", + "CdnConfigServiceRestInterceptor", +) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/cdn_config_service/transports/base.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/cdn_config_service/transports/base.py new file mode 100644 index 000000000000..59b1b0bc4a99 --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/cdn_config_service/transports/base.py @@ -0,0 +1,318 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.ads.admanager_v1 import gapic_version as package_version +from google.ads.admanager_v1.types import cdn_config_messages, cdn_config_service + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class CdnConfigServiceTransport(abc.ABC): + """Abstract transport class for CdnConfigService.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/admanager", + "https://www.googleapis.com/auth/admanager.readonly", + ) + + DEFAULT_HOST: str = "admanager.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'admanager.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_cdn_config: gapic_v1.method.wrap_method( + self.get_cdn_config, + default_timeout=None, + client_info=client_info, + ), + self.list_cdn_configs: gapic_v1.method.wrap_method( + self.list_cdn_configs, + default_timeout=None, + client_info=client_info, + ), + self.create_cdn_config: gapic_v1.method.wrap_method( + self.create_cdn_config, + default_timeout=None, + client_info=client_info, + ), + self.batch_create_cdn_configs: gapic_v1.method.wrap_method( + self.batch_create_cdn_configs, + default_timeout=None, + client_info=client_info, + ), + self.update_cdn_config: gapic_v1.method.wrap_method( + self.update_cdn_config, + default_timeout=None, + client_info=client_info, + ), + self.batch_update_cdn_configs: gapic_v1.method.wrap_method( + self.batch_update_cdn_configs, + default_timeout=None, + client_info=client_info, + ), + self.batch_activate_cdn_configs: gapic_v1.method.wrap_method( + self.batch_activate_cdn_configs, + default_timeout=None, + client_info=client_info, + ), + self.batch_archive_cdn_configs: gapic_v1.method.wrap_method( + self.batch_archive_cdn_configs, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def get_cdn_config( + self, + ) -> Callable[ + [cdn_config_service.GetCdnConfigRequest], + Union[cdn_config_messages.CdnConfig, Awaitable[cdn_config_messages.CdnConfig]], + ]: + raise NotImplementedError() + + @property + def list_cdn_configs( + self, + ) -> Callable[ + [cdn_config_service.ListCdnConfigsRequest], + Union[ + cdn_config_service.ListCdnConfigsResponse, + Awaitable[cdn_config_service.ListCdnConfigsResponse], + ], + ]: + raise NotImplementedError() + + @property + def create_cdn_config( + self, + ) -> Callable[ + [cdn_config_service.CreateCdnConfigRequest], + Union[cdn_config_messages.CdnConfig, Awaitable[cdn_config_messages.CdnConfig]], + ]: + raise NotImplementedError() + + @property + def batch_create_cdn_configs( + self, + ) -> Callable[ + [cdn_config_service.BatchCreateCdnConfigsRequest], + Union[ + cdn_config_service.BatchCreateCdnConfigsResponse, + Awaitable[cdn_config_service.BatchCreateCdnConfigsResponse], + ], + ]: + raise NotImplementedError() + + @property + def update_cdn_config( + self, + ) -> Callable[ + [cdn_config_service.UpdateCdnConfigRequest], + Union[cdn_config_messages.CdnConfig, Awaitable[cdn_config_messages.CdnConfig]], + ]: + raise NotImplementedError() + + @property + def batch_update_cdn_configs( + self, + ) -> Callable[ + [cdn_config_service.BatchUpdateCdnConfigsRequest], + Union[ + cdn_config_service.BatchUpdateCdnConfigsResponse, + Awaitable[cdn_config_service.BatchUpdateCdnConfigsResponse], + ], + ]: + raise NotImplementedError() + + @property + def batch_activate_cdn_configs( + self, + ) -> Callable[ + [cdn_config_service.BatchActivateCdnConfigsRequest], + Union[ + cdn_config_service.BatchActivateCdnConfigsResponse, + Awaitable[cdn_config_service.BatchActivateCdnConfigsResponse], + ], + ]: + raise NotImplementedError() + + @property + def batch_archive_cdn_configs( + self, + ) -> Callable[ + [cdn_config_service.BatchArchiveCdnConfigsRequest], + Union[ + cdn_config_service.BatchArchiveCdnConfigsResponse, + Awaitable[cdn_config_service.BatchArchiveCdnConfigsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("CdnConfigServiceTransport",) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/cdn_config_service/transports/rest.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/cdn_config_service/transports/rest.py new file mode 100644 index 000000000000..100c253f4020 --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/cdn_config_service/transports/rest.py @@ -0,0 +1,2278 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +import dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.ads.admanager_v1.types import cdn_config_messages, cdn_config_service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseCdnConfigServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class CdnConfigServiceRestInterceptor: + """Interceptor for CdnConfigService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the CdnConfigServiceRestTransport. + + .. code-block:: python + class MyCustomCdnConfigServiceInterceptor(CdnConfigServiceRestInterceptor): + def pre_batch_activate_cdn_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_activate_cdn_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_batch_archive_cdn_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_archive_cdn_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_batch_create_cdn_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_create_cdn_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_batch_update_cdn_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_update_cdn_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_cdn_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_cdn_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_cdn_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_cdn_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_cdn_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_cdn_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_cdn_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_cdn_config(self, response): + logging.log(f"Received response: {response}") + return response + + transport = CdnConfigServiceRestTransport(interceptor=MyCustomCdnConfigServiceInterceptor()) + client = CdnConfigServiceClient(transport=transport) + + + """ + + def pre_batch_activate_cdn_configs( + self, + request: cdn_config_service.BatchActivateCdnConfigsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cdn_config_service.BatchActivateCdnConfigsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_activate_cdn_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the CdnConfigService server. + """ + return request, metadata + + def post_batch_activate_cdn_configs( + self, response: cdn_config_service.BatchActivateCdnConfigsResponse + ) -> cdn_config_service.BatchActivateCdnConfigsResponse: + """Post-rpc interceptor for batch_activate_cdn_configs + + DEPRECATED. Please use the `post_batch_activate_cdn_configs_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the CdnConfigService server but before + it is returned to user code. This `post_batch_activate_cdn_configs` interceptor runs + before the `post_batch_activate_cdn_configs_with_metadata` interceptor. + """ + return response + + def post_batch_activate_cdn_configs_with_metadata( + self, + response: cdn_config_service.BatchActivateCdnConfigsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cdn_config_service.BatchActivateCdnConfigsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for batch_activate_cdn_configs + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the CdnConfigService server but before it is returned to user code. + + We recommend only using this `post_batch_activate_cdn_configs_with_metadata` + interceptor in new development instead of the `post_batch_activate_cdn_configs` interceptor. + When both interceptors are used, this `post_batch_activate_cdn_configs_with_metadata` interceptor runs after the + `post_batch_activate_cdn_configs` interceptor. The (possibly modified) response returned by + `post_batch_activate_cdn_configs` will be passed to + `post_batch_activate_cdn_configs_with_metadata`. + """ + return response, metadata + + def pre_batch_archive_cdn_configs( + self, + request: cdn_config_service.BatchArchiveCdnConfigsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cdn_config_service.BatchArchiveCdnConfigsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_archive_cdn_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the CdnConfigService server. + """ + return request, metadata + + def post_batch_archive_cdn_configs( + self, response: cdn_config_service.BatchArchiveCdnConfigsResponse + ) -> cdn_config_service.BatchArchiveCdnConfigsResponse: + """Post-rpc interceptor for batch_archive_cdn_configs + + DEPRECATED. Please use the `post_batch_archive_cdn_configs_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the CdnConfigService server but before + it is returned to user code. This `post_batch_archive_cdn_configs` interceptor runs + before the `post_batch_archive_cdn_configs_with_metadata` interceptor. + """ + return response + + def post_batch_archive_cdn_configs_with_metadata( + self, + response: cdn_config_service.BatchArchiveCdnConfigsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cdn_config_service.BatchArchiveCdnConfigsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for batch_archive_cdn_configs + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the CdnConfigService server but before it is returned to user code. + + We recommend only using this `post_batch_archive_cdn_configs_with_metadata` + interceptor in new development instead of the `post_batch_archive_cdn_configs` interceptor. + When both interceptors are used, this `post_batch_archive_cdn_configs_with_metadata` interceptor runs after the + `post_batch_archive_cdn_configs` interceptor. The (possibly modified) response returned by + `post_batch_archive_cdn_configs` will be passed to + `post_batch_archive_cdn_configs_with_metadata`. + """ + return response, metadata + + def pre_batch_create_cdn_configs( + self, + request: cdn_config_service.BatchCreateCdnConfigsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cdn_config_service.BatchCreateCdnConfigsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_create_cdn_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the CdnConfigService server. + """ + return request, metadata + + def post_batch_create_cdn_configs( + self, response: cdn_config_service.BatchCreateCdnConfigsResponse + ) -> cdn_config_service.BatchCreateCdnConfigsResponse: + """Post-rpc interceptor for batch_create_cdn_configs + + DEPRECATED. Please use the `post_batch_create_cdn_configs_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the CdnConfigService server but before + it is returned to user code. This `post_batch_create_cdn_configs` interceptor runs + before the `post_batch_create_cdn_configs_with_metadata` interceptor. + """ + return response + + def post_batch_create_cdn_configs_with_metadata( + self, + response: cdn_config_service.BatchCreateCdnConfigsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cdn_config_service.BatchCreateCdnConfigsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for batch_create_cdn_configs + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the CdnConfigService server but before it is returned to user code. + + We recommend only using this `post_batch_create_cdn_configs_with_metadata` + interceptor in new development instead of the `post_batch_create_cdn_configs` interceptor. + When both interceptors are used, this `post_batch_create_cdn_configs_with_metadata` interceptor runs after the + `post_batch_create_cdn_configs` interceptor. The (possibly modified) response returned by + `post_batch_create_cdn_configs` will be passed to + `post_batch_create_cdn_configs_with_metadata`. + """ + return response, metadata + + def pre_batch_update_cdn_configs( + self, + request: cdn_config_service.BatchUpdateCdnConfigsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cdn_config_service.BatchUpdateCdnConfigsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_update_cdn_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the CdnConfigService server. + """ + return request, metadata + + def post_batch_update_cdn_configs( + self, response: cdn_config_service.BatchUpdateCdnConfigsResponse + ) -> cdn_config_service.BatchUpdateCdnConfigsResponse: + """Post-rpc interceptor for batch_update_cdn_configs + + DEPRECATED. Please use the `post_batch_update_cdn_configs_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the CdnConfigService server but before + it is returned to user code. This `post_batch_update_cdn_configs` interceptor runs + before the `post_batch_update_cdn_configs_with_metadata` interceptor. + """ + return response + + def post_batch_update_cdn_configs_with_metadata( + self, + response: cdn_config_service.BatchUpdateCdnConfigsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cdn_config_service.BatchUpdateCdnConfigsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for batch_update_cdn_configs + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the CdnConfigService server but before it is returned to user code. + + We recommend only using this `post_batch_update_cdn_configs_with_metadata` + interceptor in new development instead of the `post_batch_update_cdn_configs` interceptor. + When both interceptors are used, this `post_batch_update_cdn_configs_with_metadata` interceptor runs after the + `post_batch_update_cdn_configs` interceptor. The (possibly modified) response returned by + `post_batch_update_cdn_configs` will be passed to + `post_batch_update_cdn_configs_with_metadata`. + """ + return response, metadata + + def pre_create_cdn_config( + self, + request: cdn_config_service.CreateCdnConfigRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cdn_config_service.CreateCdnConfigRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_cdn_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the CdnConfigService server. + """ + return request, metadata + + def post_create_cdn_config( + self, response: cdn_config_messages.CdnConfig + ) -> cdn_config_messages.CdnConfig: + """Post-rpc interceptor for create_cdn_config + + DEPRECATED. Please use the `post_create_cdn_config_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the CdnConfigService server but before + it is returned to user code. This `post_create_cdn_config` interceptor runs + before the `post_create_cdn_config_with_metadata` interceptor. + """ + return response + + def post_create_cdn_config_with_metadata( + self, + response: cdn_config_messages.CdnConfig, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[cdn_config_messages.CdnConfig, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_cdn_config + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the CdnConfigService server but before it is returned to user code. + + We recommend only using this `post_create_cdn_config_with_metadata` + interceptor in new development instead of the `post_create_cdn_config` interceptor. + When both interceptors are used, this `post_create_cdn_config_with_metadata` interceptor runs after the + `post_create_cdn_config` interceptor. The (possibly modified) response returned by + `post_create_cdn_config` will be passed to + `post_create_cdn_config_with_metadata`. + """ + return response, metadata + + def pre_get_cdn_config( + self, + request: cdn_config_service.GetCdnConfigRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cdn_config_service.GetCdnConfigRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_cdn_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the CdnConfigService server. + """ + return request, metadata + + def post_get_cdn_config( + self, response: cdn_config_messages.CdnConfig + ) -> cdn_config_messages.CdnConfig: + """Post-rpc interceptor for get_cdn_config + + DEPRECATED. Please use the `post_get_cdn_config_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the CdnConfigService server but before + it is returned to user code. This `post_get_cdn_config` interceptor runs + before the `post_get_cdn_config_with_metadata` interceptor. + """ + return response + + def post_get_cdn_config_with_metadata( + self, + response: cdn_config_messages.CdnConfig, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[cdn_config_messages.CdnConfig, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_cdn_config + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the CdnConfigService server but before it is returned to user code. + + We recommend only using this `post_get_cdn_config_with_metadata` + interceptor in new development instead of the `post_get_cdn_config` interceptor. + When both interceptors are used, this `post_get_cdn_config_with_metadata` interceptor runs after the + `post_get_cdn_config` interceptor. The (possibly modified) response returned by + `post_get_cdn_config` will be passed to + `post_get_cdn_config_with_metadata`. + """ + return response, metadata + + def pre_list_cdn_configs( + self, + request: cdn_config_service.ListCdnConfigsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cdn_config_service.ListCdnConfigsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_cdn_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the CdnConfigService server. + """ + return request, metadata + + def post_list_cdn_configs( + self, response: cdn_config_service.ListCdnConfigsResponse + ) -> cdn_config_service.ListCdnConfigsResponse: + """Post-rpc interceptor for list_cdn_configs + + DEPRECATED. Please use the `post_list_cdn_configs_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the CdnConfigService server but before + it is returned to user code. This `post_list_cdn_configs` interceptor runs + before the `post_list_cdn_configs_with_metadata` interceptor. + """ + return response + + def post_list_cdn_configs_with_metadata( + self, + response: cdn_config_service.ListCdnConfigsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cdn_config_service.ListCdnConfigsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_cdn_configs + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the CdnConfigService server but before it is returned to user code. + + We recommend only using this `post_list_cdn_configs_with_metadata` + interceptor in new development instead of the `post_list_cdn_configs` interceptor. + When both interceptors are used, this `post_list_cdn_configs_with_metadata` interceptor runs after the + `post_list_cdn_configs` interceptor. The (possibly modified) response returned by + `post_list_cdn_configs` will be passed to + `post_list_cdn_configs_with_metadata`. + """ + return response, metadata + + def pre_update_cdn_config( + self, + request: cdn_config_service.UpdateCdnConfigRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cdn_config_service.UpdateCdnConfigRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_cdn_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the CdnConfigService server. + """ + return request, metadata + + def post_update_cdn_config( + self, response: cdn_config_messages.CdnConfig + ) -> cdn_config_messages.CdnConfig: + """Post-rpc interceptor for update_cdn_config + + DEPRECATED. Please use the `post_update_cdn_config_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the CdnConfigService server but before + it is returned to user code. This `post_update_cdn_config` interceptor runs + before the `post_update_cdn_config_with_metadata` interceptor. + """ + return response + + def post_update_cdn_config_with_metadata( + self, + response: cdn_config_messages.CdnConfig, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[cdn_config_messages.CdnConfig, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_cdn_config + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the CdnConfigService server but before it is returned to user code. + + We recommend only using this `post_update_cdn_config_with_metadata` + interceptor in new development instead of the `post_update_cdn_config` interceptor. + When both interceptors are used, this `post_update_cdn_config_with_metadata` interceptor runs after the + `post_update_cdn_config` interceptor. The (possibly modified) response returned by + `post_update_cdn_config` will be passed to + `post_update_cdn_config_with_metadata`. + """ + return response, metadata + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the CdnConfigService server. + """ + return request, metadata + + def post_cancel_operation(self, response: None) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the CdnConfigService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the CdnConfigService server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the CdnConfigService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class CdnConfigServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: CdnConfigServiceRestInterceptor + + +class CdnConfigServiceRestTransport(_BaseCdnConfigServiceRestTransport): + """REST backend synchronous transport for CdnConfigService. + + Provides methods for handling ``CdnConfig`` objects. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "admanager.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[CdnConfigServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'admanager.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[CdnConfigServiceRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or CdnConfigServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _BatchActivateCdnConfigs( + _BaseCdnConfigServiceRestTransport._BaseBatchActivateCdnConfigs, + CdnConfigServiceRestStub, + ): + def __hash__(self): + return hash("CdnConfigServiceRestTransport.BatchActivateCdnConfigs") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: cdn_config_service.BatchActivateCdnConfigsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cdn_config_service.BatchActivateCdnConfigsResponse: + r"""Call the batch activate cdn + configs method over HTTP. + + Args: + request (~.cdn_config_service.BatchActivateCdnConfigsRequest): + The request object. Request message to activate ``CdnConfig`` objects. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.cdn_config_service.BatchActivateCdnConfigsResponse: + Response message for ``BatchActivateCdnConfigs`` method. + """ + + http_options = _BaseCdnConfigServiceRestTransport._BaseBatchActivateCdnConfigs._get_http_options() + + request, metadata = self._interceptor.pre_batch_activate_cdn_configs( + request, metadata + ) + transcoded_request = _BaseCdnConfigServiceRestTransport._BaseBatchActivateCdnConfigs._get_transcoded_request( + http_options, request + ) + + body = _BaseCdnConfigServiceRestTransport._BaseBatchActivateCdnConfigs._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseCdnConfigServiceRestTransport._BaseBatchActivateCdnConfigs._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.CdnConfigServiceClient.BatchActivateCdnConfigs", + extra={ + "serviceName": "google.ads.admanager.v1.CdnConfigService", + "rpcName": "BatchActivateCdnConfigs", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + CdnConfigServiceRestTransport._BatchActivateCdnConfigs._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = cdn_config_service.BatchActivateCdnConfigsResponse() + pb_resp = cdn_config_service.BatchActivateCdnConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_activate_cdn_configs(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_batch_activate_cdn_configs_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + cdn_config_service.BatchActivateCdnConfigsResponse.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.CdnConfigServiceClient.batch_activate_cdn_configs", + extra={ + "serviceName": "google.ads.admanager.v1.CdnConfigService", + "rpcName": "BatchActivateCdnConfigs", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _BatchArchiveCdnConfigs( + _BaseCdnConfigServiceRestTransport._BaseBatchArchiveCdnConfigs, + CdnConfigServiceRestStub, + ): + def __hash__(self): + return hash("CdnConfigServiceRestTransport.BatchArchiveCdnConfigs") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: cdn_config_service.BatchArchiveCdnConfigsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cdn_config_service.BatchArchiveCdnConfigsResponse: + r"""Call the batch archive cdn configs method over HTTP. + + Args: + request (~.cdn_config_service.BatchArchiveCdnConfigsRequest): + The request object. Request message to archive ``CdnConfig`` objects. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.cdn_config_service.BatchArchiveCdnConfigsResponse: + Response object for ``BatchArchiveCdnConfigs`` method. + """ + + http_options = _BaseCdnConfigServiceRestTransport._BaseBatchArchiveCdnConfigs._get_http_options() + + request, metadata = self._interceptor.pre_batch_archive_cdn_configs( + request, metadata + ) + transcoded_request = _BaseCdnConfigServiceRestTransport._BaseBatchArchiveCdnConfigs._get_transcoded_request( + http_options, request + ) + + body = _BaseCdnConfigServiceRestTransport._BaseBatchArchiveCdnConfigs._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseCdnConfigServiceRestTransport._BaseBatchArchiveCdnConfigs._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.CdnConfigServiceClient.BatchArchiveCdnConfigs", + extra={ + "serviceName": "google.ads.admanager.v1.CdnConfigService", + "rpcName": "BatchArchiveCdnConfigs", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + CdnConfigServiceRestTransport._BatchArchiveCdnConfigs._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = cdn_config_service.BatchArchiveCdnConfigsResponse() + pb_resp = cdn_config_service.BatchArchiveCdnConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_archive_cdn_configs(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_batch_archive_cdn_configs_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + cdn_config_service.BatchArchiveCdnConfigsResponse.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.CdnConfigServiceClient.batch_archive_cdn_configs", + extra={ + "serviceName": "google.ads.admanager.v1.CdnConfigService", + "rpcName": "BatchArchiveCdnConfigs", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _BatchCreateCdnConfigs( + _BaseCdnConfigServiceRestTransport._BaseBatchCreateCdnConfigs, + CdnConfigServiceRestStub, + ): + def __hash__(self): + return hash("CdnConfigServiceRestTransport.BatchCreateCdnConfigs") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: cdn_config_service.BatchCreateCdnConfigsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cdn_config_service.BatchCreateCdnConfigsResponse: + r"""Call the batch create cdn configs method over HTTP. + + Args: + request (~.cdn_config_service.BatchCreateCdnConfigsRequest): + The request object. Request object for ``BatchCreateCdnConfigs`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.cdn_config_service.BatchCreateCdnConfigsResponse: + Response object for ``BatchCreateCdnConfigs`` method. + """ + + http_options = _BaseCdnConfigServiceRestTransport._BaseBatchCreateCdnConfigs._get_http_options() + + request, metadata = self._interceptor.pre_batch_create_cdn_configs( + request, metadata + ) + transcoded_request = _BaseCdnConfigServiceRestTransport._BaseBatchCreateCdnConfigs._get_transcoded_request( + http_options, request + ) + + body = _BaseCdnConfigServiceRestTransport._BaseBatchCreateCdnConfigs._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseCdnConfigServiceRestTransport._BaseBatchCreateCdnConfigs._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.CdnConfigServiceClient.BatchCreateCdnConfigs", + extra={ + "serviceName": "google.ads.admanager.v1.CdnConfigService", + "rpcName": "BatchCreateCdnConfigs", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + CdnConfigServiceRestTransport._BatchCreateCdnConfigs._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = cdn_config_service.BatchCreateCdnConfigsResponse() + pb_resp = cdn_config_service.BatchCreateCdnConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_create_cdn_configs(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_batch_create_cdn_configs_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + cdn_config_service.BatchCreateCdnConfigsResponse.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.CdnConfigServiceClient.batch_create_cdn_configs", + extra={ + "serviceName": "google.ads.admanager.v1.CdnConfigService", + "rpcName": "BatchCreateCdnConfigs", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _BatchUpdateCdnConfigs( + _BaseCdnConfigServiceRestTransport._BaseBatchUpdateCdnConfigs, + CdnConfigServiceRestStub, + ): + def __hash__(self): + return hash("CdnConfigServiceRestTransport.BatchUpdateCdnConfigs") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: cdn_config_service.BatchUpdateCdnConfigsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cdn_config_service.BatchUpdateCdnConfigsResponse: + r"""Call the batch update cdn configs method over HTTP. + + Args: + request (~.cdn_config_service.BatchUpdateCdnConfigsRequest): + The request object. Request object for ``BatchUpdateCdnConfigs`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.cdn_config_service.BatchUpdateCdnConfigsResponse: + Response object for ``BatchUpdateCdnConfigs`` method. + """ + + http_options = _BaseCdnConfigServiceRestTransport._BaseBatchUpdateCdnConfigs._get_http_options() + + request, metadata = self._interceptor.pre_batch_update_cdn_configs( + request, metadata + ) + transcoded_request = _BaseCdnConfigServiceRestTransport._BaseBatchUpdateCdnConfigs._get_transcoded_request( + http_options, request + ) + + body = _BaseCdnConfigServiceRestTransport._BaseBatchUpdateCdnConfigs._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseCdnConfigServiceRestTransport._BaseBatchUpdateCdnConfigs._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.CdnConfigServiceClient.BatchUpdateCdnConfigs", + extra={ + "serviceName": "google.ads.admanager.v1.CdnConfigService", + "rpcName": "BatchUpdateCdnConfigs", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + CdnConfigServiceRestTransport._BatchUpdateCdnConfigs._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = cdn_config_service.BatchUpdateCdnConfigsResponse() + pb_resp = cdn_config_service.BatchUpdateCdnConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_update_cdn_configs(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_batch_update_cdn_configs_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + cdn_config_service.BatchUpdateCdnConfigsResponse.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.CdnConfigServiceClient.batch_update_cdn_configs", + extra={ + "serviceName": "google.ads.admanager.v1.CdnConfigService", + "rpcName": "BatchUpdateCdnConfigs", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateCdnConfig( + _BaseCdnConfigServiceRestTransport._BaseCreateCdnConfig, + CdnConfigServiceRestStub, + ): + def __hash__(self): + return hash("CdnConfigServiceRestTransport.CreateCdnConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: cdn_config_service.CreateCdnConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cdn_config_messages.CdnConfig: + r"""Call the create cdn config method over HTTP. + + Args: + request (~.cdn_config_service.CreateCdnConfigRequest): + The request object. Request object for ``CreateCdnConfig`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.cdn_config_messages.CdnConfig: + A CdnConfig encapsulates information + about where and how to ingest and + deliver content enabled for DAI (Dynamic + Ad Insertion). + + """ + + http_options = _BaseCdnConfigServiceRestTransport._BaseCreateCdnConfig._get_http_options() + + request, metadata = self._interceptor.pre_create_cdn_config( + request, metadata + ) + transcoded_request = _BaseCdnConfigServiceRestTransport._BaseCreateCdnConfig._get_transcoded_request( + http_options, request + ) + + body = _BaseCdnConfigServiceRestTransport._BaseCreateCdnConfig._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseCdnConfigServiceRestTransport._BaseCreateCdnConfig._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.CdnConfigServiceClient.CreateCdnConfig", + extra={ + "serviceName": "google.ads.admanager.v1.CdnConfigService", + "rpcName": "CreateCdnConfig", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = CdnConfigServiceRestTransport._CreateCdnConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = cdn_config_messages.CdnConfig() + pb_resp = cdn_config_messages.CdnConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_cdn_config(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_cdn_config_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = cdn_config_messages.CdnConfig.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.CdnConfigServiceClient.create_cdn_config", + extra={ + "serviceName": "google.ads.admanager.v1.CdnConfigService", + "rpcName": "CreateCdnConfig", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetCdnConfig( + _BaseCdnConfigServiceRestTransport._BaseGetCdnConfig, CdnConfigServiceRestStub + ): + def __hash__(self): + return hash("CdnConfigServiceRestTransport.GetCdnConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: cdn_config_service.GetCdnConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cdn_config_messages.CdnConfig: + r"""Call the get cdn config method over HTTP. + + Args: + request (~.cdn_config_service.GetCdnConfigRequest): + The request object. Request object for ``GetCdnConfig`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.cdn_config_messages.CdnConfig: + A CdnConfig encapsulates information + about where and how to ingest and + deliver content enabled for DAI (Dynamic + Ad Insertion). + + """ + + http_options = ( + _BaseCdnConfigServiceRestTransport._BaseGetCdnConfig._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_cdn_config(request, metadata) + transcoded_request = _BaseCdnConfigServiceRestTransport._BaseGetCdnConfig._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseCdnConfigServiceRestTransport._BaseGetCdnConfig._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.CdnConfigServiceClient.GetCdnConfig", + extra={ + "serviceName": "google.ads.admanager.v1.CdnConfigService", + "rpcName": "GetCdnConfig", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = CdnConfigServiceRestTransport._GetCdnConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = cdn_config_messages.CdnConfig() + pb_resp = cdn_config_messages.CdnConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_cdn_config(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_cdn_config_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = cdn_config_messages.CdnConfig.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.CdnConfigServiceClient.get_cdn_config", + extra={ + "serviceName": "google.ads.admanager.v1.CdnConfigService", + "rpcName": "GetCdnConfig", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListCdnConfigs( + _BaseCdnConfigServiceRestTransport._BaseListCdnConfigs, CdnConfigServiceRestStub + ): + def __hash__(self): + return hash("CdnConfigServiceRestTransport.ListCdnConfigs") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: cdn_config_service.ListCdnConfigsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cdn_config_service.ListCdnConfigsResponse: + r"""Call the list cdn configs method over HTTP. + + Args: + request (~.cdn_config_service.ListCdnConfigsRequest): + The request object. Request object for ``ListCdnConfigs`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.cdn_config_service.ListCdnConfigsResponse: + Response object for ``ListCdnConfigsRequest`` containing + matching ``CdnConfig`` objects. + + """ + + http_options = _BaseCdnConfigServiceRestTransport._BaseListCdnConfigs._get_http_options() + + request, metadata = self._interceptor.pre_list_cdn_configs( + request, metadata + ) + transcoded_request = _BaseCdnConfigServiceRestTransport._BaseListCdnConfigs._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseCdnConfigServiceRestTransport._BaseListCdnConfigs._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.CdnConfigServiceClient.ListCdnConfigs", + extra={ + "serviceName": "google.ads.admanager.v1.CdnConfigService", + "rpcName": "ListCdnConfigs", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = CdnConfigServiceRestTransport._ListCdnConfigs._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = cdn_config_service.ListCdnConfigsResponse() + pb_resp = cdn_config_service.ListCdnConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_cdn_configs(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_cdn_configs_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + cdn_config_service.ListCdnConfigsResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.CdnConfigServiceClient.list_cdn_configs", + extra={ + "serviceName": "google.ads.admanager.v1.CdnConfigService", + "rpcName": "ListCdnConfigs", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateCdnConfig( + _BaseCdnConfigServiceRestTransport._BaseUpdateCdnConfig, + CdnConfigServiceRestStub, + ): + def __hash__(self): + return hash("CdnConfigServiceRestTransport.UpdateCdnConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: cdn_config_service.UpdateCdnConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cdn_config_messages.CdnConfig: + r"""Call the update cdn config method over HTTP. + + Args: + request (~.cdn_config_service.UpdateCdnConfigRequest): + The request object. Request object for ``UpdateCdnConfig`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.cdn_config_messages.CdnConfig: + A CdnConfig encapsulates information + about where and how to ingest and + deliver content enabled for DAI (Dynamic + Ad Insertion). + + """ + + http_options = _BaseCdnConfigServiceRestTransport._BaseUpdateCdnConfig._get_http_options() + + request, metadata = self._interceptor.pre_update_cdn_config( + request, metadata + ) + transcoded_request = _BaseCdnConfigServiceRestTransport._BaseUpdateCdnConfig._get_transcoded_request( + http_options, request + ) + + body = _BaseCdnConfigServiceRestTransport._BaseUpdateCdnConfig._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseCdnConfigServiceRestTransport._BaseUpdateCdnConfig._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.CdnConfigServiceClient.UpdateCdnConfig", + extra={ + "serviceName": "google.ads.admanager.v1.CdnConfigService", + "rpcName": "UpdateCdnConfig", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = CdnConfigServiceRestTransport._UpdateCdnConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = cdn_config_messages.CdnConfig() + pb_resp = cdn_config_messages.CdnConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_cdn_config(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_cdn_config_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = cdn_config_messages.CdnConfig.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.CdnConfigServiceClient.update_cdn_config", + extra={ + "serviceName": "google.ads.admanager.v1.CdnConfigService", + "rpcName": "UpdateCdnConfig", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def batch_activate_cdn_configs( + self, + ) -> Callable[ + [cdn_config_service.BatchActivateCdnConfigsRequest], + cdn_config_service.BatchActivateCdnConfigsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchActivateCdnConfigs( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def batch_archive_cdn_configs( + self, + ) -> Callable[ + [cdn_config_service.BatchArchiveCdnConfigsRequest], + cdn_config_service.BatchArchiveCdnConfigsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchArchiveCdnConfigs( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def batch_create_cdn_configs( + self, + ) -> Callable[ + [cdn_config_service.BatchCreateCdnConfigsRequest], + cdn_config_service.BatchCreateCdnConfigsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchCreateCdnConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def batch_update_cdn_configs( + self, + ) -> Callable[ + [cdn_config_service.BatchUpdateCdnConfigsRequest], + cdn_config_service.BatchUpdateCdnConfigsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchUpdateCdnConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_cdn_config( + self, + ) -> Callable[ + [cdn_config_service.CreateCdnConfigRequest], cdn_config_messages.CdnConfig + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateCdnConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_cdn_config( + self, + ) -> Callable[ + [cdn_config_service.GetCdnConfigRequest], cdn_config_messages.CdnConfig + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetCdnConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_cdn_configs( + self, + ) -> Callable[ + [cdn_config_service.ListCdnConfigsRequest], + cdn_config_service.ListCdnConfigsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListCdnConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_cdn_config( + self, + ) -> Callable[ + [cdn_config_service.UpdateCdnConfigRequest], cdn_config_messages.CdnConfig + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateCdnConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation( + _BaseCdnConfigServiceRestTransport._BaseCancelOperation, + CdnConfigServiceRestStub, + ): + def __hash__(self): + return hash("CdnConfigServiceRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseCdnConfigServiceRestTransport._BaseCancelOperation._get_http_options() + + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request = _BaseCdnConfigServiceRestTransport._BaseCancelOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseCdnConfigServiceRestTransport._BaseCancelOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.CdnConfigServiceClient.CancelOperation", + extra={ + "serviceName": "google.ads.admanager.v1.CdnConfigService", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = CdnConfigServiceRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation( + _BaseCdnConfigServiceRestTransport._BaseGetOperation, CdnConfigServiceRestStub + ): + def __hash__(self): + return hash("CdnConfigServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = ( + _BaseCdnConfigServiceRestTransport._BaseGetOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseCdnConfigServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseCdnConfigServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.CdnConfigServiceClient.GetOperation", + extra={ + "serviceName": "google.ads.admanager.v1.CdnConfigService", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = CdnConfigServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.CdnConfigServiceAsyncClient.GetOperation", + extra={ + "serviceName": "google.ads.admanager.v1.CdnConfigService", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("CdnConfigServiceRestTransport",) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/cdn_config_service/transports/rest_base.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/cdn_config_service/transports/rest_base.py new file mode 100644 index 000000000000..f85ec368db03 --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/cdn_config_service/transports/rest_base.py @@ -0,0 +1,578 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.ads.admanager_v1.types import cdn_config_messages, cdn_config_service + +from .base import DEFAULT_CLIENT_INFO, CdnConfigServiceTransport + + +class _BaseCdnConfigServiceRestTransport(CdnConfigServiceTransport): + """Base REST backend transport for CdnConfigService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "admanager.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'admanager.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseBatchActivateCdnConfigs: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=networks/*}/cdnConfigs:batchActivate", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cdn_config_service.BatchActivateCdnConfigsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCdnConfigServiceRestTransport._BaseBatchActivateCdnConfigs._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseBatchArchiveCdnConfigs: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=networks/*}/cdnConfigs:batchArchive", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cdn_config_service.BatchArchiveCdnConfigsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCdnConfigServiceRestTransport._BaseBatchArchiveCdnConfigs._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseBatchCreateCdnConfigs: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=networks/*}/cdnConfigs:batchCreate", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cdn_config_service.BatchCreateCdnConfigsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCdnConfigServiceRestTransport._BaseBatchCreateCdnConfigs._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseBatchUpdateCdnConfigs: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=networks/*}/cdnConfigs:batchUpdate", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cdn_config_service.BatchUpdateCdnConfigsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCdnConfigServiceRestTransport._BaseBatchUpdateCdnConfigs._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateCdnConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=networks/*}/cdnConfigs", + "body": "cdn_config", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cdn_config_service.CreateCdnConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCdnConfigServiceRestTransport._BaseCreateCdnConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetCdnConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=networks/*/cdnConfigs/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cdn_config_service.GetCdnConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCdnConfigServiceRestTransport._BaseGetCdnConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListCdnConfigs: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=networks/*}/cdnConfigs", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cdn_config_service.ListCdnConfigsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCdnConfigServiceRestTransport._BaseListCdnConfigs._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateCdnConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{cdn_config.name=networks/*/cdnConfigs/*}", + "body": "cdn_config", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cdn_config_service.UpdateCdnConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCdnConfigServiceRestTransport._BaseUpdateCdnConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=networks/*/operations/reports/runs/*}:cancel", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=networks/*/operations/reports/runs/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseCdnConfigServiceRestTransport",) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/cms_metadata_key_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/cms_metadata_key_service/client.py index ed0937f14146..a0714159a8b2 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/cms_metadata_key_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/cms_metadata_key_service/client.py @@ -760,7 +760,7 @@ def get_cms_metadata_key( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> cms_metadata_key_messages.CmsMetadataKey: - r"""API to retrieve a ``CmsMetadataKey`` object. + r"""Retrieves a ``CmsMetadataKey`` object. .. code-block:: python @@ -870,7 +870,7 @@ def list_cms_metadata_keys( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListCmsMetadataKeysPager: - r"""API to retrieve a list of ``CmsMetadataKey`` objects. + r"""Lists ``CmsMetadataKey`` objects. .. code-block:: python @@ -995,7 +995,7 @@ def batch_activate_cms_metadata_keys( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> cms_metadata_key_service.BatchActivateCmsMetadataKeysResponse: - r"""API to activate a list of ``CmsMetadataKey`` objects. + r"""Activates a list of ``CmsMetadataKey`` objects. .. code-block:: python @@ -1121,7 +1121,7 @@ def batch_deactivate_cms_metadata_keys( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> cms_metadata_key_service.BatchDeactivateCmsMetadataKeysResponse: - r"""API to deactivate a list of ``CmsMetadataKey`` objects. + r"""Deactivates a list of ``CmsMetadataKey`` objects. .. code-block:: python diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/cms_metadata_value_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/cms_metadata_value_service/client.py index af93ed239cc4..b5c217f94b07 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/cms_metadata_value_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/cms_metadata_value_service/client.py @@ -782,7 +782,7 @@ def get_cms_metadata_value( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> cms_metadata_value_messages.CmsMetadataValue: - r"""API to retrieve a ``CmsMetadataValue`` object. + r"""Retrieves a ``CmsMetadataValue`` object. .. code-block:: python @@ -894,7 +894,7 @@ def list_cms_metadata_values( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListCmsMetadataValuesPager: - r"""API to retrieve a list of ``CmsMetadataValue`` objects. + r"""Lists ``CmsMetadataValue`` objects. .. code-block:: python @@ -1023,7 +1023,7 @@ def batch_activate_cms_metadata_values( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> cms_metadata_value_service.BatchActivateCmsMetadataValuesResponse: - r"""API to activate a list of ``CmsMetadataValue`` objects. + r"""Activates a list of ``CmsMetadataValue`` objects. .. code-block:: python @@ -1154,7 +1154,7 @@ def batch_deactivate_cms_metadata_values( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> cms_metadata_value_service.BatchDeactivateCmsMetadataValuesResponse: - r"""API to deactivate a list of ``CmsMetadataValue`` objects. + r"""Deactivates a list of ``CmsMetadataValue`` objects. .. code-block:: python diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/company_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/company_service/client.py index 2b5edba9a89f..ad92e2b92f77 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/company_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/company_service/client.py @@ -805,7 +805,7 @@ def get_company( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> company_messages.Company: - r"""API to retrieve a ``Company`` object. + r"""Retrieves a ``Company`` object. .. code-block:: python @@ -910,7 +910,7 @@ def list_companies( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListCompaniesPager: - r"""API to retrieve a list of ``Company`` objects. + r"""Lists ``Company`` objects. .. code-block:: python diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/contact_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/contact_service/client.py index 9a6120a3c832..8326904e5e94 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/contact_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/contact_service/client.py @@ -770,7 +770,7 @@ def get_contact( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> contact_messages.Contact: - r"""API to retrieve a ``Contact`` object. + r"""Retrieves a ``Contact`` object. .. code-block:: python @@ -881,7 +881,7 @@ def list_contacts( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListContactsPager: - r"""API to retrieve a list of ``Contact`` objects. + r"""Lists ``Contact`` objects. .. code-block:: python @@ -1004,7 +1004,7 @@ def create_contact( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> contact_messages.Contact: - r"""API to create a ``Contact`` object. + r"""Creates a ``Contact`` object. .. code-block:: python @@ -1127,7 +1127,7 @@ def batch_create_contacts( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> contact_service.BatchCreateContactsResponse: - r"""API to batch create ``Contact`` objects. + r"""Creates ``Contact`` objects. .. code-block:: python @@ -1247,7 +1247,7 @@ def update_contact( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> contact_messages.Contact: - r"""API to update a ``Contact`` object. + r"""Updates a ``Contact`` object. .. code-block:: python @@ -1375,7 +1375,7 @@ def batch_update_contacts( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> contact_service.BatchUpdateContactsResponse: - r"""API to batch update ``Contact`` objects. + r"""Batch updates ``Contact`` objects. .. code-block:: python diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/content_bundle_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/content_bundle_service/client.py index 41344a2aa859..d939a95b851b 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/content_bundle_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/content_bundle_service/client.py @@ -61,10 +61,12 @@ _LOGGER = std_logging.getLogger(__name__) +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore from google.longrunning import operations_pb2 # type: ignore from google.ads.admanager_v1.services.content_bundle_service import pagers from google.ads.admanager_v1.types import ( + content_bundle_enums, content_bundle_messages, content_bundle_service, ) @@ -757,7 +759,7 @@ def get_content_bundle( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> content_bundle_messages.ContentBundle: - r"""API to retrieve a ``ContentBundle`` object. + r"""Retrieves a ``ContentBundle`` object. .. code-block:: python @@ -873,7 +875,7 @@ def list_content_bundles( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListContentBundlesPager: - r"""API to retrieve a list of ``ContentBundle`` objects. + r"""Lists ``ContentBundle`` objects. .. code-block:: python @@ -986,6 +988,258 @@ def sample_list_content_bundles(): # Done; return the response. return response + def batch_activate_content_bundles( + self, + request: Optional[ + Union[content_bundle_service.BatchActivateContentBundlesRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + names: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> content_bundle_service.BatchActivateContentBundlesResponse: + r"""Activate a list of ``ContentBundle`` objects. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_batch_activate_content_bundles(): + # Create a client + client = admanager_v1.ContentBundleServiceClient() + + # Initialize request argument(s) + request = admanager_v1.BatchActivateContentBundlesRequest( + parent="parent_value", + names=['names_value1', 'names_value2'], + ) + + # Make the request + response = client.batch_activate_content_bundles(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.BatchActivateContentBundlesRequest, dict]): + The request object. Request message for ``BatchActivateContentBundles`` + method. + parent (str): + Required. The parent resource where ``ContentBundles`` + will be activated. Format: ``networks/{network_code}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + names (MutableSequence[str]): + Required. The resource names of the ``ContentBundle``\ s + to activate. Format: + ``networks/{network_code}/contentBundles/{content_bundle_id}`` + + This corresponds to the ``names`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.admanager_v1.types.BatchActivateContentBundlesResponse: + Response object for BatchActivateContentBundles method. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, names] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, content_bundle_service.BatchActivateContentBundlesRequest + ): + request = content_bundle_service.BatchActivateContentBundlesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if names is not None: + request.names = names + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.batch_activate_content_bundles + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_deactivate_content_bundles( + self, + request: Optional[ + Union[content_bundle_service.BatchDeactivateContentBundlesRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + names: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> content_bundle_service.BatchDeactivateContentBundlesResponse: + r"""Deactivates a list of ``ContentBundle`` objects. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_batch_deactivate_content_bundles(): + # Create a client + client = admanager_v1.ContentBundleServiceClient() + + # Initialize request argument(s) + request = admanager_v1.BatchDeactivateContentBundlesRequest( + parent="parent_value", + names=['names_value1', 'names_value2'], + ) + + # Make the request + response = client.batch_deactivate_content_bundles(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.BatchDeactivateContentBundlesRequest, dict]): + The request object. Request message for ``BatchDeactivateContentBundles`` + method. + parent (str): + Required. The parent resource where ``ContentBundles`` + will be deactivated. Format: ``networks/{network_code}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + names (MutableSequence[str]): + Required. The resource names of the ``ContentBundle``\ s + to deactivate. Format: + ``networks/{network_code}/contentBundles/{content_bundle_id}`` + + This corresponds to the ``names`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.admanager_v1.types.BatchDeactivateContentBundlesResponse: + Response object for BatchDeactivateContentBundles + method. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, names] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, content_bundle_service.BatchDeactivateContentBundlesRequest + ): + request = content_bundle_service.BatchDeactivateContentBundlesRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if names is not None: + request.names = names + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.batch_deactivate_content_bundles + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "ContentBundleServiceClient": return self diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/content_bundle_service/transports/base.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/content_bundle_service/transports/base.py index 5397cbd16b08..9a6966bd4099 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/content_bundle_service/transports/base.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/content_bundle_service/transports/base.py @@ -157,6 +157,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.batch_activate_content_bundles: gapic_v1.method.wrap_method( + self.batch_activate_content_bundles, + default_timeout=None, + client_info=client_info, + ), + self.batch_deactivate_content_bundles: gapic_v1.method.wrap_method( + self.batch_deactivate_content_bundles, + default_timeout=None, + client_info=client_info, + ), self.cancel_operation: gapic_v1.method.wrap_method( self.cancel_operation, default_timeout=None, @@ -202,6 +212,30 @@ def list_content_bundles( ]: raise NotImplementedError() + @property + def batch_activate_content_bundles( + self, + ) -> Callable[ + [content_bundle_service.BatchActivateContentBundlesRequest], + Union[ + content_bundle_service.BatchActivateContentBundlesResponse, + Awaitable[content_bundle_service.BatchActivateContentBundlesResponse], + ], + ]: + raise NotImplementedError() + + @property + def batch_deactivate_content_bundles( + self, + ) -> Callable[ + [content_bundle_service.BatchDeactivateContentBundlesRequest], + Union[ + content_bundle_service.BatchDeactivateContentBundlesResponse, + Awaitable[content_bundle_service.BatchDeactivateContentBundlesResponse], + ], + ]: + raise NotImplementedError() + @property def get_operation( self, diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/content_bundle_service/transports/rest.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/content_bundle_service/transports/rest.py index 41380de85909..ac8e448ffa5c 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/content_bundle_service/transports/rest.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/content_bundle_service/transports/rest.py @@ -75,6 +75,22 @@ class ContentBundleServiceRestInterceptor: .. code-block:: python class MyCustomContentBundleServiceInterceptor(ContentBundleServiceRestInterceptor): + def pre_batch_activate_content_bundles(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_activate_content_bundles(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_batch_deactivate_content_bundles(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_deactivate_content_bundles(self, response): + logging.log(f"Received response: {response}") + return response + def pre_get_content_bundle(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -97,6 +113,110 @@ def post_list_content_bundles(self, response): """ + def pre_batch_activate_content_bundles( + self, + request: content_bundle_service.BatchActivateContentBundlesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + content_bundle_service.BatchActivateContentBundlesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_activate_content_bundles + + Override in a subclass to manipulate the request or metadata + before they are sent to the ContentBundleService server. + """ + return request, metadata + + def post_batch_activate_content_bundles( + self, response: content_bundle_service.BatchActivateContentBundlesResponse + ) -> content_bundle_service.BatchActivateContentBundlesResponse: + """Post-rpc interceptor for batch_activate_content_bundles + + DEPRECATED. Please use the `post_batch_activate_content_bundles_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ContentBundleService server but before + it is returned to user code. This `post_batch_activate_content_bundles` interceptor runs + before the `post_batch_activate_content_bundles_with_metadata` interceptor. + """ + return response + + def post_batch_activate_content_bundles_with_metadata( + self, + response: content_bundle_service.BatchActivateContentBundlesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + content_bundle_service.BatchActivateContentBundlesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for batch_activate_content_bundles + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ContentBundleService server but before it is returned to user code. + + We recommend only using this `post_batch_activate_content_bundles_with_metadata` + interceptor in new development instead of the `post_batch_activate_content_bundles` interceptor. + When both interceptors are used, this `post_batch_activate_content_bundles_with_metadata` interceptor runs after the + `post_batch_activate_content_bundles` interceptor. The (possibly modified) response returned by + `post_batch_activate_content_bundles` will be passed to + `post_batch_activate_content_bundles_with_metadata`. + """ + return response, metadata + + def pre_batch_deactivate_content_bundles( + self, + request: content_bundle_service.BatchDeactivateContentBundlesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + content_bundle_service.BatchDeactivateContentBundlesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_deactivate_content_bundles + + Override in a subclass to manipulate the request or metadata + before they are sent to the ContentBundleService server. + """ + return request, metadata + + def post_batch_deactivate_content_bundles( + self, response: content_bundle_service.BatchDeactivateContentBundlesResponse + ) -> content_bundle_service.BatchDeactivateContentBundlesResponse: + """Post-rpc interceptor for batch_deactivate_content_bundles + + DEPRECATED. Please use the `post_batch_deactivate_content_bundles_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ContentBundleService server but before + it is returned to user code. This `post_batch_deactivate_content_bundles` interceptor runs + before the `post_batch_deactivate_content_bundles_with_metadata` interceptor. + """ + return response + + def post_batch_deactivate_content_bundles_with_metadata( + self, + response: content_bundle_service.BatchDeactivateContentBundlesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + content_bundle_service.BatchDeactivateContentBundlesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for batch_deactivate_content_bundles + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ContentBundleService server but before it is returned to user code. + + We recommend only using this `post_batch_deactivate_content_bundles_with_metadata` + interceptor in new development instead of the `post_batch_deactivate_content_bundles` interceptor. + When both interceptors are used, this `post_batch_deactivate_content_bundles_with_metadata` interceptor runs after the + `post_batch_deactivate_content_bundles` interceptor. The (possibly modified) response returned by + `post_batch_deactivate_content_bundles` will be passed to + `post_batch_deactivate_content_bundles_with_metadata`. + """ + return response, metadata + def pre_get_content_bundle( self, request: content_bundle_service.GetContentBundleRequest, @@ -342,6 +462,330 @@ def __init__( self._interceptor = interceptor or ContentBundleServiceRestInterceptor() self._prep_wrapped_messages(client_info) + class _BatchActivateContentBundles( + _BaseContentBundleServiceRestTransport._BaseBatchActivateContentBundles, + ContentBundleServiceRestStub, + ): + def __hash__(self): + return hash("ContentBundleServiceRestTransport.BatchActivateContentBundles") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: content_bundle_service.BatchActivateContentBundlesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> content_bundle_service.BatchActivateContentBundlesResponse: + r"""Call the batch activate content + bundles method over HTTP. + + Args: + request (~.content_bundle_service.BatchActivateContentBundlesRequest): + The request object. Request message for ``BatchActivateContentBundles`` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.content_bundle_service.BatchActivateContentBundlesResponse: + Response object for ``BatchActivateContentBundles`` + method. + + """ + + http_options = _BaseContentBundleServiceRestTransport._BaseBatchActivateContentBundles._get_http_options() + + request, metadata = self._interceptor.pre_batch_activate_content_bundles( + request, metadata + ) + transcoded_request = _BaseContentBundleServiceRestTransport._BaseBatchActivateContentBundles._get_transcoded_request( + http_options, request + ) + + body = _BaseContentBundleServiceRestTransport._BaseBatchActivateContentBundles._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseContentBundleServiceRestTransport._BaseBatchActivateContentBundles._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.ContentBundleServiceClient.BatchActivateContentBundles", + extra={ + "serviceName": "google.ads.admanager.v1.ContentBundleService", + "rpcName": "BatchActivateContentBundles", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ContentBundleServiceRestTransport._BatchActivateContentBundles._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = content_bundle_service.BatchActivateContentBundlesResponse() + pb_resp = content_bundle_service.BatchActivateContentBundlesResponse.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_activate_content_bundles(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_batch_activate_content_bundles_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = content_bundle_service.BatchActivateContentBundlesResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.ContentBundleServiceClient.batch_activate_content_bundles", + extra={ + "serviceName": "google.ads.admanager.v1.ContentBundleService", + "rpcName": "BatchActivateContentBundles", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _BatchDeactivateContentBundles( + _BaseContentBundleServiceRestTransport._BaseBatchDeactivateContentBundles, + ContentBundleServiceRestStub, + ): + def __hash__(self): + return hash( + "ContentBundleServiceRestTransport.BatchDeactivateContentBundles" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: content_bundle_service.BatchDeactivateContentBundlesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> content_bundle_service.BatchDeactivateContentBundlesResponse: + r"""Call the batch deactivate content + bundles method over HTTP. + + Args: + request (~.content_bundle_service.BatchDeactivateContentBundlesRequest): + The request object. Request message for ``BatchDeactivateContentBundles`` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.content_bundle_service.BatchDeactivateContentBundlesResponse: + Response object for ``BatchDeactivateContentBundles`` + method. + + """ + + http_options = _BaseContentBundleServiceRestTransport._BaseBatchDeactivateContentBundles._get_http_options() + + request, metadata = self._interceptor.pre_batch_deactivate_content_bundles( + request, metadata + ) + transcoded_request = _BaseContentBundleServiceRestTransport._BaseBatchDeactivateContentBundles._get_transcoded_request( + http_options, request + ) + + body = _BaseContentBundleServiceRestTransport._BaseBatchDeactivateContentBundles._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseContentBundleServiceRestTransport._BaseBatchDeactivateContentBundles._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.ContentBundleServiceClient.BatchDeactivateContentBundles", + extra={ + "serviceName": "google.ads.admanager.v1.ContentBundleService", + "rpcName": "BatchDeactivateContentBundles", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ContentBundleServiceRestTransport._BatchDeactivateContentBundles._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = content_bundle_service.BatchDeactivateContentBundlesResponse() + pb_resp = content_bundle_service.BatchDeactivateContentBundlesResponse.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_deactivate_content_bundles(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_batch_deactivate_content_bundles_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = content_bundle_service.BatchDeactivateContentBundlesResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.ContentBundleServiceClient.batch_deactivate_content_bundles", + extra={ + "serviceName": "google.ads.admanager.v1.ContentBundleService", + "rpcName": "BatchDeactivateContentBundles", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _GetContentBundle( _BaseContentBundleServiceRestTransport._BaseGetContentBundle, ContentBundleServiceRestStub, @@ -652,6 +1096,32 @@ def __call__( ) return resp + @property + def batch_activate_content_bundles( + self, + ) -> Callable[ + [content_bundle_service.BatchActivateContentBundlesRequest], + content_bundle_service.BatchActivateContentBundlesResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchActivateContentBundles( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def batch_deactivate_content_bundles( + self, + ) -> Callable[ + [content_bundle_service.BatchDeactivateContentBundlesRequest], + content_bundle_service.BatchDeactivateContentBundlesResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchDeactivateContentBundles( + self._session, self._host, self._interceptor + ) # type: ignore + @property def get_content_bundle( self, diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/content_bundle_service/transports/rest_base.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/content_bundle_service/transports/rest_base.py index fcaabbe29444..d7f69cede10d 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/content_bundle_service/transports/rest_base.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/content_bundle_service/transports/rest_base.py @@ -91,6 +91,124 @@ def __init__( api_audience=api_audience, ) + class _BaseBatchActivateContentBundles: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=networks/*}/contentBundles:batchActivate", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = content_bundle_service.BatchActivateContentBundlesRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseContentBundleServiceRestTransport._BaseBatchActivateContentBundles._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseBatchDeactivateContentBundles: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=networks/*}/contentBundles:batchDeactivate", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = content_bundle_service.BatchDeactivateContentBundlesRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseContentBundleServiceRestTransport._BaseBatchDeactivateContentBundles._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseGetContentBundle: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/content_label_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/content_label_service/client.py index e491766b192f..356557647992 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/content_label_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/content_label_service/client.py @@ -754,7 +754,7 @@ def get_content_label( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> content_label_messages.ContentLabel: - r"""API to retrieve a ``ContentLabel`` object. + r"""Retrieves a ``ContentLabel`` object. .. code-block:: python @@ -861,7 +861,7 @@ def list_content_labels( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListContentLabelsPager: - r"""API to retrieve a list of ``ContentLabel`` objects. + r"""Lists ``ContentLabel`` objects. .. code-block:: python diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/content_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/content_service/client.py index 2710a5a5ddb2..8f8669749ba3 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/content_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/content_service/client.py @@ -61,10 +61,16 @@ _LOGGER = std_logging.getLogger(__name__) +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore from google.longrunning import operations_pb2 # type: ignore from google.ads.admanager_v1.services.content_service import pagers -from google.ads.admanager_v1.types import content_messages, content_service +from google.ads.admanager_v1.types import ( + content_enums, + content_messages, + content_service, +) from .transports.base import DEFAULT_CLIENT_INFO, ContentServiceTransport from .transports.rest import ContentServiceRestTransport @@ -224,6 +230,26 @@ def transport(self) -> ContentServiceTransport: """ return self._transport + @staticmethod + def cms_metadata_value_path( + network_code: str, + cms_metadata_value: str, + ) -> str: + """Returns a fully-qualified cms_metadata_value string.""" + return "networks/{network_code}/cmsMetadataValues/{cms_metadata_value}".format( + network_code=network_code, + cms_metadata_value=cms_metadata_value, + ) + + @staticmethod + def parse_cms_metadata_value_path(path: str) -> Dict[str, str]: + """Parses a cms_metadata_value path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/cmsMetadataValues/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def content_path( network_code: str, @@ -241,6 +267,46 @@ def parse_content_path(path: str) -> Dict[str, str]: m = re.match(r"^networks/(?P.+?)/content/(?P.+?)$", path) return m.groupdict() if m else {} + @staticmethod + def content_bundle_path( + network_code: str, + content_bundle: str, + ) -> str: + """Returns a fully-qualified content_bundle string.""" + return "networks/{network_code}/contentBundles/{content_bundle}".format( + network_code=network_code, + content_bundle=content_bundle, + ) + + @staticmethod + def parse_content_bundle_path(path: str) -> Dict[str, str]: + """Parses a content_bundle path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/contentBundles/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def content_source_path( + network_code: str, + content_source: str, + ) -> str: + """Returns a fully-qualified content_source string.""" + return "networks/{network_code}/contentSources/{content_source}".format( + network_code=network_code, + content_source=content_source, + ) + + @staticmethod + def parse_content_source_path(path: str) -> Dict[str, str]: + """Parses a content_source path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/contentSources/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def network_path( network_code: str, @@ -744,7 +810,7 @@ def get_content( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> content_messages.Content: - r"""API to retrieve a ``Content`` object. + r"""Retrieves a ``Content`` object. .. code-block:: python @@ -849,7 +915,7 @@ def list_content( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListContentPager: - r"""API to retrieve a list of ``Content`` objects. + r"""Lists ``Content`` objects. .. code-block:: python diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/creative_set_service/__init__.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/creative_set_service/__init__.py new file mode 100644 index 000000000000..0b3e2dc653ee --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/creative_set_service/__init__.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +from .client import CreativeSetServiceClient + +__all__ = ("CreativeSetServiceClient",) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/creative_set_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/creative_set_service/client.py new file mode 100644 index 000000000000..5d20cc58810f --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/creative_set_service/client.py @@ -0,0 +1,1387 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +import json +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.ads.admanager_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.ads.admanager_v1.services.creative_set_service import pagers +from google.ads.admanager_v1.types import creative_set_messages, creative_set_service + +from .transports.base import DEFAULT_CLIENT_INFO, CreativeSetServiceTransport +from .transports.rest import CreativeSetServiceRestTransport + + +class CreativeSetServiceClientMeta(type): + """Metaclass for the CreativeSetService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[CreativeSetServiceTransport]] + _transport_registry["rest"] = CreativeSetServiceRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[CreativeSetServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class CreativeSetServiceClient(metaclass=CreativeSetServiceClientMeta): + """Provides methods for handling ``CreativeSet`` objects.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + Optional[str]: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # Could not parse api_endpoint; return as-is. + return api_endpoint + + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "admanager.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "admanager.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CreativeSetServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CreativeSetServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> CreativeSetServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CreativeSetServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def creative_path( + network_code: str, + creative: str, + ) -> str: + """Returns a fully-qualified creative string.""" + return "networks/{network_code}/creatives/{creative}".format( + network_code=network_code, + creative=creative, + ) + + @staticmethod + def parse_creative_path(path: str) -> Dict[str, str]: + """Parses a creative path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/creatives/(?P.+?)$", path + ) + return m.groupdict() if m else {} + + @staticmethod + def creative_set_path( + network_code: str, + creative_set: str, + ) -> str: + """Returns a fully-qualified creative_set string.""" + return "networks/{network_code}/creativeSets/{creative_set}".format( + network_code=network_code, + creative_set=creative_set, + ) + + @staticmethod + def parse_creative_set_path(path: str) -> Dict[str, str]: + """Parses a creative_set path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/creativeSets/(?P.+?)$", path + ) + return m.groupdict() if m else {} + + @staticmethod + def network_path( + network_code: str, + ) -> str: + """Returns a fully-qualified network string.""" + return "networks/{network_code}".format( + network_code=network_code, + ) + + @staticmethod + def parse_network_path(path: str) -> Dict[str, str]: + """Parses a network path into its component segments.""" + m = re.match(r"^networks/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = CreativeSetServiceClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = CreativeSetServiceClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = CreativeSetServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = CreativeSetServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = CreativeSetServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = CreativeSetServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + CreativeSetServiceTransport, + Callable[..., CreativeSetServiceTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the creative set service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,CreativeSetServiceTransport,Callable[..., CreativeSetServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the CreativeSetServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + CreativeSetServiceClient._read_environment_variables() + ) + self._client_cert_source = CreativeSetServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = CreativeSetServiceClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, CreativeSetServiceTransport) + if transport_provided: + # transport is a CreativeSetServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(CreativeSetServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or CreativeSetServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[CreativeSetServiceTransport], + Callable[..., CreativeSetServiceTransport], + ] = ( + CreativeSetServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., CreativeSetServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.ads.admanager_v1.CreativeSetServiceClient`.", + extra={ + "serviceName": "google.ads.admanager.v1.CreativeSetService", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.ads.admanager.v1.CreativeSetService", + "credentialsType": None, + }, + ) + + def get_creative_set( + self, + request: Optional[ + Union[creative_set_service.GetCreativeSetRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> creative_set_messages.CreativeSet: + r"""Retrieves a ``CreativeSet`` object. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_get_creative_set(): + # Create a client + client = admanager_v1.CreativeSetServiceClient() + + # Initialize request argument(s) + request = admanager_v1.GetCreativeSetRequest( + name="name_value", + ) + + # Make the request + response = client.get_creative_set(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.GetCreativeSetRequest, dict]): + The request object. Request object for ``GetCreativeSet`` method. + name (str): + Required. The resource name of the CreativeSet. Format: + ``networks/{network_code}/creativeSets/{creative_set_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.admanager_v1.types.CreativeSet: + A CreativeSet is comprised of a master Creative and its companion + \`Creative`s. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, creative_set_service.GetCreativeSetRequest): + request = creative_set_service.GetCreativeSetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_creative_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_creative_sets( + self, + request: Optional[ + Union[creative_set_service.ListCreativeSetsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListCreativeSetsPager: + r"""Lists ``CreativeSet`` objects. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_list_creative_sets(): + # Create a client + client = admanager_v1.CreativeSetServiceClient() + + # Initialize request argument(s) + request = admanager_v1.ListCreativeSetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_creative_sets(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.ListCreativeSetsRequest, dict]): + The request object. Request object for ``ListCreativeSets`` method. + parent (str): + Required. The parent, which owns this collection of + CreativeSets. Format: ``networks/{network_code}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.admanager_v1.services.creative_set_service.pagers.ListCreativeSetsPager: + Response object for ListCreativeSetsRequest containing matching + CreativeSet objects. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, creative_set_service.ListCreativeSetsRequest): + request = creative_set_service.ListCreativeSetsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_creative_sets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListCreativeSetsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_creative_set( + self, + request: Optional[ + Union[creative_set_service.CreateCreativeSetRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + creative_set: Optional[creative_set_messages.CreativeSet] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> creative_set_messages.CreativeSet: + r"""Creates a ``CreativeSet`` object. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_create_creative_set(): + # Create a client + client = admanager_v1.CreativeSetServiceClient() + + # Initialize request argument(s) + creative_set = admanager_v1.CreativeSet() + creative_set.companion_creatives = ['companion_creatives_value1', 'companion_creatives_value2'] + + request = admanager_v1.CreateCreativeSetRequest( + parent="parent_value", + creative_set=creative_set, + ) + + # Make the request + response = client.create_creative_set(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.CreateCreativeSetRequest, dict]): + The request object. Request object for ``CreateCreativeSet`` method. + parent (str): + Required. The parent resource where this ``CreativeSet`` + will be created. Format: ``networks/{network_code}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + creative_set (google.ads.admanager_v1.types.CreativeSet): + Required. The ``CreativeSet`` to create. + This corresponds to the ``creative_set`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.admanager_v1.types.CreativeSet: + A CreativeSet is comprised of a master Creative and its companion + \`Creative`s. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, creative_set] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, creative_set_service.CreateCreativeSetRequest): + request = creative_set_service.CreateCreativeSetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if creative_set is not None: + request.creative_set = creative_set + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_creative_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_creative_set( + self, + request: Optional[ + Union[creative_set_service.UpdateCreativeSetRequest, dict] + ] = None, + *, + creative_set: Optional[creative_set_messages.CreativeSet] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> creative_set_messages.CreativeSet: + r"""Updates a ``CreativeSet`` object. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_update_creative_set(): + # Create a client + client = admanager_v1.CreativeSetServiceClient() + + # Initialize request argument(s) + creative_set = admanager_v1.CreativeSet() + creative_set.companion_creatives = ['companion_creatives_value1', 'companion_creatives_value2'] + + request = admanager_v1.UpdateCreativeSetRequest( + creative_set=creative_set, + ) + + # Make the request + response = client.update_creative_set(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.UpdateCreativeSetRequest, dict]): + The request object. Request object for ``UpdateCreativeSet`` method. + creative_set (google.ads.admanager_v1.types.CreativeSet): + Required. The ``CreativeSet`` to update. + + The ``CreativeSet``'s ``name`` is used to identify the + ``CreativeSet`` to update. + + This corresponds to the ``creative_set`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to + update. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.admanager_v1.types.CreativeSet: + A CreativeSet is comprised of a master Creative and its companion + \`Creative`s. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [creative_set, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, creative_set_service.UpdateCreativeSetRequest): + request = creative_set_service.UpdateCreativeSetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if creative_set is not None: + request.creative_set = creative_set + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_creative_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("creative_set.name", request.creative_set.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "CreativeSetServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("CreativeSetServiceClient",) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/creative_set_service/pagers.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/creative_set_service/pagers.py new file mode 100644 index 000000000000..f2581020ff2e --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/creative_set_service/pagers.py @@ -0,0 +1,117 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.ads.admanager_v1.types import creative_set_messages, creative_set_service + + +class ListCreativeSetsPager: + """A pager for iterating through ``list_creative_sets`` requests. + + This class thinly wraps an initial + :class:`google.ads.admanager_v1.types.ListCreativeSetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``creative_sets`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListCreativeSets`` requests and continue to iterate + through the ``creative_sets`` field on the + corresponding responses. + + All the usual :class:`google.ads.admanager_v1.types.ListCreativeSetsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., creative_set_service.ListCreativeSetsResponse], + request: creative_set_service.ListCreativeSetsRequest, + response: creative_set_service.ListCreativeSetsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.ads.admanager_v1.types.ListCreativeSetsRequest): + The initial request object. + response (google.ads.admanager_v1.types.ListCreativeSetsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = creative_set_service.ListCreativeSetsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[creative_set_service.ListCreativeSetsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[creative_set_messages.CreativeSet]: + for page in self.pages: + yield from page.creative_sets + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/creative_set_service/transports/README.rst b/packages/google-ads-admanager/google/ads/admanager_v1/services/creative_set_service/transports/README.rst new file mode 100644 index 000000000000..dae581f7a315 --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/creative_set_service/transports/README.rst @@ -0,0 +1,10 @@ + +transport inheritance structure +_______________________________ + +``CreativeSetServiceTransport`` is the ABC for all transports. + +- public child ``CreativeSetServiceGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``). +- public child ``CreativeSetServiceGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``). +- private child ``_BaseCreativeSetServiceRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``). +- public child ``CreativeSetServiceRestTransport`` for sync REST transport with inner classes ``METHOD`` derived from the parent's corresponding ``_BaseMETHOD`` classes (defined in ``rest.py``). diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/creative_set_service/transports/__init__.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/creative_set_service/transports/__init__.py new file mode 100644 index 000000000000..12a45370fc26 --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/creative_set_service/transports/__init__.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import CreativeSetServiceTransport +from .rest import CreativeSetServiceRestInterceptor, CreativeSetServiceRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[CreativeSetServiceTransport]] +_transport_registry["rest"] = CreativeSetServiceRestTransport + +__all__ = ( + "CreativeSetServiceTransport", + "CreativeSetServiceRestTransport", + "CreativeSetServiceRestInterceptor", +) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/creative_set_service/transports/base.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/creative_set_service/transports/base.py new file mode 100644 index 000000000000..9f94c9c62da0 --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/creative_set_service/transports/base.py @@ -0,0 +1,259 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.ads.admanager_v1 import gapic_version as package_version +from google.ads.admanager_v1.types import creative_set_messages, creative_set_service + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class CreativeSetServiceTransport(abc.ABC): + """Abstract transport class for CreativeSetService.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/admanager", + "https://www.googleapis.com/auth/admanager.readonly", + ) + + DEFAULT_HOST: str = "admanager.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'admanager.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_creative_set: gapic_v1.method.wrap_method( + self.get_creative_set, + default_timeout=None, + client_info=client_info, + ), + self.list_creative_sets: gapic_v1.method.wrap_method( + self.list_creative_sets, + default_timeout=None, + client_info=client_info, + ), + self.create_creative_set: gapic_v1.method.wrap_method( + self.create_creative_set, + default_timeout=None, + client_info=client_info, + ), + self.update_creative_set: gapic_v1.method.wrap_method( + self.update_creative_set, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def get_creative_set( + self, + ) -> Callable[ + [creative_set_service.GetCreativeSetRequest], + Union[ + creative_set_messages.CreativeSet, + Awaitable[creative_set_messages.CreativeSet], + ], + ]: + raise NotImplementedError() + + @property + def list_creative_sets( + self, + ) -> Callable[ + [creative_set_service.ListCreativeSetsRequest], + Union[ + creative_set_service.ListCreativeSetsResponse, + Awaitable[creative_set_service.ListCreativeSetsResponse], + ], + ]: + raise NotImplementedError() + + @property + def create_creative_set( + self, + ) -> Callable[ + [creative_set_service.CreateCreativeSetRequest], + Union[ + creative_set_messages.CreativeSet, + Awaitable[creative_set_messages.CreativeSet], + ], + ]: + raise NotImplementedError() + + @property + def update_creative_set( + self, + ) -> Callable[ + [creative_set_service.UpdateCreativeSetRequest], + Union[ + creative_set_messages.CreativeSet, + Awaitable[creative_set_messages.CreativeSet], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("CreativeSetServiceTransport",) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/creative_set_service/transports/rest.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/creative_set_service/transports/rest.py new file mode 100644 index 000000000000..8e2f7dcfcf1f --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/creative_set_service/transports/rest.py @@ -0,0 +1,1371 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +import dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.ads.admanager_v1.types import creative_set_messages, creative_set_service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseCreativeSetServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class CreativeSetServiceRestInterceptor: + """Interceptor for CreativeSetService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the CreativeSetServiceRestTransport. + + .. code-block:: python + class MyCustomCreativeSetServiceInterceptor(CreativeSetServiceRestInterceptor): + def pre_create_creative_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_creative_set(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_creative_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_creative_set(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_creative_sets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_creative_sets(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_creative_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_creative_set(self, response): + logging.log(f"Received response: {response}") + return response + + transport = CreativeSetServiceRestTransport(interceptor=MyCustomCreativeSetServiceInterceptor()) + client = CreativeSetServiceClient(transport=transport) + + + """ + + def pre_create_creative_set( + self, + request: creative_set_service.CreateCreativeSetRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + creative_set_service.CreateCreativeSetRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_creative_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the CreativeSetService server. + """ + return request, metadata + + def post_create_creative_set( + self, response: creative_set_messages.CreativeSet + ) -> creative_set_messages.CreativeSet: + """Post-rpc interceptor for create_creative_set + + DEPRECATED. Please use the `post_create_creative_set_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the CreativeSetService server but before + it is returned to user code. This `post_create_creative_set` interceptor runs + before the `post_create_creative_set_with_metadata` interceptor. + """ + return response + + def post_create_creative_set_with_metadata( + self, + response: creative_set_messages.CreativeSet, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + creative_set_messages.CreativeSet, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for create_creative_set + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the CreativeSetService server but before it is returned to user code. + + We recommend only using this `post_create_creative_set_with_metadata` + interceptor in new development instead of the `post_create_creative_set` interceptor. + When both interceptors are used, this `post_create_creative_set_with_metadata` interceptor runs after the + `post_create_creative_set` interceptor. The (possibly modified) response returned by + `post_create_creative_set` will be passed to + `post_create_creative_set_with_metadata`. + """ + return response, metadata + + def pre_get_creative_set( + self, + request: creative_set_service.GetCreativeSetRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + creative_set_service.GetCreativeSetRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_creative_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the CreativeSetService server. + """ + return request, metadata + + def post_get_creative_set( + self, response: creative_set_messages.CreativeSet + ) -> creative_set_messages.CreativeSet: + """Post-rpc interceptor for get_creative_set + + DEPRECATED. Please use the `post_get_creative_set_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the CreativeSetService server but before + it is returned to user code. This `post_get_creative_set` interceptor runs + before the `post_get_creative_set_with_metadata` interceptor. + """ + return response + + def post_get_creative_set_with_metadata( + self, + response: creative_set_messages.CreativeSet, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + creative_set_messages.CreativeSet, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for get_creative_set + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the CreativeSetService server but before it is returned to user code. + + We recommend only using this `post_get_creative_set_with_metadata` + interceptor in new development instead of the `post_get_creative_set` interceptor. + When both interceptors are used, this `post_get_creative_set_with_metadata` interceptor runs after the + `post_get_creative_set` interceptor. The (possibly modified) response returned by + `post_get_creative_set` will be passed to + `post_get_creative_set_with_metadata`. + """ + return response, metadata + + def pre_list_creative_sets( + self, + request: creative_set_service.ListCreativeSetsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + creative_set_service.ListCreativeSetsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_creative_sets + + Override in a subclass to manipulate the request or metadata + before they are sent to the CreativeSetService server. + """ + return request, metadata + + def post_list_creative_sets( + self, response: creative_set_service.ListCreativeSetsResponse + ) -> creative_set_service.ListCreativeSetsResponse: + """Post-rpc interceptor for list_creative_sets + + DEPRECATED. Please use the `post_list_creative_sets_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the CreativeSetService server but before + it is returned to user code. This `post_list_creative_sets` interceptor runs + before the `post_list_creative_sets_with_metadata` interceptor. + """ + return response + + def post_list_creative_sets_with_metadata( + self, + response: creative_set_service.ListCreativeSetsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + creative_set_service.ListCreativeSetsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_creative_sets + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the CreativeSetService server but before it is returned to user code. + + We recommend only using this `post_list_creative_sets_with_metadata` + interceptor in new development instead of the `post_list_creative_sets` interceptor. + When both interceptors are used, this `post_list_creative_sets_with_metadata` interceptor runs after the + `post_list_creative_sets` interceptor. The (possibly modified) response returned by + `post_list_creative_sets` will be passed to + `post_list_creative_sets_with_metadata`. + """ + return response, metadata + + def pre_update_creative_set( + self, + request: creative_set_service.UpdateCreativeSetRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + creative_set_service.UpdateCreativeSetRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_creative_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the CreativeSetService server. + """ + return request, metadata + + def post_update_creative_set( + self, response: creative_set_messages.CreativeSet + ) -> creative_set_messages.CreativeSet: + """Post-rpc interceptor for update_creative_set + + DEPRECATED. Please use the `post_update_creative_set_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the CreativeSetService server but before + it is returned to user code. This `post_update_creative_set` interceptor runs + before the `post_update_creative_set_with_metadata` interceptor. + """ + return response + + def post_update_creative_set_with_metadata( + self, + response: creative_set_messages.CreativeSet, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + creative_set_messages.CreativeSet, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for update_creative_set + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the CreativeSetService server but before it is returned to user code. + + We recommend only using this `post_update_creative_set_with_metadata` + interceptor in new development instead of the `post_update_creative_set` interceptor. + When both interceptors are used, this `post_update_creative_set_with_metadata` interceptor runs after the + `post_update_creative_set` interceptor. The (possibly modified) response returned by + `post_update_creative_set` will be passed to + `post_update_creative_set_with_metadata`. + """ + return response, metadata + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the CreativeSetService server. + """ + return request, metadata + + def post_cancel_operation(self, response: None) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the CreativeSetService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the CreativeSetService server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the CreativeSetService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class CreativeSetServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: CreativeSetServiceRestInterceptor + + +class CreativeSetServiceRestTransport(_BaseCreativeSetServiceRestTransport): + """REST backend synchronous transport for CreativeSetService. + + Provides methods for handling ``CreativeSet`` objects. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "admanager.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[CreativeSetServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'admanager.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[CreativeSetServiceRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or CreativeSetServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateCreativeSet( + _BaseCreativeSetServiceRestTransport._BaseCreateCreativeSet, + CreativeSetServiceRestStub, + ): + def __hash__(self): + return hash("CreativeSetServiceRestTransport.CreateCreativeSet") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: creative_set_service.CreateCreativeSetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> creative_set_messages.CreativeSet: + r"""Call the create creative set method over HTTP. + + Args: + request (~.creative_set_service.CreateCreativeSetRequest): + The request object. Request object for ``CreateCreativeSet`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.creative_set_messages.CreativeSet: + A ``CreativeSet`` is comprised of a master ``Creative`` + and its companion ``Creative``\ s. + + """ + + http_options = _BaseCreativeSetServiceRestTransport._BaseCreateCreativeSet._get_http_options() + + request, metadata = self._interceptor.pre_create_creative_set( + request, metadata + ) + transcoded_request = _BaseCreativeSetServiceRestTransport._BaseCreateCreativeSet._get_transcoded_request( + http_options, request + ) + + body = _BaseCreativeSetServiceRestTransport._BaseCreateCreativeSet._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseCreativeSetServiceRestTransport._BaseCreateCreativeSet._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.CreativeSetServiceClient.CreateCreativeSet", + extra={ + "serviceName": "google.ads.admanager.v1.CreativeSetService", + "rpcName": "CreateCreativeSet", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = CreativeSetServiceRestTransport._CreateCreativeSet._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = creative_set_messages.CreativeSet() + pb_resp = creative_set_messages.CreativeSet.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_creative_set(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_creative_set_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = creative_set_messages.CreativeSet.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.CreativeSetServiceClient.create_creative_set", + extra={ + "serviceName": "google.ads.admanager.v1.CreativeSetService", + "rpcName": "CreateCreativeSet", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetCreativeSet( + _BaseCreativeSetServiceRestTransport._BaseGetCreativeSet, + CreativeSetServiceRestStub, + ): + def __hash__(self): + return hash("CreativeSetServiceRestTransport.GetCreativeSet") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: creative_set_service.GetCreativeSetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> creative_set_messages.CreativeSet: + r"""Call the get creative set method over HTTP. + + Args: + request (~.creative_set_service.GetCreativeSetRequest): + The request object. Request object for ``GetCreativeSet`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.creative_set_messages.CreativeSet: + A ``CreativeSet`` is comprised of a master ``Creative`` + and its companion ``Creative``\ s. + + """ + + http_options = _BaseCreativeSetServiceRestTransport._BaseGetCreativeSet._get_http_options() + + request, metadata = self._interceptor.pre_get_creative_set( + request, metadata + ) + transcoded_request = _BaseCreativeSetServiceRestTransport._BaseGetCreativeSet._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseCreativeSetServiceRestTransport._BaseGetCreativeSet._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.CreativeSetServiceClient.GetCreativeSet", + extra={ + "serviceName": "google.ads.admanager.v1.CreativeSetService", + "rpcName": "GetCreativeSet", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = CreativeSetServiceRestTransport._GetCreativeSet._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = creative_set_messages.CreativeSet() + pb_resp = creative_set_messages.CreativeSet.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_creative_set(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_creative_set_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = creative_set_messages.CreativeSet.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.CreativeSetServiceClient.get_creative_set", + extra={ + "serviceName": "google.ads.admanager.v1.CreativeSetService", + "rpcName": "GetCreativeSet", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListCreativeSets( + _BaseCreativeSetServiceRestTransport._BaseListCreativeSets, + CreativeSetServiceRestStub, + ): + def __hash__(self): + return hash("CreativeSetServiceRestTransport.ListCreativeSets") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: creative_set_service.ListCreativeSetsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> creative_set_service.ListCreativeSetsResponse: + r"""Call the list creative sets method over HTTP. + + Args: + request (~.creative_set_service.ListCreativeSetsRequest): + The request object. Request object for ``ListCreativeSets`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.creative_set_service.ListCreativeSetsResponse: + Response object for ``ListCreativeSetsRequest`` + containing matching ``CreativeSet`` objects. + + """ + + http_options = _BaseCreativeSetServiceRestTransport._BaseListCreativeSets._get_http_options() + + request, metadata = self._interceptor.pre_list_creative_sets( + request, metadata + ) + transcoded_request = _BaseCreativeSetServiceRestTransport._BaseListCreativeSets._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseCreativeSetServiceRestTransport._BaseListCreativeSets._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.CreativeSetServiceClient.ListCreativeSets", + extra={ + "serviceName": "google.ads.admanager.v1.CreativeSetService", + "rpcName": "ListCreativeSets", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = CreativeSetServiceRestTransport._ListCreativeSets._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = creative_set_service.ListCreativeSetsResponse() + pb_resp = creative_set_service.ListCreativeSetsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_creative_sets(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_creative_sets_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + creative_set_service.ListCreativeSetsResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.CreativeSetServiceClient.list_creative_sets", + extra={ + "serviceName": "google.ads.admanager.v1.CreativeSetService", + "rpcName": "ListCreativeSets", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateCreativeSet( + _BaseCreativeSetServiceRestTransport._BaseUpdateCreativeSet, + CreativeSetServiceRestStub, + ): + def __hash__(self): + return hash("CreativeSetServiceRestTransport.UpdateCreativeSet") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: creative_set_service.UpdateCreativeSetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> creative_set_messages.CreativeSet: + r"""Call the update creative set method over HTTP. + + Args: + request (~.creative_set_service.UpdateCreativeSetRequest): + The request object. Request object for ``UpdateCreativeSet`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.creative_set_messages.CreativeSet: + A ``CreativeSet`` is comprised of a master ``Creative`` + and its companion ``Creative``\ s. + + """ + + http_options = _BaseCreativeSetServiceRestTransport._BaseUpdateCreativeSet._get_http_options() + + request, metadata = self._interceptor.pre_update_creative_set( + request, metadata + ) + transcoded_request = _BaseCreativeSetServiceRestTransport._BaseUpdateCreativeSet._get_transcoded_request( + http_options, request + ) + + body = _BaseCreativeSetServiceRestTransport._BaseUpdateCreativeSet._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseCreativeSetServiceRestTransport._BaseUpdateCreativeSet._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.CreativeSetServiceClient.UpdateCreativeSet", + extra={ + "serviceName": "google.ads.admanager.v1.CreativeSetService", + "rpcName": "UpdateCreativeSet", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = CreativeSetServiceRestTransport._UpdateCreativeSet._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = creative_set_messages.CreativeSet() + pb_resp = creative_set_messages.CreativeSet.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_creative_set(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_creative_set_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = creative_set_messages.CreativeSet.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.CreativeSetServiceClient.update_creative_set", + extra={ + "serviceName": "google.ads.admanager.v1.CreativeSetService", + "rpcName": "UpdateCreativeSet", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_creative_set( + self, + ) -> Callable[ + [creative_set_service.CreateCreativeSetRequest], + creative_set_messages.CreativeSet, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateCreativeSet(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_creative_set( + self, + ) -> Callable[ + [creative_set_service.GetCreativeSetRequest], creative_set_messages.CreativeSet + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetCreativeSet(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_creative_sets( + self, + ) -> Callable[ + [creative_set_service.ListCreativeSetsRequest], + creative_set_service.ListCreativeSetsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListCreativeSets(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_creative_set( + self, + ) -> Callable[ + [creative_set_service.UpdateCreativeSetRequest], + creative_set_messages.CreativeSet, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateCreativeSet(self._session, self._host, self._interceptor) # type: ignore + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation( + _BaseCreativeSetServiceRestTransport._BaseCancelOperation, + CreativeSetServiceRestStub, + ): + def __hash__(self): + return hash("CreativeSetServiceRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseCreativeSetServiceRestTransport._BaseCancelOperation._get_http_options() + + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request = _BaseCreativeSetServiceRestTransport._BaseCancelOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseCreativeSetServiceRestTransport._BaseCancelOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.CreativeSetServiceClient.CancelOperation", + extra={ + "serviceName": "google.ads.admanager.v1.CreativeSetService", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = CreativeSetServiceRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation( + _BaseCreativeSetServiceRestTransport._BaseGetOperation, + CreativeSetServiceRestStub, + ): + def __hash__(self): + return hash("CreativeSetServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = _BaseCreativeSetServiceRestTransport._BaseGetOperation._get_http_options() + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseCreativeSetServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseCreativeSetServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.CreativeSetServiceClient.GetOperation", + extra={ + "serviceName": "google.ads.admanager.v1.CreativeSetService", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = CreativeSetServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.CreativeSetServiceAsyncClient.GetOperation", + extra={ + "serviceName": "google.ads.admanager.v1.CreativeSetService", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("CreativeSetServiceRestTransport",) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/creative_set_service/transports/rest_base.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/creative_set_service/transports/rest_base.py new file mode 100644 index 000000000000..024d71c5ff2f --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/creative_set_service/transports/rest_base.py @@ -0,0 +1,350 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.ads.admanager_v1.types import creative_set_messages, creative_set_service + +from .base import DEFAULT_CLIENT_INFO, CreativeSetServiceTransport + + +class _BaseCreativeSetServiceRestTransport(CreativeSetServiceTransport): + """Base REST backend transport for CreativeSetService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "admanager.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'admanager.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseCreateCreativeSet: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=networks/*}/creativeSets", + "body": "creative_set", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = creative_set_service.CreateCreativeSetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCreativeSetServiceRestTransport._BaseCreateCreativeSet._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetCreativeSet: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=networks/*/creativeSets/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = creative_set_service.GetCreativeSetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCreativeSetServiceRestTransport._BaseGetCreativeSet._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListCreativeSets: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=networks/*}/creativeSets", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = creative_set_service.ListCreativeSetsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCreativeSetServiceRestTransport._BaseListCreativeSets._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateCreativeSet: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{creative_set.name=networks/*/creativeSets/*}", + "body": "creative_set", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = creative_set_service.UpdateCreativeSetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCreativeSetServiceRestTransport._BaseUpdateCreativeSet._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=networks/*/operations/reports/runs/*}:cancel", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=networks/*/operations/reports/runs/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseCreativeSetServiceRestTransport",) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/creative_template_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/creative_template_service/client.py index 9524a1df5f2b..39a60af3de2e 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/creative_template_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/creative_template_service/client.py @@ -762,7 +762,7 @@ def get_creative_template( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> creative_template_messages.CreativeTemplate: - r"""API to retrieve a ``CreativeTemplate`` object. + r"""Retrieves a ``CreativeTemplate`` object. .. code-block:: python @@ -874,7 +874,7 @@ def list_creative_templates( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListCreativeTemplatesPager: - r"""API to retrieve a list of ``CreativeTemplate`` objects. + r"""Lists ``CreativeTemplate`` objects. .. code-block:: python diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/custom_field_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/custom_field_service/client.py index a82aaad5cc22..93bf6b3426a1 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/custom_field_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/custom_field_service/client.py @@ -758,7 +758,7 @@ def get_custom_field( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> custom_field_messages.CustomField: - r"""API to retrieve a ``CustomField`` object. + r"""Retrieves a ``CustomField`` object. .. code-block:: python @@ -867,7 +867,7 @@ def list_custom_fields( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListCustomFieldsPager: - r"""API to retrieve a list of ``CustomField`` objects. + r"""Lists ``CustomField`` objects. .. code-block:: python @@ -992,7 +992,7 @@ def create_custom_field( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> custom_field_messages.CustomField: - r"""API to create a ``CustomField`` object. + r"""Creates a ``CustomField`` object. .. code-block:: python @@ -1111,7 +1111,7 @@ def batch_create_custom_fields( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> custom_field_service.BatchCreateCustomFieldsResponse: - r"""API to batch create ``CustomField`` objects. + r"""Creates ``CustomField`` objects. .. code-block:: python @@ -1236,7 +1236,7 @@ def update_custom_field( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> custom_field_messages.CustomField: - r"""API to update a ``CustomField`` object. + r"""Updates a ``CustomField`` object. .. code-block:: python @@ -1360,7 +1360,7 @@ def batch_update_custom_fields( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> custom_field_service.BatchUpdateCustomFieldsResponse: - r"""API to batch update ``CustomField`` objects. + r"""Batch updates ``CustomField`` objects. .. code-block:: python diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/custom_targeting_key_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/custom_targeting_key_service/client.py index bf368f61e6d9..f5814af67441 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/custom_targeting_key_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/custom_targeting_key_service/client.py @@ -765,7 +765,7 @@ def get_custom_targeting_key( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> custom_targeting_key_messages.CustomTargetingKey: - r"""API to retrieve a ``CustomTargetingKey`` object. + r"""Retrieves a ``CustomTargetingKey`` object. .. code-block:: python @@ -875,7 +875,7 @@ def list_custom_targeting_keys( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListCustomTargetingKeysPager: - r"""API to retrieve a list of ``CustomTargetingKey`` objects. + r"""Lists ``CustomTargetingKey`` objects. .. code-block:: python @@ -1008,7 +1008,7 @@ def create_custom_targeting_key( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> custom_targeting_key_messages.CustomTargetingKey: - r"""API to create a ``CustomTargetingKey`` object. + r"""Creates a ``CustomTargetingKey`` object. .. code-block:: python @@ -1136,7 +1136,7 @@ def batch_create_custom_targeting_keys( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> custom_targeting_key_service.BatchCreateCustomTargetingKeysResponse: - r"""API to batch create ``CustomTargetingKey`` objects. + r"""Creates ``CustomTargetingKey`` objects. .. code-block:: python @@ -1272,7 +1272,7 @@ def update_custom_targeting_key( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> custom_targeting_key_messages.CustomTargetingKey: - r"""API to update a ``CustomTargetingKey`` object. + r"""Updates a ``CustomTargetingKey`` object. .. code-block:: python @@ -1404,7 +1404,7 @@ def batch_update_custom_targeting_keys( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> custom_targeting_key_service.BatchUpdateCustomTargetingKeysResponse: - r"""API to batch update ``CustomTargetingKey`` objects. + r"""Batch updates ``CustomTargetingKey`` objects. .. code-block:: python @@ -1537,7 +1537,7 @@ def batch_activate_custom_targeting_keys( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> custom_targeting_key_service.BatchActivateCustomTargetingKeysResponse: - r"""API to batch activate ``CustomTargetingKey`` objects. + r"""Batch activates ``CustomTargetingKey`` objects. .. code-block:: python diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/custom_targeting_value_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/custom_targeting_value_service/client.py index 7a13b4f955ad..ffc2704d66f3 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/custom_targeting_value_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/custom_targeting_value_service/client.py @@ -61,6 +61,7 @@ _LOGGER = std_logging.getLogger(__name__) +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore from google.longrunning import operations_pb2 # type: ignore from google.ads.admanager_v1.services.custom_targeting_value_service import pagers @@ -788,7 +789,7 @@ def get_custom_targeting_value( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> custom_targeting_value_messages.CustomTargetingValue: - r"""API to retrieve a ``CustomTargetingValue`` object. + r"""Retrieves a ``CustomTargetingValue`` object. .. code-block:: python @@ -902,7 +903,7 @@ def list_custom_targeting_values( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListCustomTargetingValuesPager: - r"""API to retrieve a list of ``CustomTargetingValue`` objects. + r"""Lists ``CustomTargetingValue`` objects. .. code-block:: python @@ -1022,6 +1023,823 @@ def sample_list_custom_targeting_values(): # Done; return the response. return response + def create_custom_targeting_value( + self, + request: Optional[ + Union[ + custom_targeting_value_service.CreateCustomTargetingValueRequest, dict + ] + ] = None, + *, + parent: Optional[str] = None, + custom_targeting_value: Optional[ + custom_targeting_value_messages.CustomTargetingValue + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> custom_targeting_value_messages.CustomTargetingValue: + r"""Creates a ``CustomTargetingValue`` object. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_create_custom_targeting_value(): + # Create a client + client = admanager_v1.CustomTargetingValueServiceClient() + + # Initialize request argument(s) + request = admanager_v1.CreateCustomTargetingValueRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_custom_targeting_value(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.CreateCustomTargetingValueRequest, dict]): + The request object. Request object for ``CreateCustomTargetingValue`` + method. + parent (str): + Required. The parent, which owns this collection of + CustomTargetingValues. Format: + ``networks/{network_code}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + custom_targeting_value (google.ads.admanager_v1.types.CustomTargetingValue): + Required. The ``CustomTargetingValue`` to create. + This corresponds to the ``custom_targeting_value`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.admanager_v1.types.CustomTargetingValue: + The CustomTargetingValue resource. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, custom_targeting_value] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, custom_targeting_value_service.CreateCustomTargetingValueRequest + ): + request = custom_targeting_value_service.CreateCustomTargetingValueRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if custom_targeting_value is not None: + request.custom_targeting_value = custom_targeting_value + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.create_custom_targeting_value + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_create_custom_targeting_values( + self, + request: Optional[ + Union[ + custom_targeting_value_service.BatchCreateCustomTargetingValuesRequest, + dict, + ] + ] = None, + *, + parent: Optional[str] = None, + requests: Optional[ + MutableSequence[ + custom_targeting_value_service.CreateCustomTargetingValueRequest + ] + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> custom_targeting_value_service.BatchCreateCustomTargetingValuesResponse: + r"""Creates ``CustomTargetingValue`` objects. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_batch_create_custom_targeting_values(): + # Create a client + client = admanager_v1.CustomTargetingValueServiceClient() + + # Initialize request argument(s) + requests = admanager_v1.CreateCustomTargetingValueRequest() + requests.parent = "parent_value" + + request = admanager_v1.BatchCreateCustomTargetingValuesRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = client.batch_create_custom_targeting_values(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.BatchCreateCustomTargetingValuesRequest, dict]): + The request object. Request object for ``BatchCreateCustomTargetingValues`` + method. + parent (str): + Required. The parent, which owns this collection of + CustomTargetingValues. Format: + ``networks/{network_code}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + requests (MutableSequence[google.ads.admanager_v1.types.CreateCustomTargetingValueRequest]): + Required. The ``CustomTargetingValue`` objects to + create. A maximum of 100 objects can be created in a + batch. + + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.admanager_v1.types.BatchCreateCustomTargetingValuesResponse: + Response object for BatchCreateCustomTargetingValues + method. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, requests] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + custom_targeting_value_service.BatchCreateCustomTargetingValuesRequest, + ): + request = ( + custom_targeting_value_service.BatchCreateCustomTargetingValuesRequest( + request + ) + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.batch_create_custom_targeting_values + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_custom_targeting_value( + self, + request: Optional[ + Union[ + custom_targeting_value_service.UpdateCustomTargetingValueRequest, dict + ] + ] = None, + *, + custom_targeting_value: Optional[ + custom_targeting_value_messages.CustomTargetingValue + ] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> custom_targeting_value_messages.CustomTargetingValue: + r"""Updates a ``CustomTargetingValue`` object. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_update_custom_targeting_value(): + # Create a client + client = admanager_v1.CustomTargetingValueServiceClient() + + # Initialize request argument(s) + request = admanager_v1.UpdateCustomTargetingValueRequest( + ) + + # Make the request + response = client.update_custom_targeting_value(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.UpdateCustomTargetingValueRequest, dict]): + The request object. Request object for ``UpdateCustomTargetingValue`` + method. + custom_targeting_value (google.ads.admanager_v1.types.CustomTargetingValue): + Required. The ``CustomTargetingValue`` to update. + + The ``CustomTargetingValue``'s ``name`` is used to + identify the ``CustomTargetingValue`` to update. + + This corresponds to the ``custom_targeting_value`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to + update. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.admanager_v1.types.CustomTargetingValue: + The CustomTargetingValue resource. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [custom_targeting_value, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, custom_targeting_value_service.UpdateCustomTargetingValueRequest + ): + request = custom_targeting_value_service.UpdateCustomTargetingValueRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if custom_targeting_value is not None: + request.custom_targeting_value = custom_targeting_value + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.update_custom_targeting_value + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("custom_targeting_value.name", request.custom_targeting_value.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_update_custom_targeting_values( + self, + request: Optional[ + Union[ + custom_targeting_value_service.BatchUpdateCustomTargetingValuesRequest, + dict, + ] + ] = None, + *, + parent: Optional[str] = None, + requests: Optional[ + MutableSequence[ + custom_targeting_value_service.UpdateCustomTargetingValueRequest + ] + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> custom_targeting_value_service.BatchUpdateCustomTargetingValuesResponse: + r"""Batch updates ``CustomTargetingValue`` objects. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_batch_update_custom_targeting_values(): + # Create a client + client = admanager_v1.CustomTargetingValueServiceClient() + + # Initialize request argument(s) + request = admanager_v1.BatchUpdateCustomTargetingValuesRequest( + parent="parent_value", + ) + + # Make the request + response = client.batch_update_custom_targeting_values(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.BatchUpdateCustomTargetingValuesRequest, dict]): + The request object. Request object for ``BatchUpdateCustomTargetingValues`` + method. + parent (str): + Required. The parent, which owns this collection of + CustomTargetingValues. Format: + ``networks/{network_code}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + requests (MutableSequence[google.ads.admanager_v1.types.UpdateCustomTargetingValueRequest]): + Required. The ``CustomTargetingValue`` objects to + update. A maximum of 100 objects can be updated in a + batch. + + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.admanager_v1.types.BatchUpdateCustomTargetingValuesResponse: + Response object for BatchUpdateCustomTargetingValues + method. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, requests] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + custom_targeting_value_service.BatchUpdateCustomTargetingValuesRequest, + ): + request = ( + custom_targeting_value_service.BatchUpdateCustomTargetingValuesRequest( + request + ) + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.batch_update_custom_targeting_values + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_activate_custom_targeting_values( + self, + request: Optional[ + Union[ + custom_targeting_value_service.BatchActivateCustomTargetingValuesRequest, + dict, + ] + ] = None, + *, + parent: Optional[str] = None, + requests: Optional[ + MutableSequence[ + custom_targeting_value_service.ActivateCustomTargetingValueRequest + ] + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> custom_targeting_value_service.BatchActivateCustomTargetingValuesResponse: + r"""Batch activates ``CustomTargetingValue`` objects. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_batch_activate_custom_targeting_values(): + # Create a client + client = admanager_v1.CustomTargetingValueServiceClient() + + # Initialize request argument(s) + requests = admanager_v1.ActivateCustomTargetingValueRequest() + requests.name = "name_value" + + request = admanager_v1.BatchActivateCustomTargetingValuesRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = client.batch_activate_custom_targeting_values(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.BatchActivateCustomTargetingValuesRequest, dict]): + The request object. Request object for + ``BatchActivateCustomTargetingValues`` method. + parent (str): + Required. The parent, which owns this collection of + CustomTargetingValues. Format: + ``networks/{network_code}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + requests (MutableSequence[google.ads.admanager_v1.types.ActivateCustomTargetingValueRequest]): + Required. The ``CustomTargetingValue`` objects to + activate. A maximum of 100 objects can be activated in a + batch. + + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.admanager_v1.types.BatchActivateCustomTargetingValuesResponse: + Response object for BatchActivateCustomTargetingValues + method. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, requests] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + custom_targeting_value_service.BatchActivateCustomTargetingValuesRequest, + ): + request = custom_targeting_value_service.BatchActivateCustomTargetingValuesRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.batch_activate_custom_targeting_values + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_deactivate_custom_targeting_values( + self, + request: Optional[ + Union[ + custom_targeting_value_service.BatchDeactivateCustomTargetingValuesRequest, + dict, + ] + ] = None, + *, + parent: Optional[str] = None, + requests: Optional[ + MutableSequence[ + custom_targeting_value_service.DeactivateCustomTargetingValueRequest + ] + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> custom_targeting_value_service.BatchDeactivateCustomTargetingValuesResponse: + r"""Deactivates a list of ``CustomTargetingValue`` objects. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_batch_deactivate_custom_targeting_values(): + # Create a client + client = admanager_v1.CustomTargetingValueServiceClient() + + # Initialize request argument(s) + requests = admanager_v1.DeactivateCustomTargetingValueRequest() + requests.name = "name_value" + + request = admanager_v1.BatchDeactivateCustomTargetingValuesRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = client.batch_deactivate_custom_targeting_values(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.BatchDeactivateCustomTargetingValuesRequest, dict]): + The request object. Request message for + ``BatchDeactivateCustomTargetingValues`` method. + parent (str): + Required. The parent, which owns this collection of + CustomTargetingValues. Format: + ``networks/{network_code}/`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + requests (MutableSequence[google.ads.admanager_v1.types.DeactivateCustomTargetingValueRequest]): + Required. The ``CustomTargetingValue`` objects to + deactivate. + + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.admanager_v1.types.BatchDeactivateCustomTargetingValuesResponse: + Response object for BatchDeactivateCustomTargetingValues + method. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, requests] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + custom_targeting_value_service.BatchDeactivateCustomTargetingValuesRequest, + ): + request = custom_targeting_value_service.BatchDeactivateCustomTargetingValuesRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.batch_deactivate_custom_targeting_values + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "CustomTargetingValueServiceClient": return self diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/custom_targeting_value_service/transports/base.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/custom_targeting_value_service/transports/base.py index 91dda629415e..17fa2879a745 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/custom_targeting_value_service/transports/base.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/custom_targeting_value_service/transports/base.py @@ -157,6 +157,36 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.create_custom_targeting_value: gapic_v1.method.wrap_method( + self.create_custom_targeting_value, + default_timeout=None, + client_info=client_info, + ), + self.batch_create_custom_targeting_values: gapic_v1.method.wrap_method( + self.batch_create_custom_targeting_values, + default_timeout=None, + client_info=client_info, + ), + self.update_custom_targeting_value: gapic_v1.method.wrap_method( + self.update_custom_targeting_value, + default_timeout=None, + client_info=client_info, + ), + self.batch_update_custom_targeting_values: gapic_v1.method.wrap_method( + self.batch_update_custom_targeting_values, + default_timeout=None, + client_info=client_info, + ), + self.batch_activate_custom_targeting_values: gapic_v1.method.wrap_method( + self.batch_activate_custom_targeting_values, + default_timeout=None, + client_info=client_info, + ), + self.batch_deactivate_custom_targeting_values: gapic_v1.method.wrap_method( + self.batch_deactivate_custom_targeting_values, + default_timeout=None, + client_info=client_info, + ), self.cancel_operation: gapic_v1.method.wrap_method( self.cancel_operation, default_timeout=None, @@ -202,6 +232,86 @@ def list_custom_targeting_values( ]: raise NotImplementedError() + @property + def create_custom_targeting_value( + self, + ) -> Callable[ + [custom_targeting_value_service.CreateCustomTargetingValueRequest], + Union[ + custom_targeting_value_messages.CustomTargetingValue, + Awaitable[custom_targeting_value_messages.CustomTargetingValue], + ], + ]: + raise NotImplementedError() + + @property + def batch_create_custom_targeting_values( + self, + ) -> Callable[ + [custom_targeting_value_service.BatchCreateCustomTargetingValuesRequest], + Union[ + custom_targeting_value_service.BatchCreateCustomTargetingValuesResponse, + Awaitable[ + custom_targeting_value_service.BatchCreateCustomTargetingValuesResponse + ], + ], + ]: + raise NotImplementedError() + + @property + def update_custom_targeting_value( + self, + ) -> Callable[ + [custom_targeting_value_service.UpdateCustomTargetingValueRequest], + Union[ + custom_targeting_value_messages.CustomTargetingValue, + Awaitable[custom_targeting_value_messages.CustomTargetingValue], + ], + ]: + raise NotImplementedError() + + @property + def batch_update_custom_targeting_values( + self, + ) -> Callable[ + [custom_targeting_value_service.BatchUpdateCustomTargetingValuesRequest], + Union[ + custom_targeting_value_service.BatchUpdateCustomTargetingValuesResponse, + Awaitable[ + custom_targeting_value_service.BatchUpdateCustomTargetingValuesResponse + ], + ], + ]: + raise NotImplementedError() + + @property + def batch_activate_custom_targeting_values( + self, + ) -> Callable[ + [custom_targeting_value_service.BatchActivateCustomTargetingValuesRequest], + Union[ + custom_targeting_value_service.BatchActivateCustomTargetingValuesResponse, + Awaitable[ + custom_targeting_value_service.BatchActivateCustomTargetingValuesResponse + ], + ], + ]: + raise NotImplementedError() + + @property + def batch_deactivate_custom_targeting_values( + self, + ) -> Callable[ + [custom_targeting_value_service.BatchDeactivateCustomTargetingValuesRequest], + Union[ + custom_targeting_value_service.BatchDeactivateCustomTargetingValuesResponse, + Awaitable[ + custom_targeting_value_service.BatchDeactivateCustomTargetingValuesResponse + ], + ], + ]: + raise NotImplementedError() + @property def get_operation( self, diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/custom_targeting_value_service/transports/rest.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/custom_targeting_value_service/transports/rest.py index 6a92a7a6483a..b35db5fcaa27 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/custom_targeting_value_service/transports/rest.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/custom_targeting_value_service/transports/rest.py @@ -75,6 +75,46 @@ class CustomTargetingValueServiceRestInterceptor: .. code-block:: python class MyCustomCustomTargetingValueServiceInterceptor(CustomTargetingValueServiceRestInterceptor): + def pre_batch_activate_custom_targeting_values(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_activate_custom_targeting_values(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_batch_create_custom_targeting_values(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_create_custom_targeting_values(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_batch_deactivate_custom_targeting_values(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_deactivate_custom_targeting_values(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_batch_update_custom_targeting_values(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_update_custom_targeting_values(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_custom_targeting_value(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_custom_targeting_value(self, response): + logging.log(f"Received response: {response}") + return response + def pre_get_custom_targeting_value(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -91,12 +131,284 @@ def post_list_custom_targeting_values(self, response): logging.log(f"Received response: {response}") return response + def pre_update_custom_targeting_value(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_custom_targeting_value(self, response): + logging.log(f"Received response: {response}") + return response + transport = CustomTargetingValueServiceRestTransport(interceptor=MyCustomCustomTargetingValueServiceInterceptor()) client = CustomTargetingValueServiceClient(transport=transport) """ + def pre_batch_activate_custom_targeting_values( + self, + request: custom_targeting_value_service.BatchActivateCustomTargetingValuesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + custom_targeting_value_service.BatchActivateCustomTargetingValuesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_activate_custom_targeting_values + + Override in a subclass to manipulate the request or metadata + before they are sent to the CustomTargetingValueService server. + """ + return request, metadata + + def post_batch_activate_custom_targeting_values( + self, + response: custom_targeting_value_service.BatchActivateCustomTargetingValuesResponse, + ) -> custom_targeting_value_service.BatchActivateCustomTargetingValuesResponse: + """Post-rpc interceptor for batch_activate_custom_targeting_values + + DEPRECATED. Please use the `post_batch_activate_custom_targeting_values_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the CustomTargetingValueService server but before + it is returned to user code. This `post_batch_activate_custom_targeting_values` interceptor runs + before the `post_batch_activate_custom_targeting_values_with_metadata` interceptor. + """ + return response + + def post_batch_activate_custom_targeting_values_with_metadata( + self, + response: custom_targeting_value_service.BatchActivateCustomTargetingValuesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + custom_targeting_value_service.BatchActivateCustomTargetingValuesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for batch_activate_custom_targeting_values + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the CustomTargetingValueService server but before it is returned to user code. + + We recommend only using this `post_batch_activate_custom_targeting_values_with_metadata` + interceptor in new development instead of the `post_batch_activate_custom_targeting_values` interceptor. + When both interceptors are used, this `post_batch_activate_custom_targeting_values_with_metadata` interceptor runs after the + `post_batch_activate_custom_targeting_values` interceptor. The (possibly modified) response returned by + `post_batch_activate_custom_targeting_values` will be passed to + `post_batch_activate_custom_targeting_values_with_metadata`. + """ + return response, metadata + + def pre_batch_create_custom_targeting_values( + self, + request: custom_targeting_value_service.BatchCreateCustomTargetingValuesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + custom_targeting_value_service.BatchCreateCustomTargetingValuesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_create_custom_targeting_values + + Override in a subclass to manipulate the request or metadata + before they are sent to the CustomTargetingValueService server. + """ + return request, metadata + + def post_batch_create_custom_targeting_values( + self, + response: custom_targeting_value_service.BatchCreateCustomTargetingValuesResponse, + ) -> custom_targeting_value_service.BatchCreateCustomTargetingValuesResponse: + """Post-rpc interceptor for batch_create_custom_targeting_values + + DEPRECATED. Please use the `post_batch_create_custom_targeting_values_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the CustomTargetingValueService server but before + it is returned to user code. This `post_batch_create_custom_targeting_values` interceptor runs + before the `post_batch_create_custom_targeting_values_with_metadata` interceptor. + """ + return response + + def post_batch_create_custom_targeting_values_with_metadata( + self, + response: custom_targeting_value_service.BatchCreateCustomTargetingValuesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + custom_targeting_value_service.BatchCreateCustomTargetingValuesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for batch_create_custom_targeting_values + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the CustomTargetingValueService server but before it is returned to user code. + + We recommend only using this `post_batch_create_custom_targeting_values_with_metadata` + interceptor in new development instead of the `post_batch_create_custom_targeting_values` interceptor. + When both interceptors are used, this `post_batch_create_custom_targeting_values_with_metadata` interceptor runs after the + `post_batch_create_custom_targeting_values` interceptor. The (possibly modified) response returned by + `post_batch_create_custom_targeting_values` will be passed to + `post_batch_create_custom_targeting_values_with_metadata`. + """ + return response, metadata + + def pre_batch_deactivate_custom_targeting_values( + self, + request: custom_targeting_value_service.BatchDeactivateCustomTargetingValuesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + custom_targeting_value_service.BatchDeactivateCustomTargetingValuesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_deactivate_custom_targeting_values + + Override in a subclass to manipulate the request or metadata + before they are sent to the CustomTargetingValueService server. + """ + return request, metadata + + def post_batch_deactivate_custom_targeting_values( + self, + response: custom_targeting_value_service.BatchDeactivateCustomTargetingValuesResponse, + ) -> custom_targeting_value_service.BatchDeactivateCustomTargetingValuesResponse: + """Post-rpc interceptor for batch_deactivate_custom_targeting_values + + DEPRECATED. Please use the `post_batch_deactivate_custom_targeting_values_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the CustomTargetingValueService server but before + it is returned to user code. This `post_batch_deactivate_custom_targeting_values` interceptor runs + before the `post_batch_deactivate_custom_targeting_values_with_metadata` interceptor. + """ + return response + + def post_batch_deactivate_custom_targeting_values_with_metadata( + self, + response: custom_targeting_value_service.BatchDeactivateCustomTargetingValuesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + custom_targeting_value_service.BatchDeactivateCustomTargetingValuesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for batch_deactivate_custom_targeting_values + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the CustomTargetingValueService server but before it is returned to user code. + + We recommend only using this `post_batch_deactivate_custom_targeting_values_with_metadata` + interceptor in new development instead of the `post_batch_deactivate_custom_targeting_values` interceptor. + When both interceptors are used, this `post_batch_deactivate_custom_targeting_values_with_metadata` interceptor runs after the + `post_batch_deactivate_custom_targeting_values` interceptor. The (possibly modified) response returned by + `post_batch_deactivate_custom_targeting_values` will be passed to + `post_batch_deactivate_custom_targeting_values_with_metadata`. + """ + return response, metadata + + def pre_batch_update_custom_targeting_values( + self, + request: custom_targeting_value_service.BatchUpdateCustomTargetingValuesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + custom_targeting_value_service.BatchUpdateCustomTargetingValuesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_update_custom_targeting_values + + Override in a subclass to manipulate the request or metadata + before they are sent to the CustomTargetingValueService server. + """ + return request, metadata + + def post_batch_update_custom_targeting_values( + self, + response: custom_targeting_value_service.BatchUpdateCustomTargetingValuesResponse, + ) -> custom_targeting_value_service.BatchUpdateCustomTargetingValuesResponse: + """Post-rpc interceptor for batch_update_custom_targeting_values + + DEPRECATED. Please use the `post_batch_update_custom_targeting_values_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the CustomTargetingValueService server but before + it is returned to user code. This `post_batch_update_custom_targeting_values` interceptor runs + before the `post_batch_update_custom_targeting_values_with_metadata` interceptor. + """ + return response + + def post_batch_update_custom_targeting_values_with_metadata( + self, + response: custom_targeting_value_service.BatchUpdateCustomTargetingValuesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + custom_targeting_value_service.BatchUpdateCustomTargetingValuesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for batch_update_custom_targeting_values + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the CustomTargetingValueService server but before it is returned to user code. + + We recommend only using this `post_batch_update_custom_targeting_values_with_metadata` + interceptor in new development instead of the `post_batch_update_custom_targeting_values` interceptor. + When both interceptors are used, this `post_batch_update_custom_targeting_values_with_metadata` interceptor runs after the + `post_batch_update_custom_targeting_values` interceptor. The (possibly modified) response returned by + `post_batch_update_custom_targeting_values` will be passed to + `post_batch_update_custom_targeting_values_with_metadata`. + """ + return response, metadata + + def pre_create_custom_targeting_value( + self, + request: custom_targeting_value_service.CreateCustomTargetingValueRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + custom_targeting_value_service.CreateCustomTargetingValueRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_custom_targeting_value + + Override in a subclass to manipulate the request or metadata + before they are sent to the CustomTargetingValueService server. + """ + return request, metadata + + def post_create_custom_targeting_value( + self, response: custom_targeting_value_messages.CustomTargetingValue + ) -> custom_targeting_value_messages.CustomTargetingValue: + """Post-rpc interceptor for create_custom_targeting_value + + DEPRECATED. Please use the `post_create_custom_targeting_value_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the CustomTargetingValueService server but before + it is returned to user code. This `post_create_custom_targeting_value` interceptor runs + before the `post_create_custom_targeting_value_with_metadata` interceptor. + """ + return response + + def post_create_custom_targeting_value_with_metadata( + self, + response: custom_targeting_value_messages.CustomTargetingValue, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + custom_targeting_value_messages.CustomTargetingValue, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for create_custom_targeting_value + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the CustomTargetingValueService server but before it is returned to user code. + + We recommend only using this `post_create_custom_targeting_value_with_metadata` + interceptor in new development instead of the `post_create_custom_targeting_value` interceptor. + When both interceptors are used, this `post_create_custom_targeting_value_with_metadata` interceptor runs after the + `post_create_custom_targeting_value` interceptor. The (possibly modified) response returned by + `post_create_custom_targeting_value` will be passed to + `post_create_custom_targeting_value_with_metadata`. + """ + return response, metadata + def pre_get_custom_targeting_value( self, request: custom_targeting_value_service.GetCustomTargetingValueRequest, @@ -201,6 +513,58 @@ def post_list_custom_targeting_values_with_metadata( """ return response, metadata + def pre_update_custom_targeting_value( + self, + request: custom_targeting_value_service.UpdateCustomTargetingValueRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + custom_targeting_value_service.UpdateCustomTargetingValueRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_custom_targeting_value + + Override in a subclass to manipulate the request or metadata + before they are sent to the CustomTargetingValueService server. + """ + return request, metadata + + def post_update_custom_targeting_value( + self, response: custom_targeting_value_messages.CustomTargetingValue + ) -> custom_targeting_value_messages.CustomTargetingValue: + """Post-rpc interceptor for update_custom_targeting_value + + DEPRECATED. Please use the `post_update_custom_targeting_value_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the CustomTargetingValueService server but before + it is returned to user code. This `post_update_custom_targeting_value` interceptor runs + before the `post_update_custom_targeting_value_with_metadata` interceptor. + """ + return response + + def post_update_custom_targeting_value_with_metadata( + self, + response: custom_targeting_value_messages.CustomTargetingValue, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + custom_targeting_value_messages.CustomTargetingValue, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for update_custom_targeting_value + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the CustomTargetingValueService server but before it is returned to user code. + + We recommend only using this `post_update_custom_targeting_value_with_metadata` + interceptor in new development instead of the `post_update_custom_targeting_value` interceptor. + When both interceptors are used, this `post_update_custom_targeting_value_with_metadata` interceptor runs after the + `post_update_custom_targeting_value` interceptor. The (possibly modified) response returned by + `post_update_custom_targeting_value` will be passed to + `post_update_custom_targeting_value_with_metadata`. + """ + return response, metadata + def pre_cancel_operation( self, request: operations_pb2.CancelOperationRequest, @@ -345,13 +709,13 @@ def __init__( self._interceptor = interceptor or CustomTargetingValueServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _GetCustomTargetingValue( - _BaseCustomTargetingValueServiceRestTransport._BaseGetCustomTargetingValue, + class _BatchActivateCustomTargetingValues( + _BaseCustomTargetingValueServiceRestTransport._BaseBatchActivateCustomTargetingValues, CustomTargetingValueServiceRestStub, ): def __hash__(self): return hash( - "CustomTargetingValueServiceRestTransport.GetCustomTargetingValue" + "CustomTargetingValueServiceRestTransport.BatchActivateCustomTargetingValues" ) @staticmethod @@ -373,23 +737,25 @@ def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, ) return response def __call__( self, - request: custom_targeting_value_service.GetCustomTargetingValueRequest, + request: custom_targeting_value_service.BatchActivateCustomTargetingValuesRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> custom_targeting_value_messages.CustomTargetingValue: - r"""Call the get custom targeting - value method over HTTP. + ) -> custom_targeting_value_service.BatchActivateCustomTargetingValuesResponse: + r"""Call the batch activate custom + targeting values method over HTTP. Args: - request (~.custom_targeting_value_service.GetCustomTargetingValueRequest): - The request object. Request object for ``GetCustomTargetingValue`` method. + request (~.custom_targeting_value_service.BatchActivateCustomTargetingValuesRequest): + The request object. Request object for + ``BatchActivateCustomTargetingValues`` method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -399,21 +765,29 @@ def __call__( be of type `bytes`. Returns: - ~.custom_targeting_value_messages.CustomTargetingValue: - The ``CustomTargetingValue`` resource. + ~.custom_targeting_value_service.BatchActivateCustomTargetingValuesResponse: + Response object for + ``BatchActivateCustomTargetingValues`` method. + """ - http_options = _BaseCustomTargetingValueServiceRestTransport._BaseGetCustomTargetingValue._get_http_options() + http_options = _BaseCustomTargetingValueServiceRestTransport._BaseBatchActivateCustomTargetingValues._get_http_options() - request, metadata = self._interceptor.pre_get_custom_targeting_value( - request, metadata + request, metadata = ( + self._interceptor.pre_batch_activate_custom_targeting_values( + request, metadata + ) ) - transcoded_request = _BaseCustomTargetingValueServiceRestTransport._BaseGetCustomTargetingValue._get_transcoded_request( + transcoded_request = _BaseCustomTargetingValueServiceRestTransport._BaseBatchActivateCustomTargetingValues._get_transcoded_request( http_options, request ) + body = _BaseCustomTargetingValueServiceRestTransport._BaseBatchActivateCustomTargetingValues._get_request_body_json( + transcoded_request + ) + # Jsonify the query params - query_params = _BaseCustomTargetingValueServiceRestTransport._BaseGetCustomTargetingValue._get_query_params_json( + query_params = _BaseCustomTargetingValueServiceRestTransport._BaseBatchActivateCustomTargetingValues._get_query_params_json( transcoded_request ) @@ -435,7 +809,820 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.ads.admanager_v1.CustomTargetingValueServiceClient.GetCustomTargetingValue", + f"Sending request for google.ads.admanager_v1.CustomTargetingValueServiceClient.BatchActivateCustomTargetingValues", + extra={ + "serviceName": "google.ads.admanager.v1.CustomTargetingValueService", + "rpcName": "BatchActivateCustomTargetingValues", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = CustomTargetingValueServiceRestTransport._BatchActivateCustomTargetingValues._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = custom_targeting_value_service.BatchActivateCustomTargetingValuesResponse() + pb_resp = custom_targeting_value_service.BatchActivateCustomTargetingValuesResponse.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_activate_custom_targeting_values(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_batch_activate_custom_targeting_values_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = custom_targeting_value_service.BatchActivateCustomTargetingValuesResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.CustomTargetingValueServiceClient.batch_activate_custom_targeting_values", + extra={ + "serviceName": "google.ads.admanager.v1.CustomTargetingValueService", + "rpcName": "BatchActivateCustomTargetingValues", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _BatchCreateCustomTargetingValues( + _BaseCustomTargetingValueServiceRestTransport._BaseBatchCreateCustomTargetingValues, + CustomTargetingValueServiceRestStub, + ): + def __hash__(self): + return hash( + "CustomTargetingValueServiceRestTransport.BatchCreateCustomTargetingValues" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: custom_targeting_value_service.BatchCreateCustomTargetingValuesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> custom_targeting_value_service.BatchCreateCustomTargetingValuesResponse: + r"""Call the batch create custom + targeting values method over HTTP. + + Args: + request (~.custom_targeting_value_service.BatchCreateCustomTargetingValuesRequest): + The request object. Request object for ``BatchCreateCustomTargetingValues`` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.custom_targeting_value_service.BatchCreateCustomTargetingValuesResponse: + Response object for ``BatchCreateCustomTargetingValues`` + method. + + """ + + http_options = _BaseCustomTargetingValueServiceRestTransport._BaseBatchCreateCustomTargetingValues._get_http_options() + + request, metadata = ( + self._interceptor.pre_batch_create_custom_targeting_values( + request, metadata + ) + ) + transcoded_request = _BaseCustomTargetingValueServiceRestTransport._BaseBatchCreateCustomTargetingValues._get_transcoded_request( + http_options, request + ) + + body = _BaseCustomTargetingValueServiceRestTransport._BaseBatchCreateCustomTargetingValues._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseCustomTargetingValueServiceRestTransport._BaseBatchCreateCustomTargetingValues._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.CustomTargetingValueServiceClient.BatchCreateCustomTargetingValues", + extra={ + "serviceName": "google.ads.admanager.v1.CustomTargetingValueService", + "rpcName": "BatchCreateCustomTargetingValues", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = CustomTargetingValueServiceRestTransport._BatchCreateCustomTargetingValues._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = custom_targeting_value_service.BatchCreateCustomTargetingValuesResponse() + pb_resp = custom_targeting_value_service.BatchCreateCustomTargetingValuesResponse.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_create_custom_targeting_values(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_batch_create_custom_targeting_values_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = custom_targeting_value_service.BatchCreateCustomTargetingValuesResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.CustomTargetingValueServiceClient.batch_create_custom_targeting_values", + extra={ + "serviceName": "google.ads.admanager.v1.CustomTargetingValueService", + "rpcName": "BatchCreateCustomTargetingValues", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _BatchDeactivateCustomTargetingValues( + _BaseCustomTargetingValueServiceRestTransport._BaseBatchDeactivateCustomTargetingValues, + CustomTargetingValueServiceRestStub, + ): + def __hash__(self): + return hash( + "CustomTargetingValueServiceRestTransport.BatchDeactivateCustomTargetingValues" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: custom_targeting_value_service.BatchDeactivateCustomTargetingValuesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> ( + custom_targeting_value_service.BatchDeactivateCustomTargetingValuesResponse + ): + r"""Call the batch deactivate custom + targeting values method over HTTP. + + Args: + request (~.custom_targeting_value_service.BatchDeactivateCustomTargetingValuesRequest): + The request object. Request message for + ``BatchDeactivateCustomTargetingValues`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.custom_targeting_value_service.BatchDeactivateCustomTargetingValuesResponse: + Response object for + ``BatchDeactivateCustomTargetingValues`` method. + + """ + + http_options = _BaseCustomTargetingValueServiceRestTransport._BaseBatchDeactivateCustomTargetingValues._get_http_options() + + request, metadata = ( + self._interceptor.pre_batch_deactivate_custom_targeting_values( + request, metadata + ) + ) + transcoded_request = _BaseCustomTargetingValueServiceRestTransport._BaseBatchDeactivateCustomTargetingValues._get_transcoded_request( + http_options, request + ) + + body = _BaseCustomTargetingValueServiceRestTransport._BaseBatchDeactivateCustomTargetingValues._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseCustomTargetingValueServiceRestTransport._BaseBatchDeactivateCustomTargetingValues._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.CustomTargetingValueServiceClient.BatchDeactivateCustomTargetingValues", + extra={ + "serviceName": "google.ads.admanager.v1.CustomTargetingValueService", + "rpcName": "BatchDeactivateCustomTargetingValues", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = CustomTargetingValueServiceRestTransport._BatchDeactivateCustomTargetingValues._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = custom_targeting_value_service.BatchDeactivateCustomTargetingValuesResponse() + pb_resp = custom_targeting_value_service.BatchDeactivateCustomTargetingValuesResponse.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_deactivate_custom_targeting_values(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_batch_deactivate_custom_targeting_values_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = custom_targeting_value_service.BatchDeactivateCustomTargetingValuesResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.CustomTargetingValueServiceClient.batch_deactivate_custom_targeting_values", + extra={ + "serviceName": "google.ads.admanager.v1.CustomTargetingValueService", + "rpcName": "BatchDeactivateCustomTargetingValues", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _BatchUpdateCustomTargetingValues( + _BaseCustomTargetingValueServiceRestTransport._BaseBatchUpdateCustomTargetingValues, + CustomTargetingValueServiceRestStub, + ): + def __hash__(self): + return hash( + "CustomTargetingValueServiceRestTransport.BatchUpdateCustomTargetingValues" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: custom_targeting_value_service.BatchUpdateCustomTargetingValuesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> custom_targeting_value_service.BatchUpdateCustomTargetingValuesResponse: + r"""Call the batch update custom + targeting values method over HTTP. + + Args: + request (~.custom_targeting_value_service.BatchUpdateCustomTargetingValuesRequest): + The request object. Request object for ``BatchUpdateCustomTargetingValues`` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.custom_targeting_value_service.BatchUpdateCustomTargetingValuesResponse: + Response object for ``BatchUpdateCustomTargetingValues`` + method. + + """ + + http_options = _BaseCustomTargetingValueServiceRestTransport._BaseBatchUpdateCustomTargetingValues._get_http_options() + + request, metadata = ( + self._interceptor.pre_batch_update_custom_targeting_values( + request, metadata + ) + ) + transcoded_request = _BaseCustomTargetingValueServiceRestTransport._BaseBatchUpdateCustomTargetingValues._get_transcoded_request( + http_options, request + ) + + body = _BaseCustomTargetingValueServiceRestTransport._BaseBatchUpdateCustomTargetingValues._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseCustomTargetingValueServiceRestTransport._BaseBatchUpdateCustomTargetingValues._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.CustomTargetingValueServiceClient.BatchUpdateCustomTargetingValues", + extra={ + "serviceName": "google.ads.admanager.v1.CustomTargetingValueService", + "rpcName": "BatchUpdateCustomTargetingValues", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = CustomTargetingValueServiceRestTransport._BatchUpdateCustomTargetingValues._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = custom_targeting_value_service.BatchUpdateCustomTargetingValuesResponse() + pb_resp = custom_targeting_value_service.BatchUpdateCustomTargetingValuesResponse.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_update_custom_targeting_values(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_batch_update_custom_targeting_values_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = custom_targeting_value_service.BatchUpdateCustomTargetingValuesResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.CustomTargetingValueServiceClient.batch_update_custom_targeting_values", + extra={ + "serviceName": "google.ads.admanager.v1.CustomTargetingValueService", + "rpcName": "BatchUpdateCustomTargetingValues", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateCustomTargetingValue( + _BaseCustomTargetingValueServiceRestTransport._BaseCreateCustomTargetingValue, + CustomTargetingValueServiceRestStub, + ): + def __hash__(self): + return hash( + "CustomTargetingValueServiceRestTransport.CreateCustomTargetingValue" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: custom_targeting_value_service.CreateCustomTargetingValueRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> custom_targeting_value_messages.CustomTargetingValue: + r"""Call the create custom targeting + value method over HTTP. + + Args: + request (~.custom_targeting_value_service.CreateCustomTargetingValueRequest): + The request object. Request object for ``CreateCustomTargetingValue`` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.custom_targeting_value_messages.CustomTargetingValue: + The ``CustomTargetingValue`` resource. + """ + + http_options = _BaseCustomTargetingValueServiceRestTransport._BaseCreateCustomTargetingValue._get_http_options() + + request, metadata = self._interceptor.pre_create_custom_targeting_value( + request, metadata + ) + transcoded_request = _BaseCustomTargetingValueServiceRestTransport._BaseCreateCustomTargetingValue._get_transcoded_request( + http_options, request + ) + + body = _BaseCustomTargetingValueServiceRestTransport._BaseCreateCustomTargetingValue._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseCustomTargetingValueServiceRestTransport._BaseCreateCustomTargetingValue._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.CustomTargetingValueServiceClient.CreateCustomTargetingValue", + extra={ + "serviceName": "google.ads.admanager.v1.CustomTargetingValueService", + "rpcName": "CreateCustomTargetingValue", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = CustomTargetingValueServiceRestTransport._CreateCustomTargetingValue._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = custom_targeting_value_messages.CustomTargetingValue() + pb_resp = custom_targeting_value_messages.CustomTargetingValue.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_custom_targeting_value(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_create_custom_targeting_value_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + custom_targeting_value_messages.CustomTargetingValue.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.CustomTargetingValueServiceClient.create_custom_targeting_value", + extra={ + "serviceName": "google.ads.admanager.v1.CustomTargetingValueService", + "rpcName": "CreateCustomTargetingValue", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetCustomTargetingValue( + _BaseCustomTargetingValueServiceRestTransport._BaseGetCustomTargetingValue, + CustomTargetingValueServiceRestStub, + ): + def __hash__(self): + return hash( + "CustomTargetingValueServiceRestTransport.GetCustomTargetingValue" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: custom_targeting_value_service.GetCustomTargetingValueRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> custom_targeting_value_messages.CustomTargetingValue: + r"""Call the get custom targeting + value method over HTTP. + + Args: + request (~.custom_targeting_value_service.GetCustomTargetingValueRequest): + The request object. Request object for ``GetCustomTargetingValue`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.custom_targeting_value_messages.CustomTargetingValue: + The ``CustomTargetingValue`` resource. + """ + + http_options = _BaseCustomTargetingValueServiceRestTransport._BaseGetCustomTargetingValue._get_http_options() + + request, metadata = self._interceptor.pre_get_custom_targeting_value( + request, metadata + ) + transcoded_request = _BaseCustomTargetingValueServiceRestTransport._BaseGetCustomTargetingValue._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseCustomTargetingValueServiceRestTransport._BaseGetCustomTargetingValue._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.CustomTargetingValueServiceClient.GetCustomTargetingValue", extra={ "serviceName": "google.ads.admanager.v1.CustomTargetingValueService", "rpcName": "GetCustomTargetingValue", @@ -653,6 +1840,232 @@ def __call__( ) return resp + class _UpdateCustomTargetingValue( + _BaseCustomTargetingValueServiceRestTransport._BaseUpdateCustomTargetingValue, + CustomTargetingValueServiceRestStub, + ): + def __hash__(self): + return hash( + "CustomTargetingValueServiceRestTransport.UpdateCustomTargetingValue" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: custom_targeting_value_service.UpdateCustomTargetingValueRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> custom_targeting_value_messages.CustomTargetingValue: + r"""Call the update custom targeting + value method over HTTP. + + Args: + request (~.custom_targeting_value_service.UpdateCustomTargetingValueRequest): + The request object. Request object for ``UpdateCustomTargetingValue`` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.custom_targeting_value_messages.CustomTargetingValue: + The ``CustomTargetingValue`` resource. + """ + + http_options = _BaseCustomTargetingValueServiceRestTransport._BaseUpdateCustomTargetingValue._get_http_options() + + request, metadata = self._interceptor.pre_update_custom_targeting_value( + request, metadata + ) + transcoded_request = _BaseCustomTargetingValueServiceRestTransport._BaseUpdateCustomTargetingValue._get_transcoded_request( + http_options, request + ) + + body = _BaseCustomTargetingValueServiceRestTransport._BaseUpdateCustomTargetingValue._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseCustomTargetingValueServiceRestTransport._BaseUpdateCustomTargetingValue._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ads.admanager_v1.CustomTargetingValueServiceClient.UpdateCustomTargetingValue", + extra={ + "serviceName": "google.ads.admanager.v1.CustomTargetingValueService", + "rpcName": "UpdateCustomTargetingValue", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = CustomTargetingValueServiceRestTransport._UpdateCustomTargetingValue._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = custom_targeting_value_messages.CustomTargetingValue() + pb_resp = custom_targeting_value_messages.CustomTargetingValue.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_custom_targeting_value(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_update_custom_targeting_value_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + custom_targeting_value_messages.CustomTargetingValue.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ads.admanager_v1.CustomTargetingValueServiceClient.update_custom_targeting_value", + extra={ + "serviceName": "google.ads.admanager.v1.CustomTargetingValueService", + "rpcName": "UpdateCustomTargetingValue", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def batch_activate_custom_targeting_values( + self, + ) -> Callable[ + [custom_targeting_value_service.BatchActivateCustomTargetingValuesRequest], + custom_targeting_value_service.BatchActivateCustomTargetingValuesResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchActivateCustomTargetingValues( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def batch_create_custom_targeting_values( + self, + ) -> Callable[ + [custom_targeting_value_service.BatchCreateCustomTargetingValuesRequest], + custom_targeting_value_service.BatchCreateCustomTargetingValuesResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchCreateCustomTargetingValues( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def batch_deactivate_custom_targeting_values( + self, + ) -> Callable[ + [custom_targeting_value_service.BatchDeactivateCustomTargetingValuesRequest], + custom_targeting_value_service.BatchDeactivateCustomTargetingValuesResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchDeactivateCustomTargetingValues( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def batch_update_custom_targeting_values( + self, + ) -> Callable[ + [custom_targeting_value_service.BatchUpdateCustomTargetingValuesRequest], + custom_targeting_value_service.BatchUpdateCustomTargetingValuesResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchUpdateCustomTargetingValues( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def create_custom_targeting_value( + self, + ) -> Callable[ + [custom_targeting_value_service.CreateCustomTargetingValueRequest], + custom_targeting_value_messages.CustomTargetingValue, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateCustomTargetingValue( + self._session, self._host, self._interceptor + ) # type: ignore + @property def get_custom_targeting_value( self, @@ -679,6 +2092,19 @@ def list_custom_targeting_values( self._session, self._host, self._interceptor ) # type: ignore + @property + def update_custom_targeting_value( + self, + ) -> Callable[ + [custom_targeting_value_service.UpdateCustomTargetingValueRequest], + custom_targeting_value_messages.CustomTargetingValue, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateCustomTargetingValue( + self._session, self._host, self._interceptor + ) # type: ignore + @property def cancel_operation(self): return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/custom_targeting_value_service/transports/rest_base.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/custom_targeting_value_service/transports/rest_base.py index 801be0303914..55d8f8a86549 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/custom_targeting_value_service/transports/rest_base.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/custom_targeting_value_service/transports/rest_base.py @@ -93,6 +93,303 @@ def __init__( api_audience=api_audience, ) + class _BaseBatchActivateCustomTargetingValues: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=networks/*}/customTargetingValues:batchActivate", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = custom_targeting_value_service.BatchActivateCustomTargetingValuesRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCustomTargetingValueServiceRestTransport._BaseBatchActivateCustomTargetingValues._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseBatchCreateCustomTargetingValues: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=networks/*}/customTargetingValues:batchCreate", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = custom_targeting_value_service.BatchCreateCustomTargetingValuesRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCustomTargetingValueServiceRestTransport._BaseBatchCreateCustomTargetingValues._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseBatchDeactivateCustomTargetingValues: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=networks/*}/customTargetingValues:batchDeactivate", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = custom_targeting_value_service.BatchDeactivateCustomTargetingValuesRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCustomTargetingValueServiceRestTransport._BaseBatchDeactivateCustomTargetingValues._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseBatchUpdateCustomTargetingValues: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=networks/*}/customTargetingValues:batchUpdate", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = custom_targeting_value_service.BatchUpdateCustomTargetingValuesRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCustomTargetingValueServiceRestTransport._BaseBatchUpdateCustomTargetingValues._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateCustomTargetingValue: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=networks/*}/customTargetingValues", + "body": "custom_targeting_value", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ( + custom_targeting_value_service.CreateCustomTargetingValueRequest.pb( + request + ) + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCustomTargetingValueServiceRestTransport._BaseCreateCustomTargetingValue._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseGetCustomTargetingValue: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -203,6 +500,67 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseUpdateCustomTargetingValue: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{custom_targeting_value.name=networks/*/customTargetingValues/*}", + "body": "custom_targeting_value", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ( + custom_targeting_value_service.UpdateCustomTargetingValueRequest.pb( + request + ) + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCustomTargetingValueServiceRestTransport._BaseUpdateCustomTargetingValue._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseCancelOperation: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/device_capability_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/device_capability_service/client.py index e0fdd0a8d5fa..325844cf880b 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/device_capability_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/device_capability_service/client.py @@ -761,7 +761,7 @@ def get_device_capability( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> device_capability_messages.DeviceCapability: - r"""API to retrieve a ``DeviceCapability`` object. + r"""Retrieves a ``DeviceCapability`` object. .. code-block:: python @@ -871,7 +871,7 @@ def list_device_capabilities( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListDeviceCapabilitiesPager: - r"""API to retrieve a list of ``DeviceCapability`` objects. + r"""Lists ``DeviceCapability`` objects. .. code-block:: python diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/device_category_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/device_category_service/client.py index 008345c59ec5..9e4cf71a6620 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/device_category_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/device_category_service/client.py @@ -759,7 +759,7 @@ def get_device_category( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> device_category_messages.DeviceCategory: - r"""API to retrieve a ``DeviceCategory`` object. + r"""Retrieves a ``DeviceCategory`` object. .. code-block:: python @@ -869,7 +869,7 @@ def list_device_categories( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListDeviceCategoriesPager: - r"""API to retrieve a list of ``DeviceCategory`` objects. + r"""Lists ``DeviceCategory`` objects. .. code-block:: python diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/device_manufacturer_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/device_manufacturer_service/client.py index 44685ad443d3..ff30a38d8906 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/device_manufacturer_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/device_manufacturer_service/client.py @@ -763,7 +763,7 @@ def get_device_manufacturer( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> device_manufacturer_messages.DeviceManufacturer: - r"""API to retrieve a ``DeviceManufacturer`` object. + r"""Retrieves a ``DeviceManufacturer`` object. .. code-block:: python @@ -873,7 +873,7 @@ def list_device_manufacturers( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListDeviceManufacturersPager: - r"""API to retrieve a list of ``DeviceManufacturer`` objects. + r"""Lists ``DeviceManufacturer`` objects. .. code-block:: python diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/geo_target_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/geo_target_service/client.py index 9914356746b1..32019d59f323 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/geo_target_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/geo_target_service/client.py @@ -749,7 +749,7 @@ def get_geo_target( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> geo_target_messages.GeoTarget: - r"""API to retrieve a ``GeoTarget`` object. + r"""Retrieves a ``GeoTarget`` object. .. code-block:: python @@ -856,7 +856,7 @@ def list_geo_targets( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListGeoTargetsPager: - r"""API to retrieve a list of ``GeoTarget`` objects. + r"""Lists ``GeoTarget`` objects. .. code-block:: python diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/label_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/label_service/client.py index 837ed296cc08..c576b6c06e6b 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/label_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/label_service/client.py @@ -742,7 +742,7 @@ def get_label( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> label_messages.Label: - r"""API to retrieve a ``Label`` object. + r"""Retrieves a ``Label`` object. .. code-block:: python @@ -849,7 +849,7 @@ def list_labels( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListLabelsPager: - r"""API to retrieve a list of ``Label`` objects. + r"""Lists ``Label`` objects. .. code-block:: python @@ -972,7 +972,7 @@ def create_label( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> label_messages.Label: - r"""API to create a ``Label`` object. + r"""Creates a ``Label`` object. .. code-block:: python @@ -1091,7 +1091,7 @@ def batch_create_labels( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> label_service.BatchCreateLabelsResponse: - r"""API to batch create ``Label`` objects. + r"""Creates ``Label`` objects. .. code-block:: python @@ -1212,7 +1212,7 @@ def update_label( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> label_messages.Label: - r"""API to update a ``Label`` object. + r"""Updates a ``Label`` object. .. code-block:: python @@ -1336,7 +1336,7 @@ def batch_update_labels( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> label_service.BatchUpdateLabelsResponse: - r"""API to batch update ``Label`` objects. + r"""Batch updates ``Label`` objects. .. code-block:: python @@ -1456,7 +1456,7 @@ def batch_activate_labels( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> label_service.BatchActivateLabelsResponse: - r"""API to activate ``Label`` objects. + r"""Activates ``Label`` objects. .. code-block:: python @@ -1572,7 +1572,7 @@ def batch_deactivate_labels( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> label_service.BatchDeactivateLabelsResponse: - r"""API to deactivate ``Label`` objects. + r"""Deactivates ``Label`` objects. .. code-block:: python diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/line_item_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/line_item_service/client.py index 4a7918931803..a5e67bad839a 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/line_item_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/line_item_service/client.py @@ -61,17 +61,37 @@ _LOGGER = std_logging.getLogger(__name__) +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore import google.type.money_pb2 as money_pb2 # type: ignore from google.longrunning import operations_pb2 # type: ignore from google.ads.admanager_v1.services.line_item_service import pagers from google.ads.admanager_v1.types import ( + applied_label, + child_content_eligibility_enum, + creative_placeholder, + creative_targeting, custom_field_value, + custom_pacing_curve, + delivery_enums, + delivery_indicator, + environment_type_enum, + exclusion_scope_enum, + frequency_cap, goal, + grp_settings, + line_item_allowed_format_enum, + line_item_deal_info, + line_item_delivery_forecast_source_enum, + line_item_discount, line_item_enums, line_item_messages, line_item_service, + line_item_stats, + skippable_ad_type_enum, + targeting, + third_party_measurement_settings, ) from .transports.base import DEFAULT_CLIENT_INFO, LineItemServiceTransport @@ -232,6 +252,197 @@ def transport(self) -> LineItemServiceTransport: """ return self._transport + @staticmethod + def ad_unit_path( + network_code: str, + ad_unit: str, + ) -> str: + """Returns a fully-qualified ad_unit string.""" + return "networks/{network_code}/adUnits/{ad_unit}".format( + network_code=network_code, + ad_unit=ad_unit, + ) + + @staticmethod + def parse_ad_unit_path(path: str) -> Dict[str, str]: + """Parses a ad_unit path into its component segments.""" + m = re.match(r"^networks/(?P.+?)/adUnits/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def application_path( + network_code: str, + application: str, + ) -> str: + """Returns a fully-qualified application string.""" + return "networks/{network_code}/applications/{application}".format( + network_code=network_code, + application=application, + ) + + @staticmethod + def parse_application_path(path: str) -> Dict[str, str]: + """Parses a application path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/applications/(?P.+?)$", path + ) + return m.groupdict() if m else {} + + @staticmethod + def audience_segment_path( + network_code: str, + audience_segment: str, + ) -> str: + """Returns a fully-qualified audience_segment string.""" + return "networks/{network_code}/audienceSegments/{audience_segment}".format( + network_code=network_code, + audience_segment=audience_segment, + ) + + @staticmethod + def parse_audience_segment_path(path: str) -> Dict[str, str]: + """Parses a audience_segment path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/audienceSegments/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def bandwidth_group_path( + network_code: str, + bandwidth_group: str, + ) -> str: + """Returns a fully-qualified bandwidth_group string.""" + return "networks/{network_code}/bandwidthGroups/{bandwidth_group}".format( + network_code=network_code, + bandwidth_group=bandwidth_group, + ) + + @staticmethod + def parse_bandwidth_group_path(path: str) -> Dict[str, str]: + """Parses a bandwidth_group path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/bandwidthGroups/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def browser_path( + network_code: str, + browser: str, + ) -> str: + """Returns a fully-qualified browser string.""" + return "networks/{network_code}/browsers/{browser}".format( + network_code=network_code, + browser=browser, + ) + + @staticmethod + def parse_browser_path(path: str) -> Dict[str, str]: + """Parses a browser path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/browsers/(?P.+?)$", path + ) + return m.groupdict() if m else {} + + @staticmethod + def browser_language_path( + network_code: str, + browser_language: str, + ) -> str: + """Returns a fully-qualified browser_language string.""" + return "networks/{network_code}/browserLanguages/{browser_language}".format( + network_code=network_code, + browser_language=browser_language, + ) + + @staticmethod + def parse_browser_language_path(path: str) -> Dict[str, str]: + """Parses a browser_language path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/browserLanguages/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def cms_metadata_value_path( + network_code: str, + cms_metadata_value: str, + ) -> str: + """Returns a fully-qualified cms_metadata_value string.""" + return "networks/{network_code}/cmsMetadataValues/{cms_metadata_value}".format( + network_code=network_code, + cms_metadata_value=cms_metadata_value, + ) + + @staticmethod + def parse_cms_metadata_value_path(path: str) -> Dict[str, str]: + """Parses a cms_metadata_value path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/cmsMetadataValues/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def company_path( + network_code: str, + company: str, + ) -> str: + """Returns a fully-qualified company string.""" + return "networks/{network_code}/companies/{company}".format( + network_code=network_code, + company=company, + ) + + @staticmethod + def parse_company_path(path: str) -> Dict[str, str]: + """Parses a company path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/companies/(?P.+?)$", path + ) + return m.groupdict() if m else {} + + @staticmethod + def content_path( + network_code: str, + content: str, + ) -> str: + """Returns a fully-qualified content string.""" + return "networks/{network_code}/content/{content}".format( + network_code=network_code, + content=content, + ) + + @staticmethod + def parse_content_path(path: str) -> Dict[str, str]: + """Parses a content path into its component segments.""" + m = re.match(r"^networks/(?P.+?)/content/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def content_bundle_path( + network_code: str, + content_bundle: str, + ) -> str: + """Returns a fully-qualified content_bundle string.""" + return "networks/{network_code}/contentBundles/{content_bundle}".format( + network_code=network_code, + content_bundle=content_bundle, + ) + + @staticmethod + def parse_content_bundle_path(path: str) -> Dict[str, str]: + """Parses a content_bundle path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/contentBundles/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def custom_field_path( network_code: str, @@ -251,6 +462,146 @@ def parse_custom_field_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def custom_targeting_key_path( + network_code: str, + custom_targeting_key: str, + ) -> str: + """Returns a fully-qualified custom_targeting_key string.""" + return ( + "networks/{network_code}/customTargetingKeys/{custom_targeting_key}".format( + network_code=network_code, + custom_targeting_key=custom_targeting_key, + ) + ) + + @staticmethod + def parse_custom_targeting_key_path(path: str) -> Dict[str, str]: + """Parses a custom_targeting_key path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/customTargetingKeys/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def custom_targeting_value_path( + network_code: str, + custom_targeting_value: str, + ) -> str: + """Returns a fully-qualified custom_targeting_value string.""" + return "networks/{network_code}/customTargetingValues/{custom_targeting_value}".format( + network_code=network_code, + custom_targeting_value=custom_targeting_value, + ) + + @staticmethod + def parse_custom_targeting_value_path(path: str) -> Dict[str, str]: + """Parses a custom_targeting_value path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/customTargetingValues/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def device_capability_path( + network_code: str, + device_capability: str, + ) -> str: + """Returns a fully-qualified device_capability string.""" + return "networks/{network_code}/deviceCapabilities/{device_capability}".format( + network_code=network_code, + device_capability=device_capability, + ) + + @staticmethod + def parse_device_capability_path(path: str) -> Dict[str, str]: + """Parses a device_capability path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/deviceCapabilities/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def device_category_path( + network_code: str, + device_category: str, + ) -> str: + """Returns a fully-qualified device_category string.""" + return "networks/{network_code}/deviceCategories/{device_category}".format( + network_code=network_code, + device_category=device_category, + ) + + @staticmethod + def parse_device_category_path(path: str) -> Dict[str, str]: + """Parses a device_category path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/deviceCategories/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def device_manufacturer_path( + network_code: str, + device_manufacturer: str, + ) -> str: + """Returns a fully-qualified device_manufacturer string.""" + return ( + "networks/{network_code}/deviceManufacturers/{device_manufacturer}".format( + network_code=network_code, + device_manufacturer=device_manufacturer, + ) + ) + + @staticmethod + def parse_device_manufacturer_path(path: str) -> Dict[str, str]: + """Parses a device_manufacturer path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/deviceManufacturers/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def geo_target_path( + network_code: str, + geo_target: str, + ) -> str: + """Returns a fully-qualified geo_target string.""" + return "networks/{network_code}/geoTargets/{geo_target}".format( + network_code=network_code, + geo_target=geo_target, + ) + + @staticmethod + def parse_geo_target_path(path: str) -> Dict[str, str]: + """Parses a geo_target path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/geoTargets/(?P.+?)$", path + ) + return m.groupdict() if m else {} + + @staticmethod + def label_path( + network_code: str, + label: str, + ) -> str: + """Returns a fully-qualified label string.""" + return "networks/{network_code}/labels/{label}".format( + network_code=network_code, + label=label, + ) + + @staticmethod + def parse_label_path(path: str) -> Dict[str, str]: + """Parses a label path into its component segments.""" + m = re.match(r"^networks/(?P.+?)/labels/(?P